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