xref: /netbsd-src/bin/cp/cp.c (revision 76dfffe33547c37f8bdd446e3e4ab0f3c16cea4b)
1 /*	$NetBSD: cp.c,v 1.14 1995/09/07 06:14:51 jtc Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * David Hitz of Auspex Systems Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
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 #if 0
47 static char sccsid[] = "@(#)cp.c	8.5 (Berkeley) 4/29/95";
48 #else
49 static char rcsid[] = "$NetBSD: cp.c,v 1.14 1995/09/07 06:14:51 jtc Exp $";
50 #endif
51 #endif /* not lint */
52 
53 /*
54  * Cp copies source files to target files.
55  *
56  * The global PATH_T structure "to" always contains the path to the
57  * current target file.  Since fts(3) does not change directories,
58  * this path can be either absolute or dot-relative.
59  *
60  * The basic algorithm is to initialize "to" and use fts(3) to traverse
61  * the file hierarchy rooted in the argument list.  A trivial case is the
62  * case of 'cp file1 file2'.  The more interesting case is the case of
63  * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
64  * path (relative to the root of the traversal) is appended to dir (stored
65  * in "to") to form the final target path.
66  */
67 
68 #include <sys/param.h>
69 #include <sys/stat.h>
70 #include <sys/mman.h>
71 #include <sys/time.h>
72 
73 #include <dirent.h>
74 #include <err.h>
75 #include <errno.h>
76 #include <fcntl.h>
77 #include <fts.h>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <unistd.h>
82 
83 #include "extern.h"
84 
85 #define	STRIP_TRAILING_SLASH(p) {					\
86         while ((p).p_end > (p).p_path && (p).p_end[-1] == '/')		\
87                 *--(p).p_end = 0;					\
88 }
89 
90 PATH_T to = { to.p_path, "" };
91 
92 uid_t myuid;
93 int Rflag, iflag, pflag, rflag;
94 int myumask;
95 
96 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
97 
98 int copy __P((char *[], enum op, int));
99 int mastercmp __P((const FTSENT **, const FTSENT **));
100 
101 int
102 main(argc, argv)
103 	int argc;
104 	char *argv[];
105 {
106 	struct stat to_stat, tmp_stat;
107 	enum op type;
108 	int Hflag, Lflag, Pflag, ch, fts_options, r;
109 	char *target;
110 
111 	Hflag = Lflag = Pflag = Rflag = 0;
112 	while ((ch = getopt(argc, argv, "HLPRfipr")) != EOF)
113 		switch (ch) {
114 		case 'H':
115 			Hflag = 1;
116 			Lflag = Pflag = 0;
117 			break;
118 		case 'L':
119 			Lflag = 1;
120 			Hflag = Pflag = 0;
121 			break;
122 		case 'P':
123 			Pflag = 1;
124 			Hflag = Lflag = 0;
125 			break;
126 		case 'R':
127 			Rflag = 1;
128 			break;
129 		case 'f':
130 			iflag = 0;
131 			break;
132 		case 'i':
133 			iflag = isatty(fileno(stdin));
134 			break;
135 		case 'p':
136 			pflag = 1;
137 			break;
138 		case 'r':
139 			rflag = 1;
140 			break;
141 		case '?':
142 		default:
143 			usage();
144 			break;
145 		}
146 	argc -= optind;
147 	argv += optind;
148 
149 	if (argc < 2)
150 		usage();
151 
152 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
153 	if (rflag) {
154 		if (Rflag)
155 			errx(1,
156 		    "the -R and -r options may not be specified together.");
157 		if (Hflag || Lflag || Pflag)
158 			errx(1,
159 	"the -H, -L, and -P options may not be specified with the -r option.");
160 		fts_options &= ~FTS_PHYSICAL;
161 		fts_options |= FTS_LOGICAL;
162 	}
163 	if (Rflag) {
164 		if (Hflag)
165 			fts_options |= FTS_COMFOLLOW;
166 		if (Lflag) {
167 			fts_options &= ~FTS_PHYSICAL;
168 			fts_options |= FTS_LOGICAL;
169 		}
170 	} else {
171 		fts_options &= ~FTS_PHYSICAL;
172 		fts_options |= FTS_LOGICAL;
173 	}
174 
175 	myuid = getuid();
176 
177 	/* Copy the umask for explicit mode setting. */
178 	myumask = umask(0);
179 	(void)umask(myumask);
180 
181 	/* Save the target base in "to". */
182 	target = argv[--argc];
183 	if (strlen(target) > MAXPATHLEN)
184 		errx(1, "%s: name too long", target);
185 	(void)strcpy(to.p_path, target);
186 	to.p_end = to.p_path + strlen(to.p_path);
187         if (to.p_path == to.p_end) {
188 		*to.p_end++ = '.';
189 		*to.p_end = 0;
190 	}
191         STRIP_TRAILING_SLASH(to);
192 	to.target_end = to.p_end;
193 
194 	/* Set end of argument list for fts(3). */
195 	argv[argc] = NULL;
196 
197 	/*
198 	 * Cp has two distinct cases:
199 	 *
200 	 * cp [-R] source target
201 	 * cp [-R] source1 ... sourceN directory
202 	 *
203 	 * In both cases, source can be either a file or a directory.
204 	 *
205 	 * In (1), the target becomes a copy of the source. That is, if the
206 	 * source is a file, the target will be a file, and likewise for
207 	 * directories.
208 	 *
209 	 * In (2), the real target is not directory, but "directory/source".
210 	 */
211 	r = stat(to.p_path, &to_stat);
212 	if (r == -1 && errno != ENOENT)
213 		err(1, "%s", to.p_path);
214 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
215 		/*
216 		 * Case (1).  Target is not a directory.
217 		 */
218 		if (argc > 1) {
219 			usage();
220 			exit(1);
221 		}
222 		/*
223 		 * Need to detect the case:
224 		 *	cp -R dir foo
225 		 * Where dir is a directory and foo does not exist, where
226 		 * we want pathname concatenations turned on but not for
227 		 * the initial mkdir().
228 		 */
229 		if (r == -1) {
230 			if (rflag || (Rflag && (Lflag || Hflag)))
231 				stat(*argv, &tmp_stat);
232 			else
233 				lstat(*argv, &tmp_stat);
234 
235 			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
236 				type = DIR_TO_DNE;
237 			else
238 				type = FILE_TO_FILE;
239 		} else
240 			type = FILE_TO_FILE;
241 	} else
242 		/*
243 		 * Case (2).  Target is a directory.
244 		 */
245 		type = FILE_TO_DIR;
246 
247 	exit (copy(argv, type, fts_options));
248 }
249 
250 int
251 copy(argv, type, fts_options)
252 	char *argv[];
253 	enum op type;
254 	int fts_options;
255 {
256 	struct stat to_stat;
257 	FTS *ftsp;
258 	FTSENT *curr;
259 	int base, dne, nlen, rval;
260 	char *p;
261 
262 	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL)
263 		err(1, NULL);
264 	for (rval = 0; (curr = fts_read(ftsp)) != NULL;) {
265 		switch (curr->fts_info) {
266 		case FTS_NS:
267 		case FTS_ERR:
268 			warnx("%s: %s",
269 			    curr->fts_path, strerror(curr->fts_errno));
270 			rval = 1;
271 			continue;
272 		case FTS_DC:			/* Warn, continue. */
273 			warnx("%s: directory causes a cycle", curr->fts_path);
274 			rval = 1;
275 			continue;
276 		case FTS_DP:			/* Ignore, continue. */
277 			continue;
278 		}
279 
280 		/*
281 		 * If we are in case (2) or (3) above, we need to append the
282                  * source name to the target name.
283                  */
284 		if (type != FILE_TO_FILE) {
285 			if ((curr->fts_namelen +
286 			    to.target_end - to.p_path + 1) > MAXPATHLEN) {
287 				warnx("%s/%s: name too long (not copied)",
288 				    to.p_path, curr->fts_name);
289 				rval = 1;
290 				continue;
291 			}
292 
293 			/*
294 			 * Need to remember the roots of traversals to create
295 			 * correct pathnames.  If there's a directory being
296 			 * copied to a non-existent directory, e.g.
297 			 *	cp -R a/dir noexist
298 			 * the resulting path name should be noexist/foo, not
299 			 * noexist/dir/foo (where foo is a file in dir), which
300 			 * is the case where the target exists.
301 			 *
302 			 * Also, check for "..".  This is for correct path
303 			 * concatentation for paths ending in "..", e.g.
304 			 *	cp -R .. /tmp
305 			 * Paths ending in ".." are changed to ".".  This is
306 			 * tricky, but seems the easiest way to fix the problem.
307 			 *
308 			 * XXX
309 			 * Since the first level MUST be FTS_ROOTLEVEL, base
310 			 * is always initialized.
311 			 */
312 			if (curr->fts_level == FTS_ROOTLEVEL)
313 				if (type != DIR_TO_DNE) {
314 					p = strrchr(curr->fts_path, '/');
315 					base = (p == NULL) ? 0 :
316 					    (int)(p - curr->fts_path + 1);
317 
318 					if (!strcmp(&curr->fts_path[base],
319 					    ".."))
320 						base += 1;
321 				} else
322 					base = curr->fts_pathlen;
323 
324 			if (to.target_end[-1] != '/') {
325 				*to.target_end = '/';
326 				*(to.target_end + 1) = 0;
327 			}
328 			p = &curr->fts_path[base];
329 			nlen = curr->fts_pathlen - base;
330 
331 			(void)strncat(to.target_end + 1, p, nlen);
332 			to.p_end = to.target_end + nlen + 1;
333 			*to.p_end = 0;
334 			STRIP_TRAILING_SLASH(to);
335 		}
336 
337 		/* Not an error but need to remember it happened */
338 		if (stat(to.p_path, &to_stat) == -1)
339 			dne = 1;
340 		else {
341 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
342 			    to_stat.st_ino == curr->fts_statp->st_ino) {
343 				warnx("%s and %s are identical (not copied).",
344 				    to.p_path, curr->fts_path);
345 				rval = 1;
346 				if (S_ISDIR(curr->fts_statp->st_mode))
347 					(void)fts_set(ftsp, curr, FTS_SKIP);
348 				continue;
349 			}
350 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
351 			    S_ISDIR(to_stat.st_mode)) {
352 		warnx("cannot overwrite directory %s with non-directory %s",
353 				    to.p_path, curr->fts_path);
354 				rval = 1;
355 				continue;
356 			}
357 			dne = 0;
358 		}
359 
360 		switch (curr->fts_statp->st_mode & S_IFMT) {
361 		case S_IFLNK:
362 			if (copy_link(curr, !dne))
363 				rval = 1;
364 			break;
365 		case S_IFDIR:
366 			if (!Rflag && !rflag) {
367 				warnx("%s is a directory (not copied).",
368 				    curr->fts_path);
369 				(void)fts_set(ftsp, curr, FTS_SKIP);
370 				rval = 1;
371 				break;
372 			}
373 			/*
374 			 * If the directory doesn't exist, create the new
375 			 * one with the from file mode plus owner RWX bits,
376 			 * modified by the umask.  Trade-off between being
377 			 * able to write the directory (if from directory is
378 			 * 555) and not causing a permissions race.  If the
379 			 * umask blocks owner writes, we fail..
380 			 */
381 			if (dne) {
382 				if (mkdir(to.p_path,
383 				    curr->fts_statp->st_mode | S_IRWXU) < 0)
384 					err(1, "%s", to.p_path);
385 			} else if (!S_ISDIR(to_stat.st_mode)) {
386 				errno = ENOTDIR;
387 				err(1, "%s", to.p_path);
388 			}
389 			/*
390 			 * If not -p and directory didn't exist, set it to be
391 			 * the same as the from directory, umodified by the
392                          * umask; arguably wrong, but it's been that way
393                          * forever.
394 			 */
395 			if (pflag && setfile(curr->fts_statp, 0))
396 				rval = 1;
397 			else if (dne)
398 				(void)chmod(to.p_path,
399 				    curr->fts_statp->st_mode);
400 			break;
401 		case S_IFBLK:
402 		case S_IFCHR:
403 			if (Rflag) {
404 				if (copy_special(curr->fts_statp, !dne))
405 					rval = 1;
406 			} else
407 				if (copy_file(curr, dne))
408 					rval = 1;
409 			break;
410 		case S_IFIFO:
411 			if (Rflag) {
412 				if (copy_fifo(curr->fts_statp, !dne))
413 					rval = 1;
414 			} else
415 				if (copy_file(curr, dne))
416 					rval = 1;
417 			break;
418 		default:
419 			if (copy_file(curr, dne))
420 				rval = 1;
421 			break;
422 		}
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