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