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