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