xref: /freebsd/bin/cp/cp.c (revision 5129159789cc9d7bc514e4546b88e3427695002d)
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 <stdio.h>
73 #include <string.h>
74 #include <unistd.h>
75 
76 #include "extern.h"
77 
78 #define	STRIP_TRAILING_SLASH(p) {					\
79         while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
80                 *--(p).p_end = 0;					\
81 }
82 
83 PATH_T to = { to.p_path, "", "" };
84 
85 uid_t myuid;
86 int Rflag, iflag, pflag, rflag, fflag, vflag;
87 int myumask;
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 	myuid = getuid();
173 
174 	/* Copy the umask for explicit mode setting. */
175 	myumask = umask(0);
176 	(void)umask(myumask);
177 
178 	/* Save the target base in "to". */
179 	target = argv[--argc];
180 	if (strlen(target) > MAXPATHLEN)
181 		errx(1, "%s: name too long", target);
182 	(void)strcpy(to.p_path, target);
183 	to.p_end = to.p_path + strlen(to.p_path);
184         if (to.p_path == to.p_end) {
185 		*to.p_end++ = '.';
186 		*to.p_end = 0;
187 	}
188         STRIP_TRAILING_SLASH(to);
189 	to.target_end = to.p_end;
190 
191 	/* Set end of argument list for fts(3). */
192 	argv[argc] = NULL;
193 
194 	/*
195 	 * Cp has two distinct cases:
196 	 *
197 	 * cp [-R] source target
198 	 * cp [-R] source1 ... sourceN directory
199 	 *
200 	 * In both cases, source can be either a file or a directory.
201 	 *
202 	 * In (1), the target becomes a copy of the source. That is, if the
203 	 * source is a file, the target will be a file, and likewise for
204 	 * directories.
205 	 *
206 	 * In (2), the real target is not directory, but "directory/source".
207 	 */
208 	r = stat(to.p_path, &to_stat);
209 	if (r == -1 && errno != ENOENT)
210 		err(1, "%s", to.p_path);
211 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
212 		/*
213 		 * Case (1).  Target is not a directory.
214 		 */
215 		if (argc > 1) {
216 			usage();
217 			exit(1);
218 		}
219 		/*
220 		 * Need to detect the case:
221 		 *	cp -R dir foo
222 		 * Where dir is a directory and foo does not exist, where
223 		 * we want pathname concatenations turned on but not for
224 		 * the initial mkdir().
225 		 */
226 		if (r == -1) {
227 			if (rflag || (Rflag && (Lflag || Hflag)))
228 				stat(*argv, &tmp_stat);
229 			else
230 				lstat(*argv, &tmp_stat);
231 
232 			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
233 				type = DIR_TO_DNE;
234 			else
235 				type = FILE_TO_FILE;
236 		} else
237 			type = FILE_TO_FILE;
238 	} else
239 		/*
240 		 * Case (2).  Target is a directory.
241 		 */
242 		type = FILE_TO_DIR;
243 
244 	exit (copy(argv, type, fts_options));
245 }
246 
247 int
248 copy(argv, type, fts_options)
249 	char *argv[];
250 	enum op type;
251 	int fts_options;
252 {
253 	struct stat to_stat;
254 	FTS *ftsp;
255 	FTSENT *curr;
256 	int base = 0, dne, badcp, nlen, rval;
257 	char *p, *target_mid;
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 		case FTS_DP:			/* Ignore, continue. */
275 			continue;
276 		}
277 
278 		/*
279 		 * If we are in case (2) or (3) above, we need to append the
280                  * source name to the target name.
281                  */
282 		if (type != FILE_TO_FILE) {
283 			/*
284 			 * Need to remember the roots of traversals to create
285 			 * correct pathnames.  If there's a directory being
286 			 * copied to a non-existent directory, e.g.
287 			 *	cp -R a/dir noexist
288 			 * the resulting path name should be noexist/foo, not
289 			 * noexist/dir/foo (where foo is a file in dir), which
290 			 * is the case where the target exists.
291 			 *
292 			 * Also, check for "..".  This is for correct path
293 			 * concatenation for paths ending in "..", e.g.
294 			 *	cp -R .. /tmp
295 			 * Paths ending in ".." are changed to ".".  This is
296 			 * tricky, but seems the easiest way to fix the problem.
297 			 *
298 			 * XXX
299 			 * Since the first level MUST be FTS_ROOTLEVEL, base
300 			 * is always initialized.
301 			 */
302 			if (curr->fts_level == FTS_ROOTLEVEL) {
303 				if (type != DIR_TO_DNE) {
304 					p = strrchr(curr->fts_path, '/');
305 					base = (p == NULL) ? 0 :
306 					    (int)(p - curr->fts_path + 1);
307 
308 					if (!strcmp(&curr->fts_path[base],
309 					    ".."))
310 						base += 1;
311 				} else
312 					base = curr->fts_pathlen;
313 			}
314 
315 			p = &curr->fts_path[base];
316 			nlen = curr->fts_pathlen - base;
317 			target_mid = to.target_end;
318 			if (*p != '/' && target_mid[-1] != '/')
319 				*target_mid++ = '/';
320 			*target_mid = 0;
321 			if (target_mid - to.p_path + nlen > MAXPATHLEN) {
322 				warnx("%s%s: name too long (not copied)",
323 				    to.p_path, p);
324 				badcp = rval = 1;
325 				continue;
326 			}
327 			(void)strncat(target_mid, p, nlen);
328 			to.p_end = target_mid + nlen;
329 			*to.p_end = 0;
330 			STRIP_TRAILING_SLASH(to);
331 		}
332 
333 		/* Not an error but need to remember it happened */
334 		if (stat(to.p_path, &to_stat) == -1)
335 			dne = 1;
336 		else {
337 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
338 			    to_stat.st_ino == curr->fts_statp->st_ino) {
339 				warnx("%s and %s are identical (not copied).",
340 				    to.p_path, curr->fts_path);
341 				badcp = rval = 1;
342 				if (S_ISDIR(curr->fts_statp->st_mode))
343 					(void)fts_set(ftsp, curr, FTS_SKIP);
344 				continue;
345 			}
346 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
347 			    S_ISDIR(to_stat.st_mode)) {
348 		warnx("cannot overwrite directory %s with non-directory %s",
349 				    to.p_path, curr->fts_path);
350 				badcp = rval = 1;
351 				continue;
352 			}
353 			dne = 0;
354 		}
355 
356 		switch (curr->fts_statp->st_mode & S_IFMT) {
357 		case S_IFLNK:
358 			if (copy_link(curr, !dne))
359 				badcp = rval = 1;
360 			break;
361 		case S_IFDIR:
362 			if (!Rflag && !rflag) {
363 				warnx("%s is a directory (not copied).",
364 				    curr->fts_path);
365 				(void)fts_set(ftsp, curr, FTS_SKIP);
366 				badcp = rval = 1;
367 				break;
368 			}
369 			/*
370 			 * If the directory doesn't exist, create the new
371 			 * one with the from file mode plus owner RWX bits,
372 			 * modified by the umask.  Trade-off between being
373 			 * able to write the directory (if from directory is
374 			 * 555) and not causing a permissions race.  If the
375 			 * umask blocks owner writes, we fail..
376 			 */
377 			if (dne) {
378 				if (mkdir(to.p_path,
379 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
380 					err(1, "%s", to.p_path);
381 			} else if (!S_ISDIR(to_stat.st_mode)) {
382 				errno = ENOTDIR;
383 				err(1, "%s", to.p_path);
384 			}
385 			/*
386 			 * If not -p and directory didn't exist, set it to be
387 			 * the same as the from directory, umodified by the
388                          * umask; arguably wrong, but it's been that way
389                          * forever.
390 			 */
391 			if (pflag && setfile(curr->fts_statp, 0))
392 				badcp = rval = 1;
393 			else if (dne)
394 				(void)chmod(to.p_path,
395 				    curr->fts_statp->st_mode);
396 			break;
397 		case S_IFBLK:
398 		case S_IFCHR:
399 			if (Rflag) {
400 				if (copy_special(curr->fts_statp, !dne))
401 					badcp = rval = 1;
402 			} else {
403 				if (copy_file(curr, dne))
404 					badcp = rval = 1;
405 			}
406 			break;
407 		case S_IFIFO:
408 			if (Rflag) {
409 				if (copy_fifo(curr->fts_statp, !dne))
410 					badcp = rval = 1;
411 			} else {
412 				if (copy_file(curr, dne))
413 					badcp = rval = 1;
414 			}
415 			break;
416 		default:
417 			if (copy_file(curr, dne))
418 				badcp = rval = 1;
419 			break;
420 		}
421 		if (vflag && !badcp)
422 			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
423 	}
424 	if (errno)
425 		err(1, "fts_read");
426 	return (rval);
427 }
428 
429 /*
430  * mastercmp --
431  *	The comparison function for the copy order.  The order is to copy
432  *	non-directory files before directory files.  The reason for this
433  *	is because files tend to be in the same cylinder group as their
434  *	parent directory, whereas directories tend not to be.  Copying the
435  *	files first reduces seeking.
436  */
437 int
438 mastercmp(a, b)
439 	const FTSENT **a, **b;
440 {
441 	int a_info, b_info;
442 
443 	a_info = (*a)->fts_info;
444 	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
445 		return (0);
446 	b_info = (*b)->fts_info;
447 	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
448 		return (0);
449 	if (a_info == FTS_D)
450 		return (-1);
451 	if (b_info == FTS_D)
452 		return (1);
453 	return (0);
454 }
455