xref: /freebsd/bin/cp/utils.c (revision 2e620256bd76c449c835c604e404483437743011)
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 static ssize_t
72 copy_fallback(int from_fd, int to_fd)
73 {
74 	static char *buf = NULL;
75 	static size_t bufsize;
76 	ssize_t rcount, wresid, wcount = 0;
77 	char *bufp;
78 
79 	if (buf == NULL) {
80 		if (sysconf(_SC_PHYS_PAGES) > PHYSPAGES_THRESHOLD)
81 			bufsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
82 		else
83 			bufsize = BUFSIZE_SMALL;
84 		buf = malloc(bufsize);
85 		if (buf == NULL)
86 			err(1, "Not enough memory");
87 	}
88 	rcount = read(from_fd, buf, bufsize);
89 	if (rcount <= 0)
90 		return (rcount);
91 	for (bufp = buf, wresid = rcount; ; bufp += wcount, wresid -= wcount) {
92 		wcount = write(to_fd, bufp, wresid);
93 		if (wcount <= 0)
94 			break;
95 		if (wcount >= (ssize_t)wresid)
96 			break;
97 	}
98 	return (wcount < 0 ? wcount : rcount);
99 }
100 
101 int
102 copy_file(const FTSENT *entp, int dne)
103 {
104 	struct stat *fs;
105 	ssize_t wcount;
106 	off_t wtotal;
107 	int ch, checkch, from_fd, rval, to_fd;
108 	int use_copy_file_range = 1;
109 
110 	from_fd = to_fd = -1;
111 	if (!lflag && !sflag &&
112 	    (from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
113 		warn("%s", entp->fts_path);
114 		return (1);
115 	}
116 
117 	fs = entp->fts_statp;
118 
119 	/*
120 	 * If the file exists and we're interactive, verify with the user.
121 	 * If the file DNE, set the mode to be the from file, minus setuid
122 	 * bits, modified by the umask; arguably wrong, but it makes copying
123 	 * executables work right and it's been that way forever.  (The
124 	 * other choice is 666 or'ed with the execute bits on the from file
125 	 * modified by the umask.)
126 	 */
127 	if (!dne) {
128 #define YESNO "(y/n [n]) "
129 		if (nflag) {
130 			if (vflag)
131 				printf("%s not overwritten\n", to.p_path);
132 			rval = 1;
133 			goto done;
134 		} else if (iflag) {
135 			(void)fprintf(stderr, "overwrite %s? %s",
136 			    to.p_path, YESNO);
137 			checkch = ch = getchar();
138 			while (ch != '\n' && ch != EOF)
139 				ch = getchar();
140 			if (checkch != 'y' && checkch != 'Y') {
141 				(void)fprintf(stderr, "not overwritten\n");
142 				rval = 1;
143 				goto done;
144 			}
145 		}
146 
147 		if (fflag) {
148 			/*
149 			 * Remove existing destination file name create a new
150 			 * file.
151 			 */
152 			(void)unlink(to.p_path);
153 			if (!lflag && !sflag) {
154 				to_fd = open(to.p_path,
155 				    O_WRONLY | O_TRUNC | O_CREAT,
156 				    fs->st_mode & ~(S_ISUID | S_ISGID));
157 			}
158 		} else if (!lflag && !sflag) {
159 			/* Overwrite existing destination file name. */
160 			to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
161 		}
162 	} else if (!lflag && !sflag) {
163 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
164 		    fs->st_mode & ~(S_ISUID | S_ISGID));
165 	}
166 
167 	if (!lflag && !sflag && to_fd == -1) {
168 		warn("%s", to.p_path);
169 		rval = 1;
170 		goto done;
171 	}
172 
173 	rval = 0;
174 
175 	if (!lflag && !sflag) {
176 		wtotal = 0;
177 		do {
178 			if (use_copy_file_range) {
179 				wcount = copy_file_range(from_fd, NULL,
180 				    to_fd, NULL, SSIZE_MAX, 0);
181 				if (wcount < 0 && errno == EINVAL) {
182 					/* Prob a non-seekable FD */
183 					use_copy_file_range = 0;
184 				}
185 			}
186 			if (!use_copy_file_range) {
187 				wcount = copy_fallback(from_fd, to_fd);
188 			}
189 			wtotal += wcount;
190 			if (info) {
191 				info = 0;
192 				(void)fprintf(stderr,
193 				    "%s -> %s %3d%%\n",
194 				    entp->fts_path, to.p_path,
195 				    cp_pct(wtotal, fs->st_size));
196 			}
197 		} while (wcount > 0);
198 		if (wcount < 0) {
199 			warn("%s", entp->fts_path);
200 			rval = 1;
201 		}
202 	} else if (lflag) {
203 		if (link(entp->fts_path, to.p_path)) {
204 			warn("%s", to.p_path);
205 			rval = 1;
206 		}
207 	} else if (sflag) {
208 		if (symlink(entp->fts_path, to.p_path)) {
209 			warn("%s", to.p_path);
210 			rval = 1;
211 		}
212 	}
213 
214 	/*
215 	 * Don't remove the target even after an error.  The target might
216 	 * not be a regular file, or its attributes might be important,
217 	 * or its contents might be irreplaceable.  It would only be safe
218 	 * to remove it if we created it and its length is 0.
219 	 */
220 
221 	if (!lflag && !sflag) {
222 		if (pflag && setfile(fs, to_fd))
223 			rval = 1;
224 		if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
225 			rval = 1;
226 		if (close(to_fd)) {
227 			warn("%s", to.p_path);
228 			rval = 1;
229 		}
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 (!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 			warn("chflags: %s", to.p_path);
364 			rval = 1;
365 		}
366 
367 	return (rval);
368 }
369 
370 int
371 preserve_fd_acls(int source_fd, int dest_fd)
372 {
373 	acl_t acl;
374 	acl_type_t acl_type;
375 	int acl_supported = 0, ret, trivial;
376 
377 	ret = fpathconf(source_fd, _PC_ACL_NFS4);
378 	if (ret > 0 ) {
379 		acl_supported = 1;
380 		acl_type = ACL_TYPE_NFS4;
381 	} else if (ret < 0 && errno != EINVAL) {
382 		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", to.p_path);
383 		return (1);
384 	}
385 	if (acl_supported == 0) {
386 		ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
387 		if (ret > 0 ) {
388 			acl_supported = 1;
389 			acl_type = ACL_TYPE_ACCESS;
390 		} else if (ret < 0 && errno != EINVAL) {
391 			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
392 			    to.p_path);
393 			return (1);
394 		}
395 	}
396 	if (acl_supported == 0)
397 		return (0);
398 
399 	acl = acl_get_fd_np(source_fd, acl_type);
400 	if (acl == NULL) {
401 		warn("failed to get acl entries while setting %s", to.p_path);
402 		return (1);
403 	}
404 	if (acl_is_trivial_np(acl, &trivial)) {
405 		warn("acl_is_trivial() failed for %s", to.p_path);
406 		acl_free(acl);
407 		return (1);
408 	}
409 	if (trivial) {
410 		acl_free(acl);
411 		return (0);
412 	}
413 	if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
414 		warn("failed to set acl entries for %s", to.p_path);
415 		acl_free(acl);
416 		return (1);
417 	}
418 	acl_free(acl);
419 	return (0);
420 }
421 
422 int
423 preserve_dir_acls(struct stat *fs, char *source_dir, char *dest_dir)
424 {
425 	acl_t (*aclgetf)(const char *, acl_type_t);
426 	int (*aclsetf)(const char *, acl_type_t, acl_t);
427 	struct acl *aclp;
428 	acl_t acl;
429 	acl_type_t acl_type;
430 	int acl_supported = 0, ret, trivial;
431 
432 	ret = pathconf(source_dir, _PC_ACL_NFS4);
433 	if (ret > 0) {
434 		acl_supported = 1;
435 		acl_type = ACL_TYPE_NFS4;
436 	} else if (ret < 0 && errno != EINVAL) {
437 		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", source_dir);
438 		return (1);
439 	}
440 	if (acl_supported == 0) {
441 		ret = pathconf(source_dir, _PC_ACL_EXTENDED);
442 		if (ret > 0) {
443 			acl_supported = 1;
444 			acl_type = ACL_TYPE_ACCESS;
445 		} else if (ret < 0 && errno != EINVAL) {
446 			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
447 			    source_dir);
448 			return (1);
449 		}
450 	}
451 	if (acl_supported == 0)
452 		return (0);
453 
454 	/*
455 	 * If the file is a link we will not follow it.
456 	 */
457 	if (S_ISLNK(fs->st_mode)) {
458 		aclgetf = acl_get_link_np;
459 		aclsetf = acl_set_link_np;
460 	} else {
461 		aclgetf = acl_get_file;
462 		aclsetf = acl_set_file;
463 	}
464 	if (acl_type == ACL_TYPE_ACCESS) {
465 		/*
466 		 * Even if there is no ACL_TYPE_DEFAULT entry here, a zero
467 		 * size ACL will be returned. So it is not safe to simply
468 		 * check the pointer to see if the default ACL is present.
469 		 */
470 		acl = aclgetf(source_dir, ACL_TYPE_DEFAULT);
471 		if (acl == NULL) {
472 			warn("failed to get default acl entries on %s",
473 			    source_dir);
474 			return (1);
475 		}
476 		aclp = &acl->ats_acl;
477 		if (aclp->acl_cnt != 0 && aclsetf(dest_dir,
478 		    ACL_TYPE_DEFAULT, acl) < 0) {
479 			warn("failed to set default acl entries on %s",
480 			    dest_dir);
481 			acl_free(acl);
482 			return (1);
483 		}
484 		acl_free(acl);
485 	}
486 	acl = aclgetf(source_dir, acl_type);
487 	if (acl == NULL) {
488 		warn("failed to get acl entries on %s", source_dir);
489 		return (1);
490 	}
491 	if (acl_is_trivial_np(acl, &trivial)) {
492 		warn("acl_is_trivial() failed on %s", source_dir);
493 		acl_free(acl);
494 		return (1);
495 	}
496 	if (trivial) {
497 		acl_free(acl);
498 		return (0);
499 	}
500 	if (aclsetf(dest_dir, acl_type, acl) < 0) {
501 		warn("failed to set acl entries on %s", dest_dir);
502 		acl_free(acl);
503 		return (1);
504 	}
505 	acl_free(acl);
506 	return (0);
507 }
508 
509 void
510 usage(void)
511 {
512 
513 	(void)fprintf(stderr, "%s\n%s\n",
514 	    "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpsvx] "
515 	    "source_file target_file",
516 	    "       cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpsvx] "
517 	    "source_file ... "
518 	    "target_directory");
519 	exit(EX_USAGE);
520 }
521