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