xref: /netbsd-src/bin/cp/cp.c (revision a5847cc334d9a7029f6352b847e9e8d71a0f9e0c)
1 /* $NetBSD: cp.c,v 1.57 2011/08/18 08:11:58 manu 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.57 2011/08/18 08:11:58 manu 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, lflag, 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, "HLNPRfailprv")) != -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 'l':
144 			lflag = 1;
145 			break;
146 		case 'p':
147 			pflag = 1;
148 			break;
149 		case 'r':
150 			rflag = 1;
151 			break;
152 		case 'v':
153 			vflag = 1;
154 			break;
155 		case '?':
156 		default:
157 			usage();
158 			/* NOTREACHED */
159 		}
160 	argc -= optind;
161 	argv += optind;
162 
163 	if (argc < 2)
164 		usage();
165 
166 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
167 	if (rflag) {
168 		if (Rflag) {
169 			errx(EXIT_FAILURE,
170 		    "the -R and -r options may not be specified together.");
171 			/* NOTREACHED */
172 		}
173 		if (Hflag || Lflag || Pflag) {
174 			errx(EXIT_FAILURE,
175 	"the -H, -L, and -P options may not be specified with the -r option.");
176 			/* NOTREACHED */
177 		}
178 		fts_options &= ~FTS_PHYSICAL;
179 		fts_options |= FTS_LOGICAL;
180 	}
181 
182 	if (Rflag) {
183 		if (Hflag)
184 			fts_options |= FTS_COMFOLLOW;
185 		if (Lflag) {
186 			fts_options &= ~FTS_PHYSICAL;
187 			fts_options |= FTS_LOGICAL;
188 		}
189 	} else if (!Pflag) {
190 		fts_options &= ~FTS_PHYSICAL;
191 		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
192 	}
193 
194 	myuid = getuid();
195 
196 	/* Copy the umask for explicit mode setting. */
197 	myumask = umask(0);
198 	(void)umask(myumask);
199 
200 	/* Save the target base in "to". */
201 	target = argv[--argc];
202 	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
203 		errx(EXIT_FAILURE, "%s: name too long", target);
204 	to.p_end = to.p_path + strlen(to.p_path);
205 	have_trailing_slash = (to.p_end[-1] == '/');
206 	if (have_trailing_slash)
207 		STRIP_TRAILING_SLASH(to);
208 	to.target_end = to.p_end;
209 
210 	/* Set end of argument list for fts(3). */
211 	argv[argc] = NULL;
212 
213 	/*
214 	 * Cp has two distinct cases:
215 	 *
216 	 * cp [-R] source target
217 	 * cp [-R] source1 ... sourceN directory
218 	 *
219 	 * In both cases, source can be either a file or a directory.
220 	 *
221 	 * In (1), the target becomes a copy of the source. That is, if the
222 	 * source is a file, the target will be a file, and likewise for
223 	 * directories.
224 	 *
225 	 * In (2), the real target is not directory, but "directory/source".
226 	 */
227 	if (Pflag)
228 		r = lstat(to.p_path, &to_stat);
229 	else
230 		r = stat(to.p_path, &to_stat);
231 	if (r == -1 && errno != ENOENT) {
232 		err(EXIT_FAILURE, "%s", to.p_path);
233 		/* NOTREACHED */
234 	}
235 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
236 		/*
237 		 * Case (1).  Target is not a directory.
238 		 */
239 		if (argc > 1)
240 			usage();
241 		/*
242 		 * Need to detect the case:
243 		 *	cp -R dir foo
244 		 * Where dir is a directory and foo does not exist, where
245 		 * we want pathname concatenations turned on but not for
246 		 * the initial mkdir().
247 		 */
248 		if (r == -1) {
249 			if (rflag || (Rflag && (Lflag || Hflag)))
250 				r = stat(*argv, &tmp_stat);
251 			else
252 				r = lstat(*argv, &tmp_stat);
253 			if (r == -1) {
254 				err(EXIT_FAILURE, "%s", *argv);
255 				/* NOTREACHED */
256 			}
257 
258 			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
259 				type = DIR_TO_DNE;
260 			else
261 				type = FILE_TO_FILE;
262 		} else
263 			type = FILE_TO_FILE;
264 
265 		if (have_trailing_slash && type == FILE_TO_FILE) {
266 			if (r == -1)
267 				errx(1, "directory %s does not exist",
268 				     to.p_path);
269 			else
270 				errx(1, "%s is not a directory", to.p_path);
271 		}
272 	} else {
273 		/*
274 		 * Case (2).  Target is a directory.
275 		 */
276 		type = FILE_TO_DIR;
277 	}
278 
279 	/*
280 	 * make "cp -rp src/ dst" behave like "cp -rp src dst" not
281 	 * like "cp -rp src/. dst"
282 	 */
283 	for (src = argv; *src; src++) {
284 		size_t len = strlen(*src);
285 		while (len-- > 1 && (*src)[len] == '/')
286 			(*src)[len] = '\0';
287 	}
288 
289 	exit(copy(argv, type, fts_options));
290 	/* NOTREACHED */
291 }
292 
293 static int dnestack[MAXPATHLEN]; /* unlikely we'll have more nested dirs */
294 static ssize_t dnesp;
295 static void
296 pushdne(int dne)
297 {
298 
299 	dnestack[dnesp++] = dne;
300 	assert(dnesp < MAXPATHLEN);
301 }
302 
303 static int
304 popdne(void)
305 {
306 	int rv;
307 
308 	rv = dnestack[--dnesp];
309 	assert(dnesp >= 0);
310 	return rv;
311 }
312 
313 int
314 copy(char *argv[], enum op type, int fts_options)
315 {
316 	struct stat to_stat;
317 	FTS *ftsp;
318 	FTSENT *curr;
319 	int base, dne, sval;
320 	int this_failed, any_failed;
321 	size_t nlen;
322 	char *p, *target_mid;
323 
324 	base = 0;	/* XXX gcc -Wuninitialized (see comment below) */
325 
326 	if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
327 		err(EXIT_FAILURE, "%s", argv[0]);
328 		/* NOTREACHED */
329 	for (any_failed = 0; (curr = fts_read(ftsp)) != NULL;) {
330 		this_failed = 0;
331 		switch (curr->fts_info) {
332 		case FTS_NS:
333 		case FTS_DNR:
334 		case FTS_ERR:
335 			warnx("%s: %s", curr->fts_path,
336 					strerror(curr->fts_errno));
337 			this_failed = any_failed = 1;
338 			continue;
339 		case FTS_DC:			/* Warn, continue. */
340 			warnx("%s: directory causes a cycle", curr->fts_path);
341 			this_failed = any_failed = 1;
342 			continue;
343 		}
344 
345 		/*
346 		 * If we are in case (2) or (3) above, we need to append the
347                  * source name to the target name.
348                  */
349 		if (type != FILE_TO_FILE) {
350 			if ((curr->fts_namelen +
351 			    to.target_end - to.p_path + 1) > MAXPATHLEN) {
352 				warnx("%s/%s: name too long (not copied)",
353 						to.p_path, curr->fts_name);
354 				this_failed = any_failed = 1;
355 				continue;
356 			}
357 
358 			/*
359 			 * Need to remember the roots of traversals to create
360 			 * correct pathnames.  If there's a directory being
361 			 * copied to a non-existent directory, e.g.
362 			 *	cp -R a/dir noexist
363 			 * the resulting path name should be noexist/foo, not
364 			 * noexist/dir/foo (where foo is a file in dir), which
365 			 * is the case where the target exists.
366 			 *
367 			 * Also, check for "..".  This is for correct path
368 			 * concatentation for paths ending in "..", e.g.
369 			 *	cp -R .. /tmp
370 			 * Paths ending in ".." are changed to ".".  This is
371 			 * tricky, but seems the easiest way to fix the problem.
372 			 *
373 			 * XXX
374 			 * Since the first level MUST be FTS_ROOTLEVEL, base
375 			 * is always initialized.
376 			 */
377 			if (curr->fts_level == FTS_ROOTLEVEL) {
378 				if (type != DIR_TO_DNE) {
379 					p = strrchr(curr->fts_path, '/');
380 					base = (p == NULL) ? 0 :
381 					    (int)(p - curr->fts_path + 1);
382 
383 					if (!strcmp(&curr->fts_path[base],
384 					    ".."))
385 						base += 1;
386 				} else
387 					base = curr->fts_pathlen;
388 			}
389 
390 			p = &curr->fts_path[base];
391 			nlen = curr->fts_pathlen - base;
392 			target_mid = to.target_end;
393 			if (*p != '/' && target_mid[-1] != '/')
394 				*target_mid++ = '/';
395 			*target_mid = 0;
396 
397 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
398 				warnx("%s%s: name too long (not copied)",
399 				    to.p_path, p);
400 				this_failed = any_failed = 1;
401 				continue;
402 			}
403 			(void)strncat(target_mid, p, nlen);
404 			to.p_end = target_mid + nlen;
405 			*to.p_end = 0;
406 			STRIP_TRAILING_SLASH(to);
407 		}
408 
409 		sval = Pflag ? lstat(to.p_path, &to_stat) : stat(to.p_path, &to_stat);
410 		/* Not an error but need to remember it happened */
411 		if (sval == -1)
412 			dne = 1;
413 		else {
414 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
415 			    to_stat.st_ino == curr->fts_statp->st_ino) {
416 				warnx("%s and %s are identical (not copied).",
417 				    to.p_path, curr->fts_path);
418 				this_failed = any_failed = 1;
419 				if (S_ISDIR(curr->fts_statp->st_mode))
420 					(void)fts_set(ftsp, curr, FTS_SKIP);
421 				continue;
422 			}
423 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
424 			    S_ISDIR(to_stat.st_mode)) {
425 		warnx("cannot overwrite directory %s with non-directory %s",
426 				    to.p_path, curr->fts_path);
427 				this_failed = any_failed = 1;
428 				continue;
429 			}
430 			dne = 0;
431 		}
432 
433 		switch (curr->fts_statp->st_mode & S_IFMT) {
434 		case S_IFLNK:
435 			/* Catch special case of a non dangling symlink */
436 			if((fts_options & FTS_LOGICAL) ||
437 			   ((fts_options & FTS_COMFOLLOW) && curr->fts_level == 0)) {
438 				if (copy_file(curr, dne))
439 					this_failed = any_failed = 1;
440 			} else {
441 				if (copy_link(curr, !dne))
442 					this_failed = any_failed = 1;
443 			}
444 			break;
445 		case S_IFDIR:
446 			if (!Rflag && !rflag) {
447 				if (curr->fts_info == FTS_D)
448 					warnx("%s is a directory (not copied).",
449 					    curr->fts_path);
450 				(void)fts_set(ftsp, curr, FTS_SKIP);
451 				this_failed = any_failed = 1;
452 				break;
453 			}
454 
455                         /*
456                          * Directories get noticed twice:
457                          *  In the first pass, create it if needed.
458                          *  In the second pass, after the children have been copied, set the permissions.
459                          */
460 			if (curr->fts_info == FTS_D) /* First pass */
461 			{
462 				/*
463 				 * If the directory doesn't exist, create the new
464 				 * one with the from file mode plus owner RWX bits,
465 				 * modified by the umask.  Trade-off between being
466 				 * able to write the directory (if from directory is
467 				 * 555) and not causing a permissions race.  If the
468 				 * umask blocks owner writes, we fail..
469 				 */
470 				pushdne(dne);
471 				if (dne) {
472 					if (mkdir(to.p_path,
473 					    curr->fts_statp->st_mode | S_IRWXU) < 0)
474 						err(EXIT_FAILURE, "%s",
475 						    to.p_path);
476 						/* NOTREACHED */
477 				} else if (!S_ISDIR(to_stat.st_mode)) {
478 					errno = ENOTDIR;
479 					err(EXIT_FAILURE, "%s",
480 						to.p_path);
481 					/* NOTREACHED */
482 				}
483 			}
484 			else if (curr->fts_info == FTS_DP) /* Second pass */
485 			{
486 	                        /*
487 				 * If not -p and directory didn't exist, set it to be
488 				 * the same as the from directory, umodified by the
489                         	 * umask; arguably wrong, but it's been that way
490                         	 * forever.
491 				 */
492 				if (pflag && setfile(curr->fts_statp, 0))
493 					this_failed = any_failed = 1;
494 				else if ((dne = popdne()))
495 					(void)chmod(to.p_path,
496 					    curr->fts_statp->st_mode);
497 			}
498 			else
499 			{
500 				warnx("directory %s encountered when not expected.",
501 				    curr->fts_path);
502 				this_failed = any_failed = 1;
503 				break;
504 			}
505 
506 			break;
507 		case S_IFBLK:
508 		case S_IFCHR:
509 			if (Rflag) {
510 				if (copy_special(curr->fts_statp, !dne))
511 					this_failed = any_failed = 1;
512 			} else
513 				if (copy_file(curr, dne))
514 					this_failed = any_failed = 1;
515 			break;
516 		case S_IFIFO:
517 			if (Rflag) {
518 				if (copy_fifo(curr->fts_statp, !dne))
519 					this_failed = any_failed = 1;
520 			} else
521 				if (copy_file(curr, dne))
522 					this_failed = any_failed = 1;
523 			break;
524 		default:
525 			if (copy_file(curr, dne))
526 				this_failed = any_failed = 1;
527 			break;
528 		}
529 		if (vflag && !this_failed)
530 			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
531 	}
532 	if (errno) {
533 		err(EXIT_FAILURE, "fts_read");
534 		/* NOTREACHED */
535 	}
536 	(void)fts_close(ftsp);
537 	return (any_failed);
538 }
539