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