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