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