xref: /freebsd/bin/cp/cp.c (revision e627b39baccd1ec9129690167cf5e6d860509655)
1 /*
2  * Copyright (c) 1988, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * David Hitz of Auspex Systems Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	$Id: cp.c,v 1.9 1996/02/19 05:56:33 pst Exp $
37  */
38 
39 #ifndef lint
40 static char copyright[] =
41 "@(#) Copyright (c) 1988, 1993, 1994\n\
42 	The Regents of the University of California.  All rights reserved.\n";
43 #endif /* not lint */
44 
45 #ifndef lint
46 static char sccsid[] = "@(#)cp.c	8.2 (Berkeley) 4/1/94";
47 #endif /* not lint */
48 
49 /*
50  * Cp copies source files to target files.
51  *
52  * The global PATH_T structure "to" always contains the path to the
53  * current target file.  Since fts(3) does not change directories,
54  * this path can be either absolute or dot-realative.
55  *
56  * The basic algorithm is to initialize "to" and use fts(3) to traverse
57  * the file hierarchy rooted in the argument list.  A trivial case is the
58  * case of 'cp file1 file2'.  The more interesting case is the case of
59  * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
60  * path (relative to the root of the traversal) is appended to dir (stored
61  * in "to") to form the final target path.
62  */
63 
64 #include <sys/param.h>
65 #include <sys/stat.h>
66 #include <sys/mman.h>
67 #include <sys/time.h>
68 
69 #include <dirent.h>
70 #include <err.h>
71 #include <errno.h>
72 #include <fcntl.h>
73 #include <fts.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <unistd.h>
78 
79 #include "extern.h"
80 
81 #define	STRIP_TRAILING_SLASH(p) {					\
82         while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
83                 *--(p).p_end = 0;					\
84 }
85 
86 PATH_T to = { to.p_path, "" };
87 
88 uid_t myuid;
89 int Rflag, iflag, pflag, rflag, fflag;
90 int myumask;
91 
92 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
93 
94 int copy __P((char *[], enum op, int));
95 int mastercmp __P((const FTSENT **, const FTSENT **));
96 
97 int
98 main(argc, argv)
99 	int argc;
100 	char *argv[];
101 {
102 	struct stat to_stat, tmp_stat;
103 	enum op type;
104 	int Hflag, Lflag, Pflag, ch, fts_options, r;
105 	char *target;
106 
107 	Hflag = Lflag = Pflag = 0;
108 	while ((ch = getopt(argc, argv, "HLPRfipr")) != EOF)
109 		switch (ch) {
110 		case 'H':
111 			Hflag = 1;
112 			Lflag = Pflag = 0;
113 			break;
114 		case 'L':
115 			Lflag = 1;
116 			Hflag = Pflag = 0;
117 			break;
118 		case 'P':
119 			Pflag = 1;
120 			Hflag = Lflag = 0;
121 			break;
122 		case 'R':
123 			Rflag = 1;
124 			break;
125 		case 'f':
126 			fflag = 1;
127 			iflag = 0;
128 			break;
129 		case 'i':
130 			iflag = 1;
131 			fflag = 0;
132 			break;
133 		case 'p':
134 			pflag = 1;
135 			break;
136 		case 'r':
137 			rflag = 1;
138 			break;
139 		default:
140 			usage();
141 			break;
142 		}
143 	argc -= optind;
144 	argv += optind;
145 
146 	if (argc < 2)
147 		usage();
148 
149 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
150 	if (rflag) {
151 		if (Rflag)
152 			errx(1,
153 		    "the -R and -r options may not be specified together.");
154 		if (Hflag || Lflag || Pflag)
155 			errx(1,
156 	"the -H, -L, and -P options may not be specified with the -r option.");
157 		fts_options &= ~FTS_PHYSICAL;
158 		fts_options |= FTS_LOGICAL;
159 	}
160 	if (Rflag) {
161 		if (Hflag)
162 			fts_options |= FTS_COMFOLLOW;
163 		if (Lflag) {
164 			fts_options &= ~FTS_PHYSICAL;
165 			fts_options |= FTS_LOGICAL;
166 		}
167 	} else {
168 		fts_options &= ~FTS_PHYSICAL;
169 		fts_options |= FTS_LOGICAL;
170 	}
171 
172 	myuid = getuid();
173 
174 	/* Copy the umask for explicit mode setting. */
175 	myumask = umask(0);
176 	(void)umask(myumask);
177 
178 	/* Save the target base in "to". */
179 	target = argv[--argc];
180 	if (strlen(target) > MAXPATHLEN)
181 		errx(1, "%s: name too long", target);
182 	(void)strcpy(to.p_path, target);
183 	to.p_end = to.p_path + strlen(to.p_path);
184         if (to.p_path == to.p_end) {
185 		*to.p_end++ = '.';
186 		*to.p_end = 0;
187 	}
188         STRIP_TRAILING_SLASH(to);
189 	to.target_end = to.p_end;
190 
191 	/* Set end of argument list for fts(3). */
192 	argv[argc] = NULL;
193 
194 	/*
195 	 * Cp has two distinct cases:
196 	 *
197 	 * cp [-R] source target
198 	 * cp [-R] source1 ... sourceN directory
199 	 *
200 	 * In both cases, source can be either a file or a directory.
201 	 *
202 	 * In (1), the target becomes a copy of the source. That is, if the
203 	 * source is a file, the target will be a file, and likewise for
204 	 * directories.
205 	 *
206 	 * In (2), the real target is not directory, but "directory/source".
207 	 */
208 	r = stat(to.p_path, &to_stat);
209 	if (r == -1 && errno != ENOENT)
210 		err(1, "%s", to.p_path);
211 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
212 		/*
213 		 * Case (1).  Target is not a directory.
214 		 */
215 		if (argc > 1) {
216 			usage();
217 			exit(1);
218 		}
219 		/*
220 		 * Need to detect the case:
221 		 *	cp -R dir foo
222 		 * Where dir is a directory and foo does not exist, where
223 		 * we want pathname concatenations turned on but not for
224 		 * the initial mkdir().
225 		 */
226 		if (r == -1) {
227 			if (rflag || (Rflag && (Lflag || Hflag)))
228 				stat(*argv, &tmp_stat);
229 			else
230 				lstat(*argv, &tmp_stat);
231 
232 			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
233 				type = DIR_TO_DNE;
234 			else
235 				type = FILE_TO_FILE;
236 		} else
237 			type = FILE_TO_FILE;
238 	} else
239 		/*
240 		 * Case (2).  Target is a directory.
241 		 */
242 		type = FILE_TO_DIR;
243 
244 	exit (copy(argv, type, fts_options));
245 }
246 
247 int
248 copy(argv, type, fts_options)
249 	char *argv[];
250 	enum op type;
251 	int fts_options;
252 {
253 	struct stat to_stat;
254 	FTS *ftsp;
255 	FTSENT *curr;
256 	int base, dne, nlen, rval;
257 	char *p, *target_mid;
258 
259 	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
260 		err(1, NULL);
261 	for (rval = 0; (curr = fts_read(ftsp)) != NULL;) {
262 		switch (curr->fts_info) {
263 		case FTS_NS:
264 		case FTS_ERR:
265 			warnx("%s: %s",
266 			    curr->fts_path, strerror(curr->fts_errno));
267 			rval = 1;
268 			continue;
269 		case FTS_DC:			/* Warn, continue. */
270 			warnx("%s: directory causes a cycle", curr->fts_path);
271 			rval = 1;
272 			continue;
273 		case FTS_DP:			/* Ignore, continue. */
274 			continue;
275 		}
276 
277 		/*
278 		 * If we are in case (2) or (3) above, we need to append the
279                  * source name to the target name.
280                  */
281 		if (type != FILE_TO_FILE) {
282 			/*
283 			 * Need to remember the roots of traversals to create
284 			 * correct pathnames.  If there's a directory being
285 			 * copied to a non-existent directory, e.g.
286 			 *	cp -R a/dir noexist
287 			 * the resulting path name should be noexist/foo, not
288 			 * noexist/dir/foo (where foo is a file in dir), which
289 			 * is the case where the target exists.
290 			 *
291 			 * Also, check for "..".  This is for correct path
292 			 * concatentation for paths ending in "..", e.g.
293 			 *	cp -R .. /tmp
294 			 * Paths ending in ".." are changed to ".".  This is
295 			 * tricky, but seems the easiest way to fix the problem.
296 			 *
297 			 * XXX
298 			 * Since the first level MUST be FTS_ROOTLEVEL, base
299 			 * is always initialized.
300 			 */
301 			if (curr->fts_level == FTS_ROOTLEVEL)
302 				if (type != DIR_TO_DNE) {
303 					p = strrchr(curr->fts_path, '/');
304 					base = (p == NULL) ? 0 :
305 					    (int)(p - curr->fts_path + 1);
306 
307 					if (!strcmp(&curr->fts_path[base],
308 					    ".."))
309 						base += 1;
310 				} else
311 					base = curr->fts_pathlen;
312 
313 			p = &curr->fts_path[base];
314 			nlen = curr->fts_pathlen - base;
315 			target_mid = to.target_end;
316 			if (*p != '/' && target_mid[-1] != '/')
317 				*target_mid++ = '/';
318 			*target_mid = 0;
319 			if (target_mid - to.p_path + nlen > MAXPATHLEN) {
320 				warnx("%s%s: name too long (not copied)",
321 				    to.p_path, p);
322 				rval = 1;
323 				continue;
324 			}
325 			(void)strncat(target_mid, p, nlen);
326 			to.p_end = target_mid + nlen;
327 			*to.p_end = 0;
328 			STRIP_TRAILING_SLASH(to);
329 		}
330 
331 		/* Not an error but need to remember it happened */
332 		if (stat(to.p_path, &to_stat) == -1)
333 			dne = 1;
334 		else {
335 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
336 			    to_stat.st_ino == curr->fts_statp->st_ino) {
337 				warnx("%s and %s are identical (not copied).",
338 				    to.p_path, curr->fts_path);
339 				rval = 1;
340 				if (S_ISDIR(curr->fts_statp->st_mode))
341 					(void)fts_set(ftsp, curr, FTS_SKIP);
342 				continue;
343 			}
344 			dne = 0;
345 		}
346 
347 		switch (curr->fts_statp->st_mode & S_IFMT) {
348 		case S_IFLNK:
349 			if (copy_link(curr, !dne))
350 				rval = 1;
351 			break;
352 		case S_IFDIR:
353 			if (!Rflag && !rflag) {
354 				warnx("%s is a directory (not copied).",
355 				    curr->fts_path);
356 				(void)fts_set(ftsp, curr, FTS_SKIP);
357 				rval = 1;
358 				break;
359 			}
360 			/*
361 			 * If the directory doesn't exist, create the new
362 			 * one with the from file mode plus owner RWX bits,
363 			 * modified by the umask.  Trade-off between being
364 			 * able to write the directory (if from directory is
365 			 * 555) and not causing a permissions race.  If the
366 			 * umask blocks owner writes, we fail..
367 			 */
368 			if (dne) {
369 				if (mkdir(to.p_path,
370 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
371 					err(1, "%s", to.p_path);
372 			} else if (!S_ISDIR(to_stat.st_mode)) {
373 				errno = ENOTDIR;
374 				err(1, "%s", to.p_path);
375 			}
376 			/*
377 			 * If not -p and directory didn't exist, set it to be
378 			 * the same as the from directory, umodified by the
379                          * umask; arguably wrong, but it's been that way
380                          * forever.
381 			 */
382 			if (pflag && setfile(curr->fts_statp, 0))
383 				rval = 1;
384 			else if (dne)
385 				(void)chmod(to.p_path,
386 				    curr->fts_statp->st_mode);
387 			break;
388 		case S_IFBLK:
389 		case S_IFCHR:
390 			if (Rflag) {
391 				if (copy_special(curr->fts_statp, !dne))
392 					rval = 1;
393 			} else {
394 				if (copy_file(curr, dne))
395 					rval = 1;
396 			}
397 			break;
398 		case S_IFIFO:
399 			if (Rflag) {
400 				if (copy_fifo(curr->fts_statp, !dne))
401 					rval = 1;
402 			} else {
403 				if (copy_file(curr, dne))
404 					rval = 1;
405 			}
406 			break;
407 		default:
408 			if (copy_file(curr, dne))
409 				rval = 1;
410 			break;
411 		}
412 	}
413 	if (errno)
414 		err(1, "fts_read");
415 	return (rval);
416 }
417 
418 /*
419  * mastercmp --
420  *	The comparison function for the copy order.  The order is to copy
421  *	non-directory files before directory files.  The reason for this
422  *	is because files tend to be in the same cylinder group as their
423  *	parent directory, whereas directories tend not to be.  Copying the
424  *	files first reduces seeking.
425  */
426 int
427 mastercmp(a, b)
428 	const FTSENT **a, **b;
429 {
430 	int a_info, b_info;
431 
432 	a_info = (*a)->fts_info;
433 	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
434 		return (0);
435 	b_info = (*b)->fts_info;
436 	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
437 		return (0);
438 	if (a_info == FTS_D)
439 		return (-1);
440 	if (b_info == FTS_D)
441 		return (1);
442 	return (0);
443 }
444