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