1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1991, 1993, 1994
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#include <sys/param.h>
33#include <sys/acl.h>
34#include <sys/stat.h>
35
36#include <err.h>
37#include <errno.h>
38#include <fcntl.h>
39#include <fts.h>
40#include <limits.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <sysexits.h>
44#include <unistd.h>
45
46#include "extern.h"
47
48#define	cp_pct(x, y)	((y == 0) ? 0 : (int)(100.0 * (x) / (y)))
49
50/*
51 * Memory strategy threshold, in pages: if physmem is larger then this, use a
52 * large buffer.
53 */
54#define PHYSPAGES_THRESHOLD (32*1024)
55
56/* Maximum buffer size in bytes - do not allow it to grow larger than this. */
57#define BUFSIZE_MAX (2*1024*1024)
58
59/*
60 * Small (default) buffer size in bytes. It's inefficient for this to be
61 * smaller than MAXPHYS.
62 */
63#define BUFSIZE_SMALL (MAXPHYS)
64
65/*
66 * Prompt used in -i case.
67 */
68#define YESNO "(y/n [n]) "
69
70static ssize_t
71copy_fallback(int from_fd, int to_fd)
72{
73	static char *buf = NULL;
74	static size_t bufsize;
75	ssize_t rcount, wresid, wcount = 0;
76	char *bufp;
77
78	if (buf == NULL) {
79		if (sysconf(_SC_PHYS_PAGES) > PHYSPAGES_THRESHOLD)
80			bufsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
81		else
82			bufsize = BUFSIZE_SMALL;
83		buf = malloc(bufsize);
84		if (buf == NULL)
85			err(1, "Not enough memory");
86	}
87	rcount = read(from_fd, buf, bufsize);
88	if (rcount <= 0)
89		return (rcount);
90	for (bufp = buf, wresid = rcount; ; bufp += wcount, wresid -= wcount) {
91		wcount = write(to_fd, bufp, wresid);
92		if (wcount <= 0)
93			break;
94		if (wcount >= wresid)
95			break;
96	}
97	return (wcount < 0 ? wcount : rcount);
98}
99
100int
101copy_file(const FTSENT *entp, int dne)
102{
103	struct stat sb, *fs;
104	ssize_t wcount;
105	off_t wtotal;
106	int ch, checkch, from_fd, rval, to_fd;
107	int use_copy_file_range = 1;
108
109	fs = entp->fts_statp;
110	from_fd = to_fd = -1;
111	if (!lflag && !sflag) {
112		if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) < 0 ||
113		    fstat(from_fd, &sb) != 0) {
114			warn("%s", entp->fts_path);
115			if (from_fd >= 0)
116				(void)close(from_fd);
117			return (1);
118		}
119		/*
120		 * Check that the file hasn't been replaced with one of a
121		 * different type.  This can happen if we've been asked to
122		 * copy something which is actively being modified and
123		 * lost the race, or if we've been asked to copy something
124		 * like /proc/X/fd/Y which stat(2) reports as S_IFREG but
125		 * is actually something else once you open it.
126		 */
127		if ((sb.st_mode & S_IFMT) != (fs->st_mode & S_IFMT)) {
128			warnx("%s: File changed", entp->fts_path);
129			(void)close(from_fd);
130			return (1);
131		}
132	}
133
134	/*
135	 * If the file exists and we're interactive, verify with the user.
136	 * If the file DNE, set the mode to be the from file, minus setuid
137	 * bits, modified by the umask; arguably wrong, but it makes copying
138	 * executables work right and it's been that way forever.  (The
139	 * other choice is 666 or'ed with the execute bits on the from file
140	 * modified by the umask.)
141	 */
142	if (!dne) {
143		if (nflag) {
144			if (vflag)
145				printf("%s not overwritten\n", to.p_path);
146			rval = 1;
147			goto done;
148		} else if (iflag) {
149			(void)fprintf(stderr, "overwrite %s? %s",
150			    to.p_path, YESNO);
151			checkch = ch = getchar();
152			while (ch != '\n' && ch != EOF)
153				ch = getchar();
154			if (checkch != 'y' && checkch != 'Y') {
155				(void)fprintf(stderr, "not overwritten\n");
156				rval = 1;
157				goto done;
158			}
159		}
160
161		if (fflag) {
162			/* remove existing destination file */
163			(void)unlink(to.p_path);
164			dne = 1;
165		}
166	}
167
168	rval = 0;
169
170	if (lflag) {
171		if (link(entp->fts_path, to.p_path) != 0) {
172			warn("%s", to.p_path);
173			rval = 1;
174		}
175		goto done;
176	}
177
178	if (sflag) {
179		if (symlink(entp->fts_path, to.p_path) != 0) {
180			warn("%s", to.p_path);
181			rval = 1;
182		}
183		goto done;
184	}
185
186	if (!dne) {
187		/* overwrite existing destination file */
188		to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
189	} else {
190		/* create new destination file */
191		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
192		    fs->st_mode & ~(S_ISUID | S_ISGID));
193	}
194	if (to_fd == -1) {
195		warn("%s", to.p_path);
196		rval = 1;
197		goto done;
198	}
199
200	wtotal = 0;
201	do {
202		if (use_copy_file_range) {
203			wcount = copy_file_range(from_fd, NULL,
204			    to_fd, NULL, SSIZE_MAX, 0);
205			if (wcount < 0 && errno == EINVAL) {
206				/* probably a non-seekable descriptor */
207				use_copy_file_range = 0;
208			}
209		}
210		if (!use_copy_file_range) {
211			wcount = copy_fallback(from_fd, to_fd);
212		}
213		wtotal += wcount;
214		if (info) {
215			info = 0;
216			(void)fprintf(stderr,
217			    "%s -> %s %3d%%\n",
218			    entp->fts_path, to.p_path,
219			    cp_pct(wtotal, fs->st_size));
220		}
221	} while (wcount > 0);
222	if (wcount < 0) {
223		warn("%s", entp->fts_path);
224		rval = 1;
225	}
226
227	/*
228	 * Don't remove the target even after an error.  The target might
229	 * not be a regular file, or its attributes might be important,
230	 * or its contents might be irreplaceable.  It would only be safe
231	 * to remove it if we created it and its length is 0.
232	 */
233	if (pflag && setfile(fs, to_fd))
234		rval = 1;
235	if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
236		rval = 1;
237	if (close(to_fd)) {
238		warn("%s", to.p_path);
239		rval = 1;
240	}
241
242done:
243	if (from_fd != -1)
244		(void)close(from_fd);
245	return (rval);
246}
247
248int
249copy_link(const FTSENT *p, int exists)
250{
251	ssize_t len;
252	char llink[PATH_MAX];
253
254	if (exists && nflag) {
255		if (vflag)
256			printf("%s not overwritten\n", to.p_path);
257		return (1);
258	}
259	if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
260		warn("readlink: %s", p->fts_path);
261		return (1);
262	}
263	llink[len] = '\0';
264	if (exists && unlink(to.p_path)) {
265		warn("unlink: %s", to.p_path);
266		return (1);
267	}
268	if (symlink(llink, to.p_path)) {
269		warn("symlink: %s", llink);
270		return (1);
271	}
272	return (pflag ? setfile(p->fts_statp, -1) : 0);
273}
274
275int
276copy_fifo(struct stat *from_stat, int exists)
277{
278
279	if (exists && nflag) {
280		if (vflag)
281			printf("%s not overwritten\n", to.p_path);
282		return (1);
283	}
284	if (exists && unlink(to.p_path)) {
285		warn("unlink: %s", to.p_path);
286		return (1);
287	}
288	if (mkfifo(to.p_path, from_stat->st_mode)) {
289		warn("mkfifo: %s", to.p_path);
290		return (1);
291	}
292	return (pflag ? setfile(from_stat, -1) : 0);
293}
294
295int
296copy_special(struct stat *from_stat, int exists)
297{
298
299	if (exists && nflag) {
300		if (vflag)
301			printf("%s not overwritten\n", to.p_path);
302		return (1);
303	}
304	if (exists && unlink(to.p_path)) {
305		warn("unlink: %s", to.p_path);
306		return (1);
307	}
308	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
309		warn("mknod: %s", to.p_path);
310		return (1);
311	}
312	return (pflag ? setfile(from_stat, -1) : 0);
313}
314
315int
316setfile(struct stat *fs, int fd)
317{
318	static struct timespec tspec[2];
319	struct stat ts;
320	int rval, gotstat, islink, fdval;
321
322	rval = 0;
323	fdval = fd != -1;
324	islink = !fdval && S_ISLNK(fs->st_mode);
325	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
326	    S_IRWXU | S_IRWXG | S_IRWXO;
327
328	tspec[0] = fs->st_atim;
329	tspec[1] = fs->st_mtim;
330	if (fdval ? futimens(fd, tspec) : utimensat(AT_FDCWD, to.p_path, tspec,
331	    islink ? AT_SYMLINK_NOFOLLOW : 0)) {
332		warn("utimensat: %s", to.p_path);
333		rval = 1;
334	}
335	if (fdval ? fstat(fd, &ts) :
336	    (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
337		gotstat = 0;
338	else {
339		gotstat = 1;
340		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
341		    S_IRWXU | S_IRWXG | S_IRWXO;
342	}
343	/*
344	 * Changing the ownership probably won't succeed, unless we're root
345	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
346	 * the mode; current BSD behavior is to remove all setuid bits on
347	 * chown.  If chown fails, lose setuid/setgid bits.
348	 */
349	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
350		if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
351		    (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
352		    chown(to.p_path, fs->st_uid, fs->st_gid))) {
353			if (errno != EPERM) {
354				warn("chown: %s", to.p_path);
355				rval = 1;
356			}
357			fs->st_mode &= ~(S_ISUID | S_ISGID);
358		}
359
360	if (!gotstat || fs->st_mode != ts.st_mode)
361		if (fdval ? fchmod(fd, fs->st_mode) :
362		    (islink ? lchmod(to.p_path, fs->st_mode) :
363		    chmod(to.p_path, fs->st_mode))) {
364			warn("chmod: %s", to.p_path);
365			rval = 1;
366		}
367
368	if (!Nflag && (!gotstat || fs->st_flags != ts.st_flags))
369		if (fdval ?
370		    fchflags(fd, fs->st_flags) :
371		    (islink ? lchflags(to.p_path, fs->st_flags) :
372		    chflags(to.p_path, fs->st_flags))) {
373			/*
374			 * NFS doesn't support chflags; ignore errors unless
375			 * there's reason to believe we're losing bits.  (Note,
376			 * this still won't be right if the server supports
377			 * flags and we were trying to *remove* flags on a file
378			 * that we copied, i.e., that we didn't create.)
379			 */
380			if (errno != EOPNOTSUPP || fs->st_flags != 0) {
381				warn("chflags: %s", to.p_path);
382				rval = 1;
383			}
384		}
385
386	return (rval);
387}
388
389int
390preserve_fd_acls(int source_fd, int dest_fd)
391{
392	acl_t acl;
393	acl_type_t acl_type;
394	int acl_supported = 0, ret, trivial;
395
396	ret = fpathconf(source_fd, _PC_ACL_NFS4);
397	if (ret > 0 ) {
398		acl_supported = 1;
399		acl_type = ACL_TYPE_NFS4;
400	} else if (ret < 0 && errno != EINVAL) {
401		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", to.p_path);
402		return (1);
403	}
404	if (acl_supported == 0) {
405		ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
406		if (ret > 0 ) {
407			acl_supported = 1;
408			acl_type = ACL_TYPE_ACCESS;
409		} else if (ret < 0 && errno != EINVAL) {
410			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
411			    to.p_path);
412			return (1);
413		}
414	}
415	if (acl_supported == 0)
416		return (0);
417
418	acl = acl_get_fd_np(source_fd, acl_type);
419	if (acl == NULL) {
420		warn("failed to get acl entries while setting %s", to.p_path);
421		return (1);
422	}
423	if (acl_is_trivial_np(acl, &trivial)) {
424		warn("acl_is_trivial() failed for %s", to.p_path);
425		acl_free(acl);
426		return (1);
427	}
428	if (trivial) {
429		acl_free(acl);
430		return (0);
431	}
432	if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
433		warn("failed to set acl entries for %s", to.p_path);
434		acl_free(acl);
435		return (1);
436	}
437	acl_free(acl);
438	return (0);
439}
440
441int
442preserve_dir_acls(struct stat *fs, char *source_dir, char *dest_dir)
443{
444	acl_t (*aclgetf)(const char *, acl_type_t);
445	int (*aclsetf)(const char *, acl_type_t, acl_t);
446	struct acl *aclp;
447	acl_t acl;
448	acl_type_t acl_type;
449	int acl_supported = 0, ret, trivial;
450
451	ret = pathconf(source_dir, _PC_ACL_NFS4);
452	if (ret > 0) {
453		acl_supported = 1;
454		acl_type = ACL_TYPE_NFS4;
455	} else if (ret < 0 && errno != EINVAL) {
456		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", source_dir);
457		return (1);
458	}
459	if (acl_supported == 0) {
460		ret = pathconf(source_dir, _PC_ACL_EXTENDED);
461		if (ret > 0) {
462			acl_supported = 1;
463			acl_type = ACL_TYPE_ACCESS;
464		} else if (ret < 0 && errno != EINVAL) {
465			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
466			    source_dir);
467			return (1);
468		}
469	}
470	if (acl_supported == 0)
471		return (0);
472
473	/*
474	 * If the file is a link we will not follow it.
475	 */
476	if (S_ISLNK(fs->st_mode)) {
477		aclgetf = acl_get_link_np;
478		aclsetf = acl_set_link_np;
479	} else {
480		aclgetf = acl_get_file;
481		aclsetf = acl_set_file;
482	}
483	if (acl_type == ACL_TYPE_ACCESS) {
484		/*
485		 * Even if there is no ACL_TYPE_DEFAULT entry here, a zero
486		 * size ACL will be returned. So it is not safe to simply
487		 * check the pointer to see if the default ACL is present.
488		 */
489		acl = aclgetf(source_dir, ACL_TYPE_DEFAULT);
490		if (acl == NULL) {
491			warn("failed to get default acl entries on %s",
492			    source_dir);
493			return (1);
494		}
495		aclp = &acl->ats_acl;
496		if (aclp->acl_cnt != 0 && aclsetf(dest_dir,
497		    ACL_TYPE_DEFAULT, acl) < 0) {
498			warn("failed to set default acl entries on %s",
499			    dest_dir);
500			acl_free(acl);
501			return (1);
502		}
503		acl_free(acl);
504	}
505	acl = aclgetf(source_dir, acl_type);
506	if (acl == NULL) {
507		warn("failed to get acl entries on %s", source_dir);
508		return (1);
509	}
510	if (acl_is_trivial_np(acl, &trivial)) {
511		warn("acl_is_trivial() failed on %s", source_dir);
512		acl_free(acl);
513		return (1);
514	}
515	if (trivial) {
516		acl_free(acl);
517		return (0);
518	}
519	if (aclsetf(dest_dir, acl_type, acl) < 0) {
520		warn("failed to set acl entries on %s", dest_dir);
521		acl_free(acl);
522		return (1);
523	}
524	acl_free(acl);
525	return (0);
526}
527
528void
529usage(void)
530{
531
532	(void)fprintf(stderr, "%s\n%s\n",
533	    "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpsvx] "
534	    "source_file target_file",
535	    "       cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpsvx] "
536	    "source_file ... "
537	    "target_directory");
538	exit(EX_USAGE);
539}
540