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