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