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