xref: /openbsd/bin/cp/cp.c (revision d485f761)
1 /*	$OpenBSD: cp.c,v 1.17 2001/06/25 04:35:31 art Exp $	*/
2 /*	$NetBSD: cp.c,v 1.14 1995/09/07 06:14:51 jtc Exp $	*/
3 
4 /*
5  * Copyright (c) 1988, 1993, 1994
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * David Hitz of Auspex Systems Inc.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgment:
21  *	This product includes software developed by the University of
22  *	California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  */
39 
40 #ifndef lint
41 static char 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 static char rcsid[] = "$OpenBSD: cp.c,v 1.17 2001/06/25 04:35:31 art 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 #include <sys/mman.h>
72 #include <sys/time.h>
73 
74 #include <dirent.h>
75 #include <err.h>
76 #include <errno.h>
77 #include <fcntl.h>
78 #include <fts.h>
79 #include <locale.h>
80 #include <stdio.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <unistd.h>
84 
85 #include "extern.h"
86 
87 #define	STRIP_TRAILING_SLASH(p) {					\
88 	while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
89 		*--(p).p_end = '\0';					\
90 }
91 
92 PATH_T to = { to.p_path, "" };
93 
94 uid_t myuid;
95 int Rflag, fflag, iflag, pflag, rflag;
96 int myumask;
97 
98 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
99 
100 int copy __P((char *[], enum op, int));
101 int mastercmp __P((const FTSENT **, const FTSENT **));
102 char *find_last_component __P((char *));
103 
104 int
105 main(argc, argv)
106 	int argc;
107 	char *argv[];
108 {
109 	struct stat to_stat, tmp_stat;
110 	enum op type;
111 	int Hflag, Lflag, Pflag, ch, fts_options, r;
112 	char *target;
113 
114 	(void)setlocale(LC_ALL, "");
115 
116 	Hflag = Lflag = Pflag = Rflag = 0;
117 	while ((ch = getopt(argc, argv, "HLPRfipr")) != -1)
118 		switch (ch) {
119 		case 'H':
120 			Hflag = 1;
121 			Lflag = Pflag = 0;
122 			break;
123 		case 'L':
124 			Lflag = 1;
125 			Hflag = Pflag = 0;
126 			break;
127 		case 'P':
128 			Pflag = 1;
129 			Hflag = Lflag = 0;
130 			break;
131 		case 'R':
132 			Rflag = 1;
133 			break;
134 		case 'f':
135 			fflag = 1;
136 			iflag = 0;
137 			break;
138 		case 'i':
139 			iflag = isatty(fileno(stdin));
140 			fflag = 0;
141 			break;
142 		case 'p':
143 			pflag = 1;
144 			break;
145 		case 'r':
146 			rflag = 1;
147 			break;
148 		default:
149 			usage();
150 			break;
151 		}
152 	argc -= optind;
153 	argv += optind;
154 
155 	if (argc < 2)
156 		usage();
157 
158 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
159 	if (rflag) {
160 		if (Rflag)
161 			errx(1,
162 		    "the -R and -r options may not be specified together.");
163 		if (Hflag || Lflag || Pflag)
164 			errx(1,
165 	"the -H, -L, and -P options may not be specified with the -r option.");
166 		fts_options &= ~FTS_PHYSICAL;
167 		fts_options |= FTS_LOGICAL;
168 	}
169 	if (Rflag) {
170 		if (Hflag)
171 			fts_options |= FTS_COMFOLLOW;
172 		if (Lflag) {
173 			fts_options &= ~FTS_PHYSICAL;
174 			fts_options |= FTS_LOGICAL;
175 		}
176 	} else {
177 		fts_options &= ~FTS_PHYSICAL;
178 		fts_options |= FTS_LOGICAL;
179 	}
180 
181 	myuid = getuid();
182 
183 	/* Copy the umask for explicit mode setting. */
184 	myumask = umask(0);
185 	(void)umask(myumask);
186 
187 	/* Save the target base in "to". */
188 	target = argv[--argc];
189 	if (strlen(target) >= sizeof(to.p_path))
190 		errx(1, "%s: name too long", target);
191 	(void)strcpy(to.p_path, target);
192 	to.p_end = to.p_path + strlen(to.p_path);
193 	if (to.p_path == to.p_end) {
194 		*to.p_end++ = '.';
195 		*to.p_end = '\0';
196 	}
197 	to.target_end = to.p_end;
198 
199 	/* Set end of argument list for fts(3). */
200 	argv[argc] = NULL;
201 
202 	/*
203 	 * Cp has two distinct cases:
204 	 *
205 	 * cp [-R] source target
206 	 * cp [-R] source1 ... sourceN directory
207 	 *
208 	 * In both cases, source can be either a file or a directory.
209 	 *
210 	 * In (1), the target becomes a copy of the source. That is, if the
211 	 * source is a file, the target will be a file, and likewise for
212 	 * directories.
213 	 *
214 	 * In (2), the real target is not directory, but "directory/source".
215 	 */
216 	r = stat(to.p_path, &to_stat);
217 	if (r == -1 && errno != ENOENT)
218 		err(1, "%s", to.p_path);
219 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
220 		/*
221 		 * Case (1).  Target is not a directory.
222 		 */
223 		if (argc > 1)
224 			usage();
225 		/*
226 		 * Need to detect the case:
227 		 *	cp -R dir foo
228 		 * Where dir is a directory and foo does not exist, where
229 		 * we want pathname concatenations turned on but not for
230 		 * the initial mkdir().
231 		 */
232 		if (r == -1) {
233 			if (rflag || (Rflag && (Lflag || Hflag)))
234 				stat(*argv, &tmp_stat);
235 			else
236 				lstat(*argv, &tmp_stat);
237 
238 			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
239 				type = DIR_TO_DNE;
240 			else
241 				type = FILE_TO_FILE;
242 		} else
243 			type = FILE_TO_FILE;
244 	} else
245 		/*
246 		 * Case (2).  Target is a directory.
247 		 */
248 		type = FILE_TO_DIR;
249 
250 	exit (copy(argv, type, fts_options));
251 }
252 
253 char *
254 find_last_component(path)
255 	char *path;
256 
257 {
258 	char *p;
259 
260 	if ((p = strrchr(path, '/')) == NULL)
261 		p = path;
262 	else {
263 		/* Special case foo/ */
264 	        if (!*(p+1)) {
265 			while ((p >= path) &&
266 			       *p == '/')
267 				p--;
268 
269 			while ((p >= path) &&
270 			       *p != '/')
271 				p--;
272 		}
273 
274 		p++;
275 	}
276 
277 	return (p);
278 }
279 
280 int
281 copy(argv, type, fts_options)
282 	char *argv[];
283 	enum op type;
284 	int fts_options;
285 {
286 	struct stat to_stat;
287 	FTS *ftsp;
288 	FTSENT *curr;
289 	int base, dne, nlen, rval;
290 	char *p, *target_mid;
291 #ifdef lint
292 	base = 0;
293 #endif
294 	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
295 		err(1, NULL);
296 	for (rval = 0; (curr = fts_read(ftsp)) != NULL;) {
297 		switch (curr->fts_info) {
298 		case FTS_NS:
299 		case FTS_ERR:
300 			warnx("%s: %s",
301 			    curr->fts_path, strerror(curr->fts_errno));
302 			rval = 1;
303 			continue;
304 		case FTS_DC:
305 			warnx("%s: directory causes a cycle", curr->fts_path);
306 			rval = 1;
307 			continue;
308 		}
309 
310 		/*
311 		 * If we are in case (2) or (3) above, we need to append the
312 		 * source name to the target name.
313 		 */
314 		if (type != FILE_TO_FILE) {
315 			/*
316 			 * Need to remember the roots of traversals to create
317 			 * correct pathnames.  If there's a directory being
318 			 * copied to a non-existent directory, e.g.
319 			 *	cp -R a/dir noexist
320 			 * the resulting path name should be noexist/foo, not
321 			 * noexist/dir/foo (where foo is a file in dir), which
322 			 * is the case where the target exists.
323 			 *
324 			 * Also, check for "..".  This is for correct path
325 			 * concatenation for paths ending in "..", e.g.
326 			 *	cp -R .. /tmp
327 			 * Paths ending in ".." are changed to ".".  This is
328 			 * tricky, but seems the easiest way to fix the problem.
329 			 *
330 			 * XXX
331 			 * Since the first level MUST be FTS_ROOTLEVEL, base
332 			 * is always initialized.
333 			 */
334 			if (curr->fts_level == FTS_ROOTLEVEL) {
335 				if (type != DIR_TO_DNE) {
336 					p = find_last_component(curr->fts_path);
337 					base = p - curr->fts_path;
338 
339 					if (!strcmp(&curr->fts_path[base],
340 					    ".."))
341 						base += 1;
342 				} else
343 					base = curr->fts_pathlen;
344 			}
345 
346 			p = &curr->fts_path[base];
347 			nlen = curr->fts_pathlen - base;
348 			target_mid = to.target_end;
349 			if (*p != '/' && target_mid[-1] != '/')
350 				*target_mid++ = '/';
351 			*target_mid = '\0';
352 			if (target_mid - to.p_path + nlen >= MAXPATHLEN) {
353 				warnx("%s%s: name too long (not copied)",
354 				    to.p_path, p);
355 				rval = 1;
356 				continue;
357 			}
358 			(void)strncat(target_mid, p, nlen);
359 			to.p_end = target_mid + nlen;
360 			*to.p_end = '\0';
361 		}
362 
363 		/* Not an error but need to remember it happened */
364 		if (stat(to.p_path, &to_stat) == -1) {
365 			if (curr->fts_info == FTS_DP)
366 				continue;
367 			dne = 1;
368 		} else {
369 			/*
370 			 * For -p mode, we need to reset the directory
371 			 * times in the post-order pass since the times
372 			 * will have been changed when we added files to
373 			 * the directory in the pre-order pass.
374 			 */
375 			if (curr->fts_info == FTS_DP) {
376 				if (pflag && S_ISDIR(to_stat.st_mode)) {
377 					struct timeval tv[2];
378 
379 					TIMESPEC_TO_TIMEVAL(&tv[0],
380 					    &curr->fts_statp->st_atimespec);
381 					TIMESPEC_TO_TIMEVAL(&tv[1],
382 					    &curr->fts_statp->st_mtimespec);
383 					if (utimes(to.p_path, tv))
384 						warn("utimes: %s", to.p_path);
385 				}
386 				continue;
387 			}
388 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
389 			    to_stat.st_ino == curr->fts_statp->st_ino) {
390 				warnx("%s and %s are identical (not copied).",
391 				    to.p_path, curr->fts_path);
392 				rval = 1;
393 				if (S_ISDIR(curr->fts_statp->st_mode))
394 					(void)fts_set(ftsp, curr, FTS_SKIP);
395 				continue;
396 			}
397 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
398 			    S_ISDIR(to_stat.st_mode)) {
399 		warnx("cannot overwrite directory %s with non-directory %s",
400 				    to.p_path, curr->fts_path);
401 				rval = 1;
402 				continue;
403 			}
404 			dne = 0;
405 		}
406 
407 		switch (curr->fts_statp->st_mode & S_IFMT) {
408 		case S_IFLNK:
409 			if (copy_link(curr, !dne))
410 				rval = 1;
411 			break;
412 		case S_IFDIR:
413 			if (!Rflag && !rflag) {
414 				warnx("%s is a directory (not copied).",
415 				    curr->fts_path);
416 				(void)fts_set(ftsp, curr, FTS_SKIP);
417 				rval = 1;
418 				break;
419 			}
420 			/*
421 			 * If the directory doesn't exist, create the new
422 			 * one with the from file mode plus owner RWX bits,
423 			 * modified by the umask.  Trade-off between being
424 			 * able to write the directory (if from directory is
425 			 * 555) and not causing a permissions race.  If the
426 			 * umask blocks owner writes, we fail..
427 			 */
428 			if (dne) {
429 				if (mkdir(to.p_path,
430 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
431 					err(1, "%s", to.p_path);
432 			} else if (!S_ISDIR(to_stat.st_mode)) {
433 				errno = ENOTDIR;
434 				err(1, "%s", to.p_path);
435 			}
436 			/*
437 			 * If not -p and directory didn't exist, set it to be
438 			 * the same as the from directory, unmodified by the
439 			 * umask; arguably wrong, but it's been that way
440 			 * forever.
441 			 */
442 			if (pflag && setfile(curr->fts_statp, 0))
443 				rval = 1;
444 			else if (dne)
445 				(void)chmod(to.p_path,
446 				    curr->fts_statp->st_mode);
447 			break;
448 		case S_IFBLK:
449 		case S_IFCHR:
450 			if (Rflag) {
451 				if (copy_special(curr->fts_statp, !dne))
452 					rval = 1;
453 			} else
454 				if (copy_file(curr, dne))
455 					rval = 1;
456 			break;
457 		case S_IFIFO:
458 			if (Rflag) {
459 				if (copy_fifo(curr->fts_statp, !dne))
460 					rval = 1;
461 			} else
462 				if (copy_file(curr, dne))
463 					rval = 1;
464 			break;
465 		default:
466 			if (copy_file(curr, dne))
467 				rval = 1;
468 			break;
469 		}
470 	}
471 	if (errno)
472 		err(1, "fts_read");
473 	return (rval);
474 }
475 
476 /*
477  * mastercmp --
478  *	The comparison function for the copy order.  The order is to copy
479  *	non-directory files before directory files.  The reason for this
480  *	is because files tend to be in the same cylinder group as their
481  *	parent directory, whereas directories tend not to be.  Copying the
482  *	files first reduces seeking.
483  */
484 int
485 mastercmp(a, b)
486 	const FTSENT **a, **b;
487 {
488 	int a_info, b_info;
489 
490 	a_info = (*a)->fts_info;
491 	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
492 		return (0);
493 	b_info = (*b)->fts_info;
494 	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
495 		return (0);
496 	if (a_info == FTS_D)
497 		return (-1);
498 	if (b_info == FTS_D)
499 		return (1);
500 	return (0);
501 }
502