xref: /freebsd/bin/cp/cp.c (revision 6990ffd8a95caaba6858ad44ff1b3157d1efba8f)
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 PATH_T to = { to.p_path, "", "" };
86 
87 int Rflag, iflag, pflag, rflag, fflag, vflag;
88 
89 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
90 
91 int copy __P((char *[], enum op, int));
92 int mastercmp __P((const FTSENT **, const FTSENT **));
93 
94 int
95 main(argc, argv)
96 	int argc;
97 	char *argv[];
98 {
99 	struct stat to_stat, tmp_stat;
100 	enum op type;
101 	int Hflag, Lflag, Pflag, ch, fts_options, r;
102 	char *target;
103 
104 	Hflag = Lflag = Pflag = 0;
105 	while ((ch = getopt(argc, argv, "HLPRfiprv")) != -1)
106 		switch (ch) {
107 		case 'H':
108 			Hflag = 1;
109 			Lflag = Pflag = 0;
110 			break;
111 		case 'L':
112 			Lflag = 1;
113 			Hflag = Pflag = 0;
114 			break;
115 		case 'P':
116 			Pflag = 1;
117 			Hflag = Lflag = 0;
118 			break;
119 		case 'R':
120 			Rflag = 1;
121 			break;
122 		case 'f':
123 			fflag = 1;
124 			iflag = 0;
125 			break;
126 		case 'i':
127 			iflag = 1;
128 			fflag = 0;
129 			break;
130 		case 'p':
131 			pflag = 1;
132 			break;
133 		case 'r':
134 			rflag = 1;
135 			break;
136 		case 'v':
137 			vflag = 1;
138 			break;
139 		default:
140 			usage();
141 			break;
142 		}
143 	argc -= optind;
144 	argv += optind;
145 
146 	if (argc < 2)
147 		usage();
148 
149 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
150 	if (rflag) {
151 		if (Rflag)
152 			errx(1,
153 		    "the -R and -r options may not be specified together.");
154 		if (Hflag || Lflag || Pflag)
155 			errx(1,
156 	"the -H, -L, and -P options may not be specified with the -r option.");
157 		fts_options &= ~FTS_PHYSICAL;
158 		fts_options |= FTS_LOGICAL;
159 	}
160 	if (Rflag) {
161 		if (Hflag)
162 			fts_options |= FTS_COMFOLLOW;
163 		if (Lflag) {
164 			fts_options &= ~FTS_PHYSICAL;
165 			fts_options |= FTS_LOGICAL;
166 		}
167 	} else {
168 		fts_options &= ~FTS_PHYSICAL;
169 		fts_options |= FTS_LOGICAL;
170 	}
171 
172 	/* Save the target base in "to". */
173 	target = argv[--argc];
174 	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
175 		errx(1, "%s: name too long", target);
176 	to.p_end = to.p_path + strlen(to.p_path);
177         if (to.p_path == to.p_end) {
178 		*to.p_end++ = '.';
179 		*to.p_end = 0;
180 	}
181         STRIP_TRAILING_SLASH(to);
182 	to.target_end = to.p_end;
183 
184 	/* Set end of argument list for fts(3). */
185 	argv[argc] = NULL;
186 
187 	/*
188 	 * Cp has two distinct cases:
189 	 *
190 	 * cp [-R] source target
191 	 * cp [-R] source1 ... sourceN directory
192 	 *
193 	 * In both cases, source can be either a file or a directory.
194 	 *
195 	 * In (1), the target becomes a copy of the source. That is, if the
196 	 * source is a file, the target will be a file, and likewise for
197 	 * directories.
198 	 *
199 	 * In (2), the real target is not directory, but "directory/source".
200 	 */
201 	r = stat(to.p_path, &to_stat);
202 	if (r == -1 && errno != ENOENT)
203 		err(1, "%s", to.p_path);
204 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
205 		/*
206 		 * Case (1).  Target is not a directory.
207 		 */
208 		if (argc > 1) {
209 			usage();
210 			exit(1);
211 		}
212 		/*
213 		 * Need to detect the case:
214 		 *	cp -R dir foo
215 		 * Where dir is a directory and foo does not exist, where
216 		 * we want pathname concatenations turned on but not for
217 		 * the initial mkdir().
218 		 */
219 		if (r == -1) {
220 			if (rflag || (Rflag && (Lflag || Hflag)))
221 				stat(*argv, &tmp_stat);
222 			else
223 				lstat(*argv, &tmp_stat);
224 
225 			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
226 				type = DIR_TO_DNE;
227 			else
228 				type = FILE_TO_FILE;
229 		} else
230 			type = FILE_TO_FILE;
231 	} else
232 		/*
233 		 * Case (2).  Target is a directory.
234 		 */
235 		type = FILE_TO_DIR;
236 
237 	exit (copy(argv, type, fts_options));
238 }
239 
240 int
241 copy(argv, type, fts_options)
242 	char *argv[];
243 	enum op type;
244 	int fts_options;
245 {
246 	struct stat to_stat;
247 	FTS *ftsp;
248 	FTSENT *curr;
249 	int base = 0, dne, badcp, nlen, rval;
250 	char *p, *target_mid;
251 
252 	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
253 		err(1, NULL);
254 	for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
255 		switch (curr->fts_info) {
256 		case FTS_NS:
257 		case FTS_DNR:
258 		case FTS_ERR:
259 			warnx("%s: %s",
260 			    curr->fts_path, strerror(curr->fts_errno));
261 			badcp = rval = 1;
262 			continue;
263 		case FTS_DC:			/* Warn, continue. */
264 			warnx("%s: directory causes a cycle", curr->fts_path);
265 			badcp = rval = 1;
266 			continue;
267 		case FTS_DP:			/* Ignore, continue. */
268 			continue;
269 		}
270 
271 		/*
272 		 * If we are in case (2) or (3) above, we need to append the
273                  * source name to the target name.
274                  */
275 		if (type != FILE_TO_FILE) {
276 			/*
277 			 * Need to remember the roots of traversals to create
278 			 * correct pathnames.  If there's a directory being
279 			 * copied to a non-existent directory, e.g.
280 			 *	cp -R a/dir noexist
281 			 * the resulting path name should be noexist/foo, not
282 			 * noexist/dir/foo (where foo is a file in dir), which
283 			 * is the case where the target exists.
284 			 *
285 			 * Also, check for "..".  This is for correct path
286 			 * concatenation for paths ending in "..", e.g.
287 			 *	cp -R .. /tmp
288 			 * Paths ending in ".." are changed to ".".  This is
289 			 * tricky, but seems the easiest way to fix the problem.
290 			 *
291 			 * XXX
292 			 * Since the first level MUST be FTS_ROOTLEVEL, base
293 			 * is always initialized.
294 			 */
295 			if (curr->fts_level == FTS_ROOTLEVEL) {
296 				if (type != DIR_TO_DNE) {
297 					p = strrchr(curr->fts_path, '/');
298 					base = (p == NULL) ? 0 :
299 					    (int)(p - curr->fts_path + 1);
300 
301 					if (!strcmp(&curr->fts_path[base],
302 					    ".."))
303 						base += 1;
304 				} else
305 					base = curr->fts_pathlen;
306 			}
307 
308 			p = &curr->fts_path[base];
309 			nlen = curr->fts_pathlen - base;
310 			target_mid = to.target_end;
311 			if (*p != '/' && target_mid[-1] != '/')
312 				*target_mid++ = '/';
313 			*target_mid = 0;
314 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
315 				warnx("%s%s: name too long (not copied)",
316 				    to.p_path, p);
317 				badcp = rval = 1;
318 				continue;
319 			}
320 			(void)strncat(target_mid, p, nlen);
321 			to.p_end = target_mid + nlen;
322 			*to.p_end = 0;
323 			STRIP_TRAILING_SLASH(to);
324 		}
325 
326 		/* Not an error but need to remember it happened */
327 		if (stat(to.p_path, &to_stat) == -1)
328 			dne = 1;
329 		else {
330 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
331 			    to_stat.st_ino == curr->fts_statp->st_ino) {
332 				warnx("%s and %s are identical (not copied).",
333 				    to.p_path, curr->fts_path);
334 				badcp = rval = 1;
335 				if (S_ISDIR(curr->fts_statp->st_mode))
336 					(void)fts_set(ftsp, curr, FTS_SKIP);
337 				continue;
338 			}
339 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
340 			    S_ISDIR(to_stat.st_mode)) {
341 		warnx("cannot overwrite directory %s with non-directory %s",
342 				    to.p_path, curr->fts_path);
343 				badcp = rval = 1;
344 				continue;
345 			}
346 			dne = 0;
347 		}
348 
349 		switch (curr->fts_statp->st_mode & S_IFMT) {
350 		case S_IFLNK:
351 			if (copy_link(curr, !dne))
352 				badcp = rval = 1;
353 			break;
354 		case S_IFDIR:
355 			if (!Rflag && !rflag) {
356 				warnx("%s is a directory (not copied).",
357 				    curr->fts_path);
358 				(void)fts_set(ftsp, curr, FTS_SKIP);
359 				badcp = rval = 1;
360 				break;
361 			}
362 			/*
363 			 * If the directory doesn't exist, create the new
364 			 * one with the from file mode plus owner RWX bits,
365 			 * modified by the umask.  Trade-off between being
366 			 * able to write the directory (if from directory is
367 			 * 555) and not causing a permissions race.  If the
368 			 * umask blocks owner writes, we fail..
369 			 */
370 			if (dne) {
371 				if (mkdir(to.p_path,
372 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
373 					err(1, "%s", to.p_path);
374 			} else if (!S_ISDIR(to_stat.st_mode)) {
375 				errno = ENOTDIR;
376 				err(1, "%s", to.p_path);
377 			}
378 			/*
379 			 * If not -p and directory didn't exist, set it to be
380 			 * the same as the from directory, umodified by the
381                          * umask; arguably wrong, but it's been that way
382                          * forever.
383 			 */
384 			if (pflag && setfile(curr->fts_statp, 0))
385 				badcp = rval = 1;
386 			else if (dne)
387 				(void)chmod(to.p_path,
388 				    curr->fts_statp->st_mode);
389 			break;
390 		case S_IFBLK:
391 		case S_IFCHR:
392 			if (Rflag) {
393 				if (copy_special(curr->fts_statp, !dne))
394 					badcp = rval = 1;
395 			} else {
396 				if (copy_file(curr, dne))
397 					badcp = rval = 1;
398 			}
399 			break;
400 		case S_IFIFO:
401 			if (Rflag) {
402 				if (copy_fifo(curr->fts_statp, !dne))
403 					badcp = rval = 1;
404 			} else {
405 				if (copy_file(curr, dne))
406 					badcp = rval = 1;
407 			}
408 			break;
409 		default:
410 			if (copy_file(curr, dne))
411 				badcp = rval = 1;
412 			break;
413 		}
414 		if (vflag && !badcp)
415 			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
416 	}
417 	if (errno)
418 		err(1, "fts_read");
419 	return (rval);
420 }
421 
422 /*
423  * mastercmp --
424  *	The comparison function for the copy order.  The order is to copy
425  *	non-directory files before directory files.  The reason for this
426  *	is because files tend to be in the same cylinder group as their
427  *	parent directory, whereas directories tend not to be.  Copying the
428  *	files first reduces seeking.
429  */
430 int
431 mastercmp(a, b)
432 	const FTSENT **a, **b;
433 {
434 	int a_info, b_info;
435 
436 	a_info = (*a)->fts_info;
437 	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
438 		return (0);
439 	b_info = (*b)->fts_info;
440 	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
441 		return (0);
442 	if (a_info == FTS_D)
443 		return (-1);
444 	if (b_info == FTS_D)
445 		return (1);
446 	return (0);
447 }
448