xref: /openbsd-src/bin/mv/cp.c (revision 118f3e42b76268dc8437d2c7ac735983d5f294ad)
1 /*	$OpenBSD: cp.c,v 1.11 2024/10/14 08:26:48 jsg Exp $	*/
2 /*	$NetBSD: cp.c,v 1.14 1995/09/07 06:14:51 jtc Exp $	*/
3 /*	$NetBSD: utils.c,v 1.6 1997/02/26 14:40:51 cgd Exp $	*/
4 
5 /*
6  * Copyright (c) 1988, 1993, 1994
7  *	The Regents of the University of California.  All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * David Hitz of Auspex Systems Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. 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 /*
38  * Cp copies source files to target files.
39  *
40  * The global PATH_T structure "to" always contains the path to the
41  * current target file.  Since fts(3) does not change directories,
42  * this path can be either absolute or dot-relative.
43  *
44  * The basic algorithm is to initialize "to" and use fts(3) to traverse
45  * the file hierarchy rooted in the argument list.  A trivial case is the
46  * case of 'cp file1 file2'.  The more interesting case is the case of
47  * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
48  * path (relative to the root of the traversal) is appended to dir (stored
49  * in "to") to form the final target path.
50  */
51 
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <sys/mman.h>
55 #include <sys/time.h>
56 
57 #include <dirent.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <fts.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 #include <limits.h>
67 
68 #define	fts_dne(_x)	(_x->fts_pointer != NULL)
69 
70 typedef struct {
71 	char *p_end;                    /* pointer to NULL at end of path */
72 	char *target_end;               /* pointer to end of target base */
73 	char p_path[PATH_MAX];          /* pointer to the start of a path */
74 } PATH_T;
75 
76 static PATH_T to = { to.p_path, "" };
77 
78 static int     copy_fifo(struct stat *, int);
79 static int     copy_file(FTSENT *, int);
80 static int     copy_link(FTSENT *, int);
81 static int     copy_special(struct stat *, int);
82 static int     setfile(struct stat *, int);
83 
84 
85 extern char *__progname;
86 
87 static uid_t myuid;
88 static int fflag, iflag;
89 static mode_t myumask;
90 
91 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
92 
93 static int copy(char *[], enum op, int);
94 static char *find_last_component(char *);
95 
96 static void __dead
97 usage(void)
98 {
99 	(void)fprintf(stderr,
100 	    "usage: %s [-fip] [-R [-H | -L | -P]] source target\n", __progname);
101 	(void)fprintf(stderr,
102 	    "       %s [-fip] [-R [-H | -L | -P]] source ... directory\n",
103 	    __progname);
104 	exit(1);
105 }
106 
107 int
108 cpmain(int argc, char *argv[])
109 {
110 	struct stat to_stat, tmp_stat;
111 	enum op type;
112 	int fts_options, r;
113 	char *target;
114 
115 	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
116 
117 	myuid = getuid();
118 
119 	/* Copy the umask for explicit mode setting. */
120 	myumask = umask(0);
121 	(void)umask(myumask);
122 
123 	/* Save the target base in "to". */
124 	target = argv[--argc];
125 	if (strlcpy(to.p_path, target, sizeof to.p_path) >= sizeof(to.p_path))
126 		errx(1, "%s: name too long", target);
127 	to.p_end = to.p_path + strlen(to.p_path);
128 	if (to.p_path == to.p_end) {
129 		*to.p_end++ = '.';
130 		*to.p_end = '\0';
131 	}
132 	to.target_end = to.p_end;
133 
134 	/* Set end of argument list for fts(3). */
135 	argv[argc] = NULL;
136 
137 	/*
138 	 * Cp has two distinct cases:
139 	 *
140 	 * cp [-R] source target
141 	 * cp [-R] source1 ... sourceN directory
142 	 *
143 	 * In both cases, source can be either a file or a directory.
144 	 *
145 	 * In (1), the target becomes a copy of the source. That is, if the
146 	 * source is a file, the target will be a file, and likewise for
147 	 * directories.
148 	 *
149 	 * In (2), the real target is not directory, but "directory/source".
150 	 */
151 	r = stat(to.p_path, &to_stat);
152 	if (r == -1 && errno != ENOENT)
153 		err(1, "%s", to.p_path);
154 	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
155 		/*
156 		 * Case (1).  Target is not a directory.
157 		 */
158 		if (argc > 1)
159 			usage();
160 		/*
161 		 * Need to detect the case:
162 		 *	cp -R dir foo
163 		 * Where dir is a directory and foo does not exist, where
164 		 * we want pathname concatenations turned on but not for
165 		 * the initial mkdir().
166 		 */
167 		if (r == -1) {
168 			lstat(*argv, &tmp_stat);
169 
170 			if (S_ISDIR(tmp_stat.st_mode))
171 				type = DIR_TO_DNE;
172 			else
173 				type = FILE_TO_FILE;
174 		} else
175 			type = FILE_TO_FILE;
176 	} else {
177 		/*
178 		 * Case (2).  Target is a directory.
179 		 */
180 		type = FILE_TO_DIR;
181 	}
182 
183 	return (copy(argv, type, fts_options));
184 }
185 
186 static char *
187 find_last_component(char *path)
188 {
189 	char *p;
190 
191 	if ((p = strrchr(path, '/')) == NULL)
192 		p = path;
193 	else {
194 		/* Special case foo/ */
195 		if (!*(p+1)) {
196 			while ((p >= path) && *p == '/')
197 				p--;
198 
199 			while ((p >= path) && *p != '/')
200 				p--;
201 		}
202 
203 		p++;
204 	}
205 
206 	return (p);
207 }
208 
209 static int
210 copy(char *argv[], enum op type, int fts_options)
211 {
212 	struct stat to_stat;
213 	FTS *ftsp;
214 	FTSENT *curr;
215 	int base, nlen, rval;
216 	char *p, *target_mid;
217 	base = 0;
218 
219 	if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
220 		err(1, NULL);
221 	for (rval = 0; (curr = fts_read(ftsp)) != NULL;) {
222 		switch (curr->fts_info) {
223 		case FTS_NS:
224 		case FTS_DNR:
225 		case FTS_ERR:
226 			warnx("%s: %s",
227 			    curr->fts_path, strerror(curr->fts_errno));
228 			rval = 1;
229 			continue;
230 		case FTS_DC:
231 			warnx("%s: directory causes a cycle", curr->fts_path);
232 			rval = 1;
233 			continue;
234 		}
235 
236 		/*
237 		 * If we are in case (2) or (3) above, we need to append the
238 		 * source name to the target name.
239 		 */
240 		if (type != FILE_TO_FILE) {
241 			/*
242 			 * Need to remember the roots of traversals to create
243 			 * correct pathnames.  If there's a directory being
244 			 * copied to a non-existent directory, e.g.
245 			 *	cp -R a/dir noexist
246 			 * the resulting path name should be noexist/foo, not
247 			 * noexist/dir/foo (where foo is a file in dir), which
248 			 * is the case where the target exists.
249 			 *
250 			 * Also, check for "..".  This is for correct path
251 			 * concatenation for paths ending in "..", e.g.
252 			 *	cp -R .. /tmp
253 			 * Paths ending in ".." are changed to ".".  This is
254 			 * tricky, but seems the easiest way to fix the problem.
255 			 *
256 			 * XXX
257 			 * Since the first level MUST be FTS_ROOTLEVEL, base
258 			 * is always initialized.
259 			 */
260 			if (curr->fts_level == FTS_ROOTLEVEL) {
261 				if (type != DIR_TO_DNE) {
262 					p = find_last_component(curr->fts_path);
263 					base = p - curr->fts_path;
264 
265 					if (!strcmp(&curr->fts_path[base],
266 					    ".."))
267 						base += 1;
268 				} else
269 					base = curr->fts_pathlen;
270 			}
271 
272 			p = &curr->fts_path[base];
273 			nlen = curr->fts_pathlen - base;
274 			target_mid = to.target_end;
275 			if (*p != '/' && target_mid[-1] != '/')
276 				*target_mid++ = '/';
277 			*target_mid = '\0';
278 			if (target_mid - to.p_path + nlen >= PATH_MAX) {
279 				warnx("%s%s: name too long (not copied)",
280 				    to.p_path, p);
281 				rval = 1;
282 				continue;
283 			}
284 			(void)strncat(target_mid, p, nlen);
285 			to.p_end = target_mid + nlen;
286 			*to.p_end = '\0';
287 		}
288 
289 		/* Not an error but need to remember it happened */
290 		if (stat(to.p_path, &to_stat) == -1) {
291 			if (curr->fts_info == FTS_DP)
292 				continue;
293 			/*
294 			 * We use fts_pointer as a boolean to indicate that
295 			 * we created this directory ourselves.  We'll use
296 			 * this later on via the fts_dne macro to decide
297 			 * whether or not to set the directory mode during
298 			 * the post-order pass.
299 			 */
300 			curr->fts_pointer = (void *)1;
301 		} else {
302 			/*
303 			 * Set directory mode/user/times on the post-order
304 			 * pass.  We can't do this earlier because the mode
305 			 * may not allow us write permission.  Furthermore,
306 			 * if we set the times during the pre-order pass,
307 			 * they will get changed later when the directory
308 			 * is populated.
309 			 */
310 			if (curr->fts_info == FTS_DP) {
311 				if (!S_ISDIR(to_stat.st_mode))
312 					continue;
313 				/*
314 				 * If not -p and directory didn't exist, set
315 				 * it to be the same as the from directory,
316 				 * unmodified by the umask; arguably wrong,
317 				 * but it's been that way forever.
318 				 */
319 				if (setfile(curr->fts_statp, -1))
320 					rval = 1;
321 				else if (fts_dne(curr))
322 					(void)chmod(to.p_path,
323 					    curr->fts_statp->st_mode);
324 				continue;
325 			}
326 			if (to_stat.st_dev == curr->fts_statp->st_dev &&
327 			    to_stat.st_ino == curr->fts_statp->st_ino) {
328 				warnx("%s and %s are identical (not copied).",
329 				    to.p_path, curr->fts_path);
330 				rval = 1;
331 				if (S_ISDIR(curr->fts_statp->st_mode))
332 					(void)fts_set(ftsp, curr, FTS_SKIP);
333 				continue;
334 			}
335 			if (!S_ISDIR(curr->fts_statp->st_mode) &&
336 			    S_ISDIR(to_stat.st_mode)) {
337 		warnx("cannot overwrite directory %s with non-directory %s",
338 				    to.p_path, curr->fts_path);
339 				rval = 1;
340 				continue;
341 			}
342 		}
343 
344 		switch (curr->fts_statp->st_mode & S_IFMT) {
345 		case S_IFLNK:
346 			if (copy_link(curr, !fts_dne(curr)))
347 				rval = 1;
348 			break;
349 		case S_IFDIR:
350 			/*
351 			 * If the directory doesn't exist, create the new
352 			 * one with the from file mode plus owner RWX bits,
353 			 * modified by the umask.  Trade-off between being
354 			 * able to write the directory (if from directory is
355 			 * 555) and not causing a permissions race.  If the
356 			 * umask blocks owner writes, we fail..
357 			 */
358 			if (fts_dne(curr)) {
359 				if (mkdir(to.p_path,
360 				    curr->fts_statp->st_mode | S_IRWXU) == -1)
361 					err(1, "%s", to.p_path);
362 			} else if (!S_ISDIR(to_stat.st_mode))
363 				errc(1, ENOTDIR, "%s", to.p_path);
364 			break;
365 		case S_IFBLK:
366 		case S_IFCHR:
367 				if (copy_special(curr->fts_statp, !fts_dne(curr)))
368 					rval = 1;
369 			break;
370 		case S_IFIFO:
371 				if (copy_fifo(curr->fts_statp, !fts_dne(curr)))
372 					rval = 1;
373 			break;
374 		case S_IFSOCK:
375 			warnc(EOPNOTSUPP, "%s", curr->fts_path);
376 			break;
377 		default:
378 			if (copy_file(curr, fts_dne(curr)))
379 				rval = 1;
380 			break;
381 		}
382 	}
383 	if (errno)
384 		err(1, "fts_read");
385 	(void)fts_close(ftsp);
386 	return (rval);
387 }
388 
389 #define _MAXBSIZE	(64 * 1024)
390 
391 static int
392 copy_file(FTSENT *entp, int dne)
393 {
394 	static char *buf;
395 	static char *zeroes;
396 	struct stat *fs;
397 	int ch, checkch, from_fd, rcount, rval, to_fd, wcount;
398 	const size_t buflen = _MAXBSIZE;
399 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
400 	char *p;
401 #endif
402 
403 	if (!buf) {
404 		buf = malloc(buflen);
405 		if (!buf)
406 			err(1, "malloc");
407 	}
408 	if (!zeroes) {
409 		zeroes = calloc(1, buflen);
410 		if (!zeroes)
411 			err(1, "calloc");
412 	}
413 
414 	if ((from_fd = open(entp->fts_path, O_RDONLY)) == -1) {
415 		warn("%s", entp->fts_path);
416 		return (1);
417 	}
418 
419 	fs = entp->fts_statp;
420 
421 	/*
422 	 * In -f (force) mode, we always unlink the destination first
423 	 * if it exists.  Note that -i and -f are mutually exclusive.
424 	 */
425 	if (!dne && fflag)
426 		(void)unlink(to.p_path);
427 
428 	/*
429 	 * If the file exists and we're interactive, verify with the user.
430 	 * If the file DNE, set the mode to be the from file, minus setuid
431 	 * bits, modified by the umask; arguably wrong, but it makes copying
432 	 * executables work right and it's been that way forever.  (The
433 	 * other choice is 666 or'ed with the execute bits on the from file
434 	 * modified by the umask.)
435 	 */
436 	if (!dne && !fflag) {
437 		if (iflag) {
438 			(void)fprintf(stderr, "overwrite %s? ", to.p_path);
439 			checkch = ch = getchar();
440 			while (ch != '\n' && ch != EOF)
441 				ch = getchar();
442 			if (checkch != 'y' && checkch != 'Y') {
443 				(void)close(from_fd);
444 				return (0);
445 			}
446 		}
447 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC);
448 	} else
449 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
450 		    fs->st_mode & ~(S_ISTXT | S_ISUID | S_ISGID));
451 
452 	if (to_fd == -1) {
453 		warn("%s", to.p_path);
454 		(void)close(from_fd);
455 		return (1);
456 	}
457 
458 	rval = 0;
459 
460 	/*
461 	 * Mmap and write if less than 8M (the limit is so we don't totally
462 	 * trash memory on big files.  This is really a minor hack, but it
463 	 * wins some CPU back.
464 	 */
465 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
466 	/* XXX broken for 0-size mmap */
467 	if (fs->st_size <= 8 * 1048576) {
468 		if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
469 		    MAP_FILE|MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
470 			warn("mmap: %s", entp->fts_path);
471 			rval = 1;
472 		} else {
473 			madvise(p, fs->st_size, MADV_SEQUENTIAL);
474 			if (write(to_fd, p, fs->st_size) != fs->st_size) {
475 				warn("%s", to.p_path);
476 				rval = 1;
477 			}
478 			/* Some systems don't unmap on close(2). */
479 			if (munmap(p, fs->st_size) == -1) {
480 				warn("%s", entp->fts_path);
481 				rval = 1;
482 			}
483 		}
484 	} else
485 #endif
486 	{
487 		int skipholes = 0;
488 		struct stat tosb;
489 		if (!fstat(to_fd, &tosb) && S_ISREG(tosb.st_mode))
490 			skipholes = 1;
491 		while ((rcount = read(from_fd, buf, buflen)) > 0) {
492 			if (skipholes && memcmp(buf, zeroes, rcount) == 0)
493 				wcount = lseek(to_fd, rcount, SEEK_CUR) == -1 ? -1 : rcount;
494 			else
495 				wcount = write(to_fd, buf, rcount);
496 			if (rcount != wcount || wcount == -1) {
497 				warn("%s", to.p_path);
498 				rval = 1;
499 				break;
500 			}
501 		}
502 		if (skipholes && rcount >= 0)
503 			rcount = ftruncate(to_fd, lseek(to_fd, 0, SEEK_CUR));
504 		if (rcount == -1) {
505 			warn("%s", entp->fts_path);
506 			rval = 1;
507 		}
508 	}
509 
510 	if (rval == 1) {
511 		(void)close(from_fd);
512 		(void)close(to_fd);
513 		return (1);
514 	}
515 
516 	if (setfile(fs, to_fd))
517 		rval = 1;
518 	(void)close(from_fd);
519 	if (close(to_fd)) {
520 		warn("%s", to.p_path);
521 		rval = 1;
522 	}
523 	return (rval);
524 }
525 
526 static int
527 copy_link(FTSENT *p, int exists)
528 {
529 	int len;
530 	char linkname[PATH_MAX];
531 
532 	if ((len = readlink(p->fts_path, linkname, sizeof(linkname)-1)) == -1) {
533 		warn("readlink: %s", p->fts_path);
534 		return (1);
535 	}
536 	linkname[len] = '\0';
537 	if (exists && unlink(to.p_path)) {
538 		warn("unlink: %s", to.p_path);
539 		return (1);
540 	}
541 	if (symlink(linkname, to.p_path)) {
542 		warn("symlink: %s", linkname);
543 		return (1);
544 	}
545 	return (setfile(p->fts_statp, -1));
546 }
547 
548 static int
549 copy_fifo(struct stat *from_stat, int exists)
550 {
551 	if (exists && unlink(to.p_path)) {
552 		warn("unlink: %s", to.p_path);
553 		return (1);
554 	}
555 	if (mkfifo(to.p_path, from_stat->st_mode)) {
556 		warn("mkfifo: %s", to.p_path);
557 		return (1);
558 	}
559 	return (setfile(from_stat, -1));
560 }
561 
562 static int
563 copy_special(struct stat *from_stat, int exists)
564 {
565 	if (exists && unlink(to.p_path)) {
566 		warn("unlink: %s", to.p_path);
567 		return (1);
568 	}
569 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
570 		warn("mknod: %s", to.p_path);
571 		return (1);
572 	}
573 	return (setfile(from_stat, -1));
574 }
575 
576 
577 static int
578 setfile(struct stat *fs, int fd)
579 {
580 	struct timespec ts[2];
581 	int rval;
582 
583 	rval = 0;
584 	fs->st_mode &= S_ISTXT | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
585 
586 	ts[0] = fs->st_atim;
587 	ts[1] = fs->st_mtim;
588 	if (fd >= 0 ? futimens(fd, ts) :
589 	    utimensat(AT_FDCWD, to.p_path, ts, AT_SYMLINK_NOFOLLOW)) {
590 		warn("update times: %s", to.p_path);
591 		rval = 1;
592 	}
593 	/*
594 	 * Changing the ownership probably won't succeed, unless we're root
595 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
596 	 * the mode; current BSD behavior is to remove all setuid bits on
597 	 * chown.  If chown fails, lose setuid/setgid bits.
598 	 */
599 	if (fd >= 0 ? fchown(fd, fs->st_uid, fs->st_gid) :
600 	    lchown(to.p_path, fs->st_uid, fs->st_gid)) {
601 		if (errno != EPERM) {
602 			warn("chown: %s", to.p_path);
603 			rval = 1;
604 		}
605 		fs->st_mode &= ~(S_ISTXT | S_ISUID | S_ISGID);
606 	}
607 	if (fd >= 0 ? fchmod(fd, fs->st_mode) :
608 	    fchmodat(AT_FDCWD, to.p_path, fs->st_mode, AT_SYMLINK_NOFOLLOW)) {
609 		warn("chmod: %s", to.p_path);
610 		rval = 1;
611 	}
612 
613 	/*
614 	 * XXX
615 	 * NFS doesn't support chflags; ignore errors unless there's reason
616 	 * to believe we're losing bits.  (Note, this still won't be right
617 	 * if the server supports flags and we were trying to *remove* flags
618 	 * on a file that we copied, i.e., that we didn't create.)
619 	 */
620 	errno = 0;
621 	if (fd >= 0 ? fchflags(fd, fs->st_flags) :
622 	    chflagsat(AT_FDCWD, to.p_path, fs->st_flags, AT_SYMLINK_NOFOLLOW))
623 		if (errno != EOPNOTSUPP || fs->st_flags != 0) {
624 			warn("chflags: %s", to.p_path);
625 			rval = 1;
626 		}
627 	return (rval);
628 }
629