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