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