xref: /freebsd/bin/cp/utils.c (revision b670c9bafc0e31c7609969bf374b2e80bdc00211)
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 <stdbool.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <sysexits.h>
45 #include <unistd.h>
46 
47 #include "extern.h"
48 
49 #define	cp_pct(x, y)	((y == 0) ? 0 : (int)(100.0 * (x) / (y)))
50 
51 /*
52  * Memory strategy threshold, in pages: if physmem is larger then this, use a
53  * large buffer.
54  */
55 #define PHYSPAGES_THRESHOLD (32*1024)
56 
57 /* Maximum buffer size in bytes - do not allow it to grow larger than this. */
58 #define BUFSIZE_MAX (2*1024*1024)
59 
60 /*
61  * Small (default) buffer size in bytes. It's inefficient for this to be
62  * smaller than MAXPHYS.
63  */
64 #define BUFSIZE_SMALL (MAXPHYS)
65 
66 /*
67  * Prompt used in -i case.
68  */
69 #define YESNO "(y/n [n]) "
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 >= wresid)
96 			break;
97 	}
98 	return (wcount < 0 ? wcount : rcount);
99 }
100 
101 int
102 copy_file(const FTSENT *entp, bool dne, bool beneath)
103 {
104 	struct stat sb, *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 	fs = entp->fts_statp;
111 	from_fd = to_fd = -1;
112 	if (!lflag && !sflag) {
113 		if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) < 0 ||
114 		    fstat(from_fd, &sb) != 0) {
115 			warn("%s", entp->fts_path);
116 			if (from_fd >= 0)
117 				(void)close(from_fd);
118 			return (1);
119 		}
120 		/*
121 		 * Check that the file hasn't been replaced with one of a
122 		 * different type.  This can happen if we've been asked to
123 		 * copy something which is actively being modified and
124 		 * lost the race, or if we've been asked to copy something
125 		 * like /proc/X/fd/Y which stat(2) reports as S_IFREG but
126 		 * is actually something else once you open it.
127 		 */
128 		if ((sb.st_mode & S_IFMT) != (fs->st_mode & S_IFMT)) {
129 			warnx("%s: File changed", entp->fts_path);
130 			(void)close(from_fd);
131 			return (1);
132 		}
133 	}
134 
135 	/*
136 	 * If the file exists and we're interactive, verify with the user.
137 	 * If the file DNE, set the mode to be the from file, minus setuid
138 	 * bits, modified by the umask; arguably wrong, but it makes copying
139 	 * executables work right and it's been that way forever.  (The
140 	 * other choice is 666 or'ed with the execute bits on the from file
141 	 * modified by the umask.)
142 	 */
143 	if (!dne) {
144 		if (nflag) {
145 			if (vflag)
146 				printf("%s%s not overwritten\n",
147 				    to.base, to.path);
148 			rval = 1;
149 			goto done;
150 		} else if (iflag) {
151 			(void)fprintf(stderr, "overwrite %s%s? %s",
152 			    to.base, to.path, YESNO);
153 			checkch = ch = getchar();
154 			while (ch != '\n' && ch != EOF)
155 				ch = getchar();
156 			if (checkch != 'y' && checkch != 'Y') {
157 				(void)fprintf(stderr, "not overwritten\n");
158 				rval = 1;
159 				goto done;
160 			}
161 		}
162 
163 		if (fflag) {
164 			/* remove existing destination file */
165 			(void)unlinkat(to.dir, to.path,
166 			    beneath ? AT_RESOLVE_BENEATH : 0);
167 			dne = 1;
168 		}
169 	}
170 
171 	rval = 0;
172 
173 	if (lflag) {
174 		if (linkat(AT_FDCWD, entp->fts_path, to.dir, to.path, 0) != 0) {
175 			warn("%s%s", to.base, to.path);
176 			rval = 1;
177 		}
178 		goto done;
179 	}
180 
181 	if (sflag) {
182 		if (symlinkat(entp->fts_path, to.dir, to.path) != 0) {
183 			warn("%s%s", to.base, to.path);
184 			rval = 1;
185 		}
186 		goto done;
187 	}
188 
189 	if (!dne) {
190 		/* overwrite existing destination file */
191 		to_fd = openat(to.dir, to.path,
192 		    O_WRONLY | O_TRUNC | (beneath ? O_RESOLVE_BENEATH : 0), 0);
193 	} else {
194 		/* create new destination file */
195 		to_fd = openat(to.dir, to.path,
196 		    O_WRONLY | O_TRUNC | O_CREAT |
197 		    (beneath ? O_RESOLVE_BENEATH : 0),
198 		    fs->st_mode & ~(S_ISUID | S_ISGID));
199 	}
200 	if (to_fd == -1) {
201 		warn("%s%s", to.base, to.path);
202 		rval = 1;
203 		goto done;
204 	}
205 
206 	wtotal = 0;
207 	do {
208 		if (use_copy_file_range) {
209 			wcount = copy_file_range(from_fd, NULL,
210 			    to_fd, NULL, SSIZE_MAX, 0);
211 			if (wcount < 0 && errno == EINVAL) {
212 				/* probably a non-seekable descriptor */
213 				use_copy_file_range = 0;
214 			}
215 		}
216 		if (!use_copy_file_range) {
217 			wcount = copy_fallback(from_fd, to_fd);
218 		}
219 		wtotal += wcount;
220 		if (info) {
221 			info = 0;
222 			(void)fprintf(stderr,
223 			    "%s -> %s%s %3d%%\n",
224 			    entp->fts_path, to.base, to.path,
225 			    cp_pct(wtotal, fs->st_size));
226 		}
227 	} while (wcount > 0);
228 	if (wcount < 0) {
229 		warn("%s", entp->fts_path);
230 		rval = 1;
231 	}
232 
233 	/*
234 	 * Don't remove the target even after an error.  The target might
235 	 * not be a regular file, or its attributes might be important,
236 	 * or its contents might be irreplaceable.  It would only be safe
237 	 * to remove it if we created it and its length is 0.
238 	 */
239 	if (pflag && setfile(fs, to_fd, beneath))
240 		rval = 1;
241 	if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
242 		rval = 1;
243 	if (close(to_fd)) {
244 		warn("%s%s", to.base, to.path);
245 		rval = 1;
246 	}
247 
248 done:
249 	if (from_fd != -1)
250 		(void)close(from_fd);
251 	return (rval);
252 }
253 
254 int
255 copy_link(const FTSENT *p, bool dne, bool beneath)
256 {
257 	ssize_t len;
258 	int atflags = beneath ? AT_RESOLVE_BENEATH : 0;
259 	char llink[PATH_MAX];
260 
261 	if (!dne && nflag) {
262 		if (vflag)
263 			printf("%s%s not overwritten\n", to.base, to.path);
264 		return (1);
265 	}
266 	if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
267 		warn("readlink: %s", p->fts_path);
268 		return (1);
269 	}
270 	llink[len] = '\0';
271 	if (!dne && unlinkat(to.dir, to.path, atflags) != 0) {
272 		warn("unlink: %s%s", to.base, to.path);
273 		return (1);
274 	}
275 	if (symlinkat(llink, to.dir, to.path) != 0) {
276 		warn("symlink: %s", llink);
277 		return (1);
278 	}
279 	return (pflag ? setfile(p->fts_statp, -1, beneath) : 0);
280 }
281 
282 int
283 copy_fifo(struct stat *from_stat, bool dne, bool beneath)
284 {
285 	int atflags = beneath ? AT_RESOLVE_BENEATH : 0;
286 
287 	if (!dne && nflag) {
288 		if (vflag)
289 			printf("%s%s not overwritten\n", to.base, to.path);
290 		return (1);
291 	}
292 	if (!dne && unlinkat(to.dir, to.path, atflags) != 0) {
293 		warn("unlink: %s%s", to.base, to.path);
294 		return (1);
295 	}
296 	if (mkfifoat(to.dir, to.path, from_stat->st_mode) != 0) {
297 		warn("mkfifo: %s%s", to.base, to.path);
298 		return (1);
299 	}
300 	return (pflag ? setfile(from_stat, -1, beneath) : 0);
301 }
302 
303 int
304 copy_special(struct stat *from_stat, bool dne, bool beneath)
305 {
306 	int atflags = beneath ? AT_RESOLVE_BENEATH : 0;
307 
308 	if (!dne && nflag) {
309 		if (vflag)
310 			printf("%s%s not overwritten\n", to.base, to.path);
311 		return (1);
312 	}
313 	if (!dne && unlinkat(to.dir, to.path, atflags) != 0) {
314 		warn("unlink: %s%s", to.base, to.path);
315 		return (1);
316 	}
317 	if (mknodat(to.dir, to.path, from_stat->st_mode, from_stat->st_rdev) != 0) {
318 		warn("mknod: %s%s", to.base, to.path);
319 		return (1);
320 	}
321 	return (pflag ? setfile(from_stat, -1, beneath) : 0);
322 }
323 
324 int
325 setfile(struct stat *fs, int fd, bool beneath)
326 {
327 	static struct timespec tspec[2];
328 	struct stat ts;
329 	int atflags = beneath ? AT_RESOLVE_BENEATH : 0;
330 	int rval, gotstat, islink, fdval;
331 
332 	rval = 0;
333 	fdval = fd != -1;
334 	islink = !fdval && S_ISLNK(fs->st_mode);
335 	if (islink)
336 		atflags |= AT_SYMLINK_NOFOLLOW;
337 	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
338 	    S_IRWXU | S_IRWXG | S_IRWXO;
339 
340 	tspec[0] = fs->st_atim;
341 	tspec[1] = fs->st_mtim;
342 	if (fdval ? futimens(fd, tspec) :
343 	    utimensat(to.dir, to.path, tspec, atflags)) {
344 		warn("utimensat: %s%s", to.base, to.path);
345 		rval = 1;
346 	}
347 	if (fdval ? fstat(fd, &ts) :
348 	    fstatat(to.dir, to.path, &ts, atflags)) {
349 		gotstat = 0;
350 	} else {
351 		gotstat = 1;
352 		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
353 		    S_IRWXU | S_IRWXG | S_IRWXO;
354 	}
355 	/*
356 	 * Changing the ownership probably won't succeed, unless we're root
357 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
358 	 * the mode; current BSD behavior is to remove all setuid bits on
359 	 * chown.  If chown fails, lose setuid/setgid bits.
360 	 */
361 	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid) {
362 		if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
363 		    fchownat(to.dir, to.path, fs->st_uid, fs->st_gid, atflags)) {
364 			if (errno != EPERM) {
365 				warn("chown: %s%s", to.base, to.path);
366 				rval = 1;
367 			}
368 			fs->st_mode &= ~(S_ISUID | S_ISGID);
369 		}
370 	}
371 
372 	if (!gotstat || fs->st_mode != ts.st_mode) {
373 		if (fdval ? fchmod(fd, fs->st_mode) :
374 		    fchmodat(to.dir, to.path, fs->st_mode, atflags)) {
375 			warn("chmod: %s%s", to.base, to.path);
376 			rval = 1;
377 		}
378 	}
379 
380 	if (!Nflag && (!gotstat || fs->st_flags != ts.st_flags)) {
381 		if (fdval ? fchflags(fd, fs->st_flags) :
382 		    chflagsat(to.dir, to.path, fs->st_flags, atflags)) {
383 			/*
384 			 * NFS doesn't support chflags; ignore errors unless
385 			 * there's reason to believe we're losing bits.  (Note,
386 			 * this still won't be right if the server supports
387 			 * flags and we were trying to *remove* flags on a file
388 			 * that we copied, i.e., that we didn't create.)
389 			 */
390 			if (errno != EOPNOTSUPP || fs->st_flags != 0) {
391 				warn("chflags: %s%s", to.base, to.path);
392 				rval = 1;
393 			}
394 		}
395 	}
396 
397 	return (rval);
398 }
399 
400 int
401 preserve_fd_acls(int source_fd, int dest_fd)
402 {
403 	acl_t acl;
404 	acl_type_t acl_type;
405 	int acl_supported = 0, ret, trivial;
406 
407 	ret = fpathconf(source_fd, _PC_ACL_NFS4);
408 	if (ret > 0 ) {
409 		acl_supported = 1;
410 		acl_type = ACL_TYPE_NFS4;
411 	} else if (ret < 0 && errno != EINVAL) {
412 		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s%s",
413 		    to.base, to.path);
414 		return (-1);
415 	}
416 	if (acl_supported == 0) {
417 		ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
418 		if (ret > 0 ) {
419 			acl_supported = 1;
420 			acl_type = ACL_TYPE_ACCESS;
421 		} else if (ret < 0 && errno != EINVAL) {
422 			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s%s",
423 			    to.base, to.path);
424 			return (-1);
425 		}
426 	}
427 	if (acl_supported == 0)
428 		return (0);
429 
430 	acl = acl_get_fd_np(source_fd, acl_type);
431 	if (acl == NULL) {
432 		warn("failed to get acl entries while setting %s%s",
433 		    to.base, to.path);
434 		return (-1);
435 	}
436 	if (acl_is_trivial_np(acl, &trivial)) {
437 		warn("acl_is_trivial() failed for %s%s",
438 		    to.base, to.path);
439 		acl_free(acl);
440 		return (-1);
441 	}
442 	if (trivial) {
443 		acl_free(acl);
444 		return (0);
445 	}
446 	if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
447 		warn("failed to set acl entries for %s%s",
448 		    to.base, to.path);
449 		acl_free(acl);
450 		return (-1);
451 	}
452 	acl_free(acl);
453 	return (0);
454 }
455 
456 int
457 preserve_dir_acls(const char *source_dir, const char *dest_dir)
458 {
459 	int source_fd = -1, dest_fd = -1, ret;
460 
461 	if ((source_fd = open(source_dir, O_PATH)) < 0) {
462 		warn("%s: failed to copy ACLs", source_dir);
463 		return (-1);
464 	}
465 	dest_fd = (*dest_dir == '\0') ? to.dir :
466 	    openat(to.dir, dest_dir, O_DIRECTORY, AT_RESOLVE_BENEATH);
467 	if (dest_fd < 0) {
468 		warn("%s: failed to copy ACLs to %s%s", source_dir,
469 		    to.base, dest_dir);
470 		close(source_fd);
471 		return (-1);
472 	}
473 	if ((ret = preserve_fd_acls(source_fd, dest_fd)) != 0) {
474 		/* preserve_fd_acls() already printed a message */
475 	}
476 	if (dest_fd != to.dir)
477 		close(dest_fd);
478 	close(source_fd);
479 	return (ret);
480 }
481 
482 void
483 usage(void)
484 {
485 
486 	(void)fprintf(stderr, "%s\n%s\n",
487 	    "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpsvx] "
488 	    "source_file target_file",
489 	    "       cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpsvx] "
490 	    "source_file ... "
491 	    "target_directory");
492 	exit(EX_USAGE);
493 }
494