xref: /freebsd/bin/cp/cp.c (revision c17d43407fe04133a94055b0dbc7ea8965654a9f)
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;
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         STRIP_TRAILING_SLASH(to);
183 	to.target_end = to.p_end;
184 
185 	/* Set end of argument list for fts(3). */
186 	argv[argc] = NULL;
187 
188 	/*
189 	 * Cp has two distinct cases:
190 	 *
191 	 * cp [-R] source target
192 	 * cp [-R] source1 ... sourceN directory
193 	 *
194 	 * In both cases, source can be either a file or a directory.
195 	 *
196 	 * In (1), the target becomes a copy of the source. That is, if the
197 	 * source is a file, the target will be a file, and likewise for
198 	 * directories.
199 	 *
200 	 * In (2), the real target is not directory, but "directory/source".
201 	 */
202 	r = stat(to.p_path, &to_stat);
203 	if (r == -1 && errno != ENOENT)
204 		err(1, "%s", to.p_path);
205 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
206 		/*
207 		 * Case (1).  Target is not a directory.
208 		 */
209 		if (argc > 1) {
210 			usage();
211 			exit(1);
212 		}
213 		/*
214 		 * Need to detect the case:
215 		 *	cp -R dir foo
216 		 * Where dir is a directory and foo does not exist, where
217 		 * we want pathname concatenations turned on but not for
218 		 * the initial mkdir().
219 		 */
220 		if (r == -1) {
221 			if (rflag || (Rflag && (Lflag || Hflag)))
222 				stat(*argv, &tmp_stat);
223 			else
224 				lstat(*argv, &tmp_stat);
225 
226 			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
227 				type = DIR_TO_DNE;
228 			else
229 				type = FILE_TO_FILE;
230 		} else
231 			type = FILE_TO_FILE;
232 	} else
233 		/*
234 		 * Case (2).  Target is a directory.
235 		 */
236 		type = FILE_TO_DIR;
237 
238 	exit (copy(argv, type, fts_options));
239 }
240 
241 int
242 copy(char *argv[], enum op type, int fts_options)
243 {
244 	struct stat to_stat;
245 	FTS *ftsp;
246 	FTSENT *curr;
247 	int base = 0, dne, badcp, rval;
248 	size_t nlen;
249 	char *p, *target_mid;
250 	mode_t mask, mode;
251 
252 	/*
253 	 * Keep an inverted copy of the umask, for use in correcting
254 	 * permissions on created directories when not using -p.
255 	 */
256 	mask = ~umask(0777);
257 	umask(~mask);
258 
259 	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
260 		err(1, NULL);
261 	for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
262 		switch (curr->fts_info) {
263 		case FTS_NS:
264 		case FTS_DNR:
265 		case FTS_ERR:
266 			warnx("%s: %s",
267 			    curr->fts_path, strerror(curr->fts_errno));
268 			badcp = rval = 1;
269 			continue;
270 		case FTS_DC:			/* Warn, continue. */
271 			warnx("%s: directory causes a cycle", curr->fts_path);
272 			badcp = rval = 1;
273 			continue;
274 		default:
275 		}
276 
277 		/*
278 		 * If we are in case (2) or (3) above, we need to append the
279                  * source name to the target name.
280                  */
281 		if (type != FILE_TO_FILE) {
282 			/*
283 			 * Need to remember the roots of traversals to create
284 			 * correct pathnames.  If there's a directory being
285 			 * copied to a non-existent directory, e.g.
286 			 *	cp -R a/dir noexist
287 			 * the resulting path name should be noexist/foo, not
288 			 * noexist/dir/foo (where foo is a file in dir), which
289 			 * is the case where the target exists.
290 			 *
291 			 * Also, check for "..".  This is for correct path
292 			 * concatenation for paths ending in "..", e.g.
293 			 *	cp -R .. /tmp
294 			 * Paths ending in ".." are changed to ".".  This is
295 			 * tricky, but seems the easiest way to fix the problem.
296 			 *
297 			 * XXX
298 			 * Since the first level MUST be FTS_ROOTLEVEL, base
299 			 * is always initialized.
300 			 */
301 			if (curr->fts_level == FTS_ROOTLEVEL) {
302 				if (type != DIR_TO_DNE) {
303 					p = strrchr(curr->fts_path, '/');
304 					base = (p == NULL) ? 0 :
305 					    (int)(p - curr->fts_path + 1);
306 
307 					if (!strcmp(&curr->fts_path[base],
308 					    ".."))
309 						base += 1;
310 				} else
311 					base = curr->fts_pathlen;
312 			}
313 
314 			p = &curr->fts_path[base];
315 			nlen = curr->fts_pathlen - base;
316 			target_mid = to.target_end;
317 			if (*p != '/' && target_mid[-1] != '/')
318 				*target_mid++ = '/';
319 			*target_mid = 0;
320 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
321 				warnx("%s%s: name too long (not copied)",
322 				    to.p_path, p);
323 				badcp = rval = 1;
324 				continue;
325 			}
326 			(void)strncat(target_mid, p, nlen);
327 			to.p_end = target_mid + nlen;
328 			*to.p_end = 0;
329 			STRIP_TRAILING_SLASH(to);
330 		}
331 
332 		if (curr->fts_info == FTS_DP) {
333 			/*
334 			 * We are nearly finished with this directory.  If we
335 			 * didn't actually copy it, or otherwise don't need to
336 			 * change its attributes, then we are done.
337 			 */
338 			if (!curr->fts_number)
339 				continue;
340 			/*
341 			 * If -p is in effect, set all the attributes.
342 			 * Otherwise, set the correct permissions, limited
343 			 * by the umask.  Optimise by avoiding a chmod()
344 			 * if possible (which is usually the case if we
345 			 * made the directory).  Note that mkdir() does not
346 			 * honour setuid, setgid and sticky bits, but we
347 			 * normally want to preserve them on directories.
348 			 */
349 			if (pflag)
350 				rval = setfile(curr->fts_statp, 0);
351 			else {
352 				mode = curr->fts_statp->st_mode;
353 				if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
354 				    ((mode | S_IRWXU) & mask) != (mode & mask))
355 					if (chmod(to.p_path, mode & mask) != 0){
356 						warn("chmod: %s", to.p_path);
357 						rval = 1;
358 					}
359 			}
360 			continue;
361 		}
362 
363 		/* Not an error but need to remember it happened */
364 		if (stat(to.p_path, &to_stat) == -1)
365 			dne = 1;
366 		else {
367 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
368 			    to_stat.st_ino == curr->fts_statp->st_ino) {
369 				warnx("%s and %s are identical (not copied).",
370 				    to.p_path, curr->fts_path);
371 				badcp = rval = 1;
372 				if (S_ISDIR(curr->fts_statp->st_mode))
373 					(void)fts_set(ftsp, curr, FTS_SKIP);
374 				continue;
375 			}
376 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
377 			    S_ISDIR(to_stat.st_mode)) {
378 				warnx("cannot overwrite directory %s with "
379 				    "non-directory %s",
380 				    to.p_path, curr->fts_path);
381 				badcp = rval = 1;
382 				continue;
383 			}
384 			dne = 0;
385 		}
386 
387 		switch (curr->fts_statp->st_mode & S_IFMT) {
388 		case S_IFLNK:
389 			if (copy_link(curr, !dne))
390 				badcp = rval = 1;
391 			break;
392 		case S_IFDIR:
393 			if (!Rflag && !rflag) {
394 				warnx("%s is a directory (not copied).",
395 				    curr->fts_path);
396 				(void)fts_set(ftsp, curr, FTS_SKIP);
397 				badcp = rval = 1;
398 				break;
399 			}
400 			/*
401 			 * If the directory doesn't exist, create the new
402 			 * one with the from file mode plus owner RWX bits,
403 			 * modified by the umask.  Trade-off between being
404 			 * able to write the directory (if from directory is
405 			 * 555) and not causing a permissions race.  If the
406 			 * umask blocks owner writes, we fail..
407 			 */
408 			if (dne) {
409 				if (mkdir(to.p_path,
410 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
411 					err(1, "%s", to.p_path);
412 			} else if (!S_ISDIR(to_stat.st_mode)) {
413 				errno = ENOTDIR;
414 				err(1, "%s", to.p_path);
415 			}
416 			/*
417 			 * Arrange to correct directory attributes later
418 			 * (in the post-order phase) if this is a new
419 			 * directory, or if the -p flag is in effect.
420 			 */
421 			curr->fts_number = pflag || dne;
422 			break;
423 		case S_IFBLK:
424 		case S_IFCHR:
425 			if (Rflag) {
426 				if (copy_special(curr->fts_statp, !dne))
427 					badcp = rval = 1;
428 			} else {
429 				if (copy_file(curr, dne))
430 					badcp = rval = 1;
431 			}
432 			break;
433 		case S_IFIFO:
434 			if (Rflag) {
435 				if (copy_fifo(curr->fts_statp, !dne))
436 					badcp = rval = 1;
437 			} else {
438 				if (copy_file(curr, dne))
439 					badcp = rval = 1;
440 			}
441 			break;
442 		default:
443 			if (copy_file(curr, dne))
444 				badcp = rval = 1;
445 			break;
446 		}
447 		if (vflag && !badcp)
448 			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
449 	}
450 	if (errno)
451 		err(1, "fts_read");
452 	return (rval);
453 }
454 
455 /*
456  * mastercmp --
457  *	The comparison function for the copy order.  The order is to copy
458  *	non-directory files before directory files.  The reason for this
459  *	is because files tend to be in the same cylinder group as their
460  *	parent directory, whereas directories tend not to be.  Copying the
461  *	files first reduces seeking.
462  */
463 int
464 mastercmp(const FTSENT **a, const FTSENT **b)
465 {
466 	int a_info, b_info;
467 
468 	a_info = (*a)->fts_info;
469 	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
470 		return (0);
471 	b_info = (*b)->fts_info;
472 	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
473 		return (0);
474 	if (a_info == FTS_D)
475 		return (-1);
476 	if (b_info == FTS_D)
477 		return (1);
478 	return (0);
479 }
480