xref: /freebsd/bin/cp/cp.c (revision 380a989b3223d455375b4fae70fd0b9bdd43bafb)
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.16 1998/05/13 07:25:14 charnier 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 			 * concatentation 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 			p = &curr->fts_path[base];
311 			nlen = curr->fts_pathlen - base;
312 			target_mid = to.target_end;
313 			if (*p != '/' && target_mid[-1] != '/')
314 				*target_mid++ = '/';
315 			*target_mid = 0;
316 			if (target_mid - to.p_path + nlen > MAXPATHLEN) {
317 				warnx("%s%s: name too long (not copied)",
318 				    to.p_path, p);
319 				rval = 1;
320 				continue;
321 			}
322 			(void)strncat(target_mid, p, nlen);
323 			to.p_end = target_mid + nlen;
324 			*to.p_end = 0;
325 			STRIP_TRAILING_SLASH(to);
326 		}
327 
328 		/* Not an error but need to remember it happened */
329 		if (stat(to.p_path, &to_stat) == -1)
330 			dne = 1;
331 		else {
332 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
333 			    to_stat.st_ino == curr->fts_statp->st_ino) {
334 				warnx("%s and %s are identical (not copied).",
335 				    to.p_path, curr->fts_path);
336 				rval = 1;
337 				if (S_ISDIR(curr->fts_statp->st_mode))
338 					(void)fts_set(ftsp, curr, FTS_SKIP);
339 				continue;
340 			}
341 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
342 			    S_ISDIR(to_stat.st_mode)) {
343 		warnx("cannot overwrite directory %s with non-directory %s",
344 				    to.p_path, curr->fts_path);
345 				rval = 1;
346 				continue;
347 			}
348 			dne = 0;
349 		}
350 
351 		switch (curr->fts_statp->st_mode & S_IFMT) {
352 		case S_IFLNK:
353 			if (copy_link(curr, !dne))
354 				rval = 1;
355 			break;
356 		case S_IFDIR:
357 			if (!Rflag && !rflag) {
358 				warnx("%s is a directory (not copied).",
359 				    curr->fts_path);
360 				(void)fts_set(ftsp, curr, FTS_SKIP);
361 				rval = 1;
362 				break;
363 			}
364 			/*
365 			 * If the directory doesn't exist, create the new
366 			 * one with the from file mode plus owner RWX bits,
367 			 * modified by the umask.  Trade-off between being
368 			 * able to write the directory (if from directory is
369 			 * 555) and not causing a permissions race.  If the
370 			 * umask blocks owner writes, we fail..
371 			 */
372 			if (dne) {
373 				if (mkdir(to.p_path,
374 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
375 					err(1, "%s", to.p_path);
376 			} else if (!S_ISDIR(to_stat.st_mode)) {
377 				errno = ENOTDIR;
378 				err(1, "%s", to.p_path);
379 			}
380 			/*
381 			 * If not -p and directory didn't exist, set it to be
382 			 * the same as the from directory, umodified by the
383                          * umask; arguably wrong, but it's been that way
384                          * forever.
385 			 */
386 			if (pflag && setfile(curr->fts_statp, 0))
387 				rval = 1;
388 			else if (dne)
389 				(void)chmod(to.p_path,
390 				    curr->fts_statp->st_mode);
391 			break;
392 		case S_IFBLK:
393 		case S_IFCHR:
394 			if (Rflag) {
395 				if (copy_special(curr->fts_statp, !dne))
396 					rval = 1;
397 			} else {
398 				if (copy_file(curr, dne))
399 					rval = 1;
400 			}
401 			break;
402 		case S_IFIFO:
403 			if (Rflag) {
404 				if (copy_fifo(curr->fts_statp, !dne))
405 					rval = 1;
406 			} else {
407 				if (copy_file(curr, dne))
408 					rval = 1;
409 			}
410 			break;
411 		default:
412 			if (copy_file(curr, dne))
413 				rval = 1;
414 			break;
415 		}
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