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