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