xref: /dragonfly/bin/cp/cp.c (revision 92fe556d)
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. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * Cp copies source files to target files.
35  *
36  * The global PATH_T structure "to" always contains the path to the
37  * current target file.  Since fts(3) does not change directories,
38  * this path can be either absolute or dot-relative.
39  *
40  * The basic algorithm is to initialize "to" and use fts(3) to traverse
41  * the file hierarchy rooted in the argument list.  A trivial case is the
42  * case of 'cp file1 file2'.  The more interesting case is the case of
43  * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
44  * path (relative to the root of the traversal) is appended to dir (stored
45  * in "to") to form the final target path.
46  */
47 
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 
51 #include <err.h>
52 #include <errno.h>
53 #include <fts.h>
54 #include <limits.h>
55 #include <signal.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 
61 #include "extern.h"
62 
63 #define	STRIP_TRAILING_SLASH(p) {					\
64         while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
65                 *--(p).p_end = 0;					\
66 }
67 
68 #if defined(__FreeBSD__) || defined(__DragonFly__)
69 #define	FTS_CONST const
70 #else
71 #define	FTS_CONST
72 #endif
73 
74 static char emptystring[] = "";
75 
76 PATH_T to = { to.p_path, emptystring, "" };
77 
78 int fflag, iflag, lflag, nflag, pflag, vflag;
79 static int Rflag, rflag;
80 volatile sig_atomic_t info;
81 
82 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
83 
84 static int copy(char *[], enum op, int);
85 static int mastercmp (const FTSENT *FTS_CONST *, const FTSENT *FTS_CONST *);
86 #ifdef SIGINFO
87 static void siginfo (int);
88 #endif
89 
90 int
91 main(int argc, char *argv[])
92 {
93 	struct stat to_stat, tmp_stat;
94 	enum op type;
95 	int Hflag, Lflag, Pflag, ch, fts_options, r, have_trailing_slash;
96 	char *target;
97 
98 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
99 	Hflag = Lflag = Pflag = 0;
100 	while ((ch = getopt(argc, argv, "HLPRafilnprvx")) != -1)
101 		switch (ch) {
102 		case 'H':
103 			Hflag = 1;
104 			Lflag = Pflag = 0;
105 			break;
106 		case 'L':
107 			Lflag = 1;
108 			Hflag = Pflag = 0;
109 			break;
110 		case 'P':
111 			Pflag = 1;
112 			Hflag = Lflag = 0;
113 			break;
114 		case 'R':
115 			Rflag = 1;
116 			break;
117 		case 'a':
118 			Pflag = 1;
119 			pflag = 1;
120 			Rflag = 1;
121 			Hflag = Lflag = 0;
122 			break;
123 		case 'f':
124 			fflag = 1;
125 			iflag = nflag = 0;
126 			break;
127 		case 'i':
128 			iflag = 1;
129 			fflag = nflag = 0;
130 			break;
131 		case 'l':
132 			lflag = 1;
133 			break;
134 		case 'n':
135 			nflag = 1;
136 			fflag = iflag = 0;
137 			break;
138 		case 'p':
139 			pflag = 1;
140 			break;
141 		case 'r':
142 			rflag = Lflag = 1;
143 			Hflag = Pflag = 0;
144 			break;
145 		case 'v':
146 			vflag = 1;
147 			break;
148 		case 'x':
149 			fts_options |= FTS_XDEV;
150 			break;
151 		default:
152 			usage();
153 			break;
154 		}
155 	argc -= optind;
156 	argv += optind;
157 
158 	if (argc < 2)
159 		usage();
160 
161 	if (Rflag && rflag)
162 		errx(1, "the -R and -r options may not be specified together");
163 	if (rflag)
164 		Rflag = 1;
165 	if (Rflag) {
166 		if (Hflag)
167 			fts_options |= FTS_COMFOLLOW;
168 		if (Lflag) {
169 			fts_options &= ~FTS_PHYSICAL;
170 			fts_options |= FTS_LOGICAL;
171 		}
172 	} else {
173 		fts_options &= ~FTS_PHYSICAL;
174 		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
175 	}
176 #ifdef SIGINFO
177 	signal(SIGINFO, siginfo);
178 #endif
179 
180 	/* Save the target base in "to". */
181 	target = argv[--argc];
182 	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
183 		errx(1, "%s: name too long", target);
184 	to.p_end = to.p_path + strlen(to.p_path);
185 	if (to.p_path == to.p_end) {
186 		*to.p_end++ = '.';
187 		*to.p_end = 0;
188 	}
189 	have_trailing_slash = (to.p_end[-1] == '/');
190 	if (have_trailing_slash)
191 		STRIP_TRAILING_SLASH(to);
192 	to.target_end = to.p_end;
193 
194 	/* Set end of argument list for fts(3). */
195 	argv[argc] = NULL;
196 
197 	/*
198 	 * Cp has two distinct cases:
199 	 *
200 	 * cp [-R] source target
201 	 * cp [-R] source1 ... sourceN directory
202 	 *
203 	 * In both cases, source can be either a file or a directory.
204 	 *
205 	 * In (1), the target becomes a copy of the source. That is, if the
206 	 * source is a file, the target will be a file, and likewise for
207 	 * directories.
208 	 *
209 	 * In (2), the real target is not directory, but "directory/source".
210 	 */
211 	r = stat(to.p_path, &to_stat);
212 	if (r == -1 && errno != ENOENT)
213 		err(1, "%s", to.p_path);
214 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
215 		/*
216 		 * Case (1).  Target is not a directory.
217 		 */
218 		if (argc > 1)
219 			errx(1, "%s is not a directory", to.p_path);
220 
221 		/*
222 		 * Need to detect the case:
223 		 *	cp -R dir foo
224 		 * Where dir is a directory and foo does not exist, where
225 		 * we want pathname concatenations turned on but not for
226 		 * the initial mkdir().
227 		 */
228 		if (r == -1) {
229 			if (Rflag && (Lflag || Hflag))
230 				stat(*argv, &tmp_stat);
231 			else
232 				lstat(*argv, &tmp_stat);
233 
234 			if (S_ISDIR(tmp_stat.st_mode) && Rflag)
235 				type = DIR_TO_DNE;
236 			else
237 				type = FILE_TO_FILE;
238 		} else
239 			type = FILE_TO_FILE;
240 
241 		if (have_trailing_slash && type == FILE_TO_FILE) {
242 			if (r == -1)
243 				errx(1, "directory %s does not exist",
244 				     to.p_path);
245 			else
246 				errx(1, "%s is not a directory", to.p_path);
247 		}
248 	} else
249 		/*
250 		 * Case (2).  Target is a directory.
251 		 */
252 		type = FILE_TO_DIR;
253 
254 	exit (copy(argv, type, fts_options));
255 }
256 
257 static int
258 copy(char *argv[], enum op type, int fts_options)
259 {
260 	struct stat to_stat;
261 	FTS *ftsp;
262 	FTSENT *curr;
263 	int base = 0, dne, badcp, rval;
264 	size_t nlen;
265 	char *p, *target_mid;
266 	mode_t mask, mode;
267 
268 	/*
269 	 * Keep an inverted copy of the umask, for use in correcting
270 	 * permissions on created directories when not using -p.
271 	 */
272 	mask = ~umask(0777);
273 	umask(~mask);
274 
275 	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
276 		err(1, "fts_open");
277 	for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
278 		switch (curr->fts_info) {
279 		case FTS_NS:
280 		case FTS_DNR:
281 		case FTS_ERR:
282 			warnx("%s: %s",
283 			    curr->fts_path, strerror(curr->fts_errno));
284 			rval = 1;
285 			continue;
286 		case FTS_DC:			/* Warn, continue. */
287 			warnx("%s: directory causes a cycle", curr->fts_path);
288 			rval = 1;
289 			continue;
290 		default:
291 			;
292 		}
293 
294 		/*
295 		 * If we are in case (2) or (3) above, we need to append the
296 		 * source name to the target name.
297 		 */
298 		if (type != FILE_TO_FILE) {
299 			/*
300 			 * Need to remember the roots of traversals to create
301 			 * correct pathnames.  If there's a directory being
302 			 * copied to a non-existent directory, e.g.
303 			 *	cp -R a/dir noexist
304 			 * the resulting path name should be noexist/foo, not
305 			 * noexist/dir/foo (where foo is a file in dir), which
306 			 * is the case where the target exists.
307 			 *
308 			 * Also, check for "..".  This is for correct path
309 			 * concatenation for paths ending in "..", e.g.
310 			 *	cp -R .. /tmp
311 			 * Paths ending in ".." are changed to ".".  This is
312 			 * tricky, but seems the easiest way to fix the problem.
313 			 *
314 			 * XXX
315 			 * Since the first level MUST be FTS_ROOTLEVEL, base
316 			 * is always initialized.
317 			 */
318 			if (curr->fts_level == FTS_ROOTLEVEL) {
319 				if (type != DIR_TO_DNE) {
320 					p = strrchr(curr->fts_path, '/');
321 					base = (p == NULL) ? 0 :
322 					    (int)(p - curr->fts_path + 1);
323 
324 					if (!strcmp(&curr->fts_path[base],
325 					    ".."))
326 						base += 1;
327 				} else
328 					base = curr->fts_pathlen;
329 			}
330 
331 			p = &curr->fts_path[base];
332 			nlen = curr->fts_pathlen - base;
333 			target_mid = to.target_end;
334 			if (*p != '/' && target_mid[-1] != '/')
335 				*target_mid++ = '/';
336 			*target_mid = 0;
337 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
338 				warnx("%s%s: name too long (not copied)",
339 				    to.p_path, p);
340 				rval = 1;
341 				continue;
342 			}
343 			strncat(target_mid, p, nlen);
344 			to.p_end = target_mid + nlen;
345 			*to.p_end = 0;
346 			STRIP_TRAILING_SLASH(to);
347 		}
348 
349 		if (curr->fts_info == FTS_DP) {
350 			/*
351 			 * We are nearly finished with this directory.  If we
352 			 * didn't actually copy it, or otherwise don't need to
353 			 * change its attributes, then we are done.
354 			 */
355 			if (!curr->fts_number)
356 				continue;
357 			/*
358 			 * If -p is in effect, set all the attributes.
359 			 * Otherwise, set the correct permissions, limited
360 			 * by the umask.  Optimise by avoiding a chmod()
361 			 * if possible (which is usually the case if we
362 			 * made the directory).  Note that mkdir() does not
363 			 * honour setuid, setgid and sticky bits, but we
364 			 * normally want to preserve them on directories.
365 			 */
366 			if (pflag) {
367 				if (setfile(curr->fts_statp, -1))
368 				    rval = 1;
369 			} else {
370 				mode = curr->fts_statp->st_mode;
371 				if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
372 				    ((mode | S_IRWXU) & mask) != (mode & mask))
373 					if (chmod(to.p_path, mode & mask) != 0){
374 						warn("chmod: %s", to.p_path);
375 						rval = 1;
376 					}
377 			}
378 			continue;
379 		}
380 
381 		/* Not an error but need to remember it happened */
382 		if (stat(to.p_path, &to_stat) == -1)
383 			dne = 1;
384 		else {
385 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
386 			    to_stat.st_ino == curr->fts_statp->st_ino) {
387 				warnx("%s and %s are identical (not copied).",
388 				    to.p_path, curr->fts_path);
389 				rval = 1;
390 				if (S_ISDIR(curr->fts_statp->st_mode))
391 					fts_set(ftsp, curr, FTS_SKIP);
392 				continue;
393 			}
394 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
395 			    S_ISDIR(to_stat.st_mode)) {
396 				warnx("cannot overwrite directory %s with "
397 				    "non-directory %s",
398 				    to.p_path, curr->fts_path);
399 				rval = 1;
400 				continue;
401 			}
402 			dne = 0;
403 		}
404 
405 		switch (curr->fts_statp->st_mode & S_IFMT) {
406 		case S_IFLNK:
407 			/* Catch special case of a non-dangling symlink */
408 			if ((fts_options & FTS_LOGICAL) ||
409 			    ((fts_options & FTS_COMFOLLOW) &&
410 			    curr->fts_level == 0)) {
411 				if (copy_file(curr, dne))
412 					badcp = rval = 1;
413 			} else {
414 				if (copy_link(curr, !dne))
415 					badcp = rval = 1;
416 			}
417 			break;
418 		case S_IFDIR:
419 			if (!Rflag) {
420 				warnx("%s is a directory (not copied).",
421 				    curr->fts_path);
422 				fts_set(ftsp, curr, FTS_SKIP);
423 				badcp = rval = 1;
424 				break;
425 			}
426 			/*
427 			 * If the directory doesn't exist, create the new
428 			 * one with the from file mode plus owner RWX bits,
429 			 * modified by the umask.  Trade-off between being
430 			 * able to write the directory (if from directory is
431 			 * 555) and not causing a permissions race.  If the
432 			 * umask blocks owner writes, we fail..
433 			 */
434 			if (dne) {
435 				if (mkdir(to.p_path,
436 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
437 					err(1, "%s", to.p_path);
438 			} else if (!S_ISDIR(to_stat.st_mode)) {
439 				errno = ENOTDIR;
440 				err(1, "%s", to.p_path);
441 			}
442 			/*
443 			 * Arrange to correct directory attributes later
444 			 * (in the post-order phase) if this is a new
445 			 * directory, or if the -p flag is in effect.
446 			 */
447 			curr->fts_number = pflag || dne;
448 			break;
449 		case S_IFBLK:
450 		case S_IFCHR:
451 			if (Rflag) {
452 				if (copy_special(curr->fts_statp, !dne))
453 					badcp = rval = 1;
454 			} else {
455 				if (copy_file(curr, dne))
456 					badcp = rval = 1;
457 			}
458 			break;
459 		case S_IFSOCK:
460 			warnx("%s is a socket (not copied).",
461 				    curr->fts_path);
462 			break;
463 		case S_IFIFO:
464 			if (Rflag) {
465 				if (copy_fifo(curr->fts_statp, !dne))
466 					badcp = rval = 1;
467 			} else {
468 				if (copy_file(curr, dne))
469 					badcp = rval = 1;
470 			}
471 			break;
472 		default:
473 			if (copy_file(curr, dne))
474 				badcp = rval = 1;
475 			break;
476 		}
477 		if (vflag && !badcp)
478 			printf("%s -> %s\n", curr->fts_path, to.p_path);
479 	}
480 	if (errno)
481 		err(1, "fts_read");
482 	fts_close(ftsp);
483 	return (rval);
484 }
485 
486 /*
487  * mastercmp --
488  *	The comparison function for the copy order.  The order is to copy
489  *	non-directory files before directory files.  The reason for this
490  *	is because files tend to be in the same cylinder group as their
491  *	parent directory, whereas directories tend not to be.  Copying the
492  *	files first reduces seeking.
493  */
494 static int
495 mastercmp(const FTSENT *FTS_CONST *a, const FTSENT *FTS_CONST *b)
496 {
497 	int a_info, b_info;
498 
499 	a_info = (*a)->fts_info;
500 	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
501 		return (0);
502 	b_info = (*b)->fts_info;
503 	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
504 		return (0);
505 	if (a_info == FTS_D)
506 		return (-1);
507 	if (b_info == FTS_D)
508 		return (1);
509 	return (0);
510 }
511 
512 #ifdef SIGINFO
513 static void
514 siginfo(int sig __unused)
515 {
516 	info = 1;
517 }
518 #endif
519