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