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