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