xref: /freebsd/bin/cp/utils.c (revision 62a52c15422470f97fc7b311d89c83f910bcc1b1)
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 /*
66  * Prompt used in -i case.
67  */
68 #define YESNO "(y/n [n]) "
69 
70 static ssize_t
71 copy_fallback(int from_fd, int to_fd)
72 {
73 	static char *buf = NULL;
74 	static size_t bufsize;
75 	ssize_t rcount, wresid, wcount = 0;
76 	char *bufp;
77 
78 	if (buf == NULL) {
79 		if (sysconf(_SC_PHYS_PAGES) > PHYSPAGES_THRESHOLD)
80 			bufsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
81 		else
82 			bufsize = BUFSIZE_SMALL;
83 		buf = malloc(bufsize);
84 		if (buf == NULL)
85 			err(1, "Not enough memory");
86 	}
87 	rcount = read(from_fd, buf, bufsize);
88 	if (rcount <= 0)
89 		return (rcount);
90 	for (bufp = buf, wresid = rcount; ; bufp += wcount, wresid -= wcount) {
91 		wcount = write(to_fd, bufp, wresid);
92 		if (wcount <= 0)
93 			break;
94 		if (wcount >= (ssize_t)wresid)
95 			break;
96 	}
97 	return (wcount < 0 ? wcount : rcount);
98 }
99 
100 int
101 copy_file(const FTSENT *entp, int dne)
102 {
103 	struct stat *fs;
104 	ssize_t wcount;
105 	off_t wtotal;
106 	int ch, checkch, from_fd, rval, to_fd;
107 	int use_copy_file_range = 1;
108 
109 	from_fd = to_fd = -1;
110 	if (!lflag && !sflag &&
111 	    (from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
112 		warn("%s", entp->fts_path);
113 		return (1);
114 	}
115 
116 	fs = entp->fts_statp;
117 
118 	/*
119 	 * If the file exists and we're interactive, verify with the user.
120 	 * If the file DNE, set the mode to be the from file, minus setuid
121 	 * bits, modified by the umask; arguably wrong, but it makes copying
122 	 * executables work right and it's been that way forever.  (The
123 	 * other choice is 666 or'ed with the execute bits on the from file
124 	 * modified by the umask.)
125 	 */
126 	if (!dne) {
127 		if (nflag) {
128 			if (vflag)
129 				printf("%s not overwritten\n", to.p_path);
130 			rval = 1;
131 			goto done;
132 		} else if (iflag) {
133 			(void)fprintf(stderr, "overwrite %s? %s",
134 			    to.p_path, YESNO);
135 			checkch = ch = getchar();
136 			while (ch != '\n' && ch != EOF)
137 				ch = getchar();
138 			if (checkch != 'y' && checkch != 'Y') {
139 				(void)fprintf(stderr, "not overwritten\n");
140 				rval = 1;
141 				goto done;
142 			}
143 		}
144 
145 		if (fflag) {
146 			/* remove existing destination file */
147 			(void)unlink(to.p_path);
148 			dne = 1;
149 		}
150 	}
151 
152 	rval = 0;
153 
154 	if (lflag) {
155 		if (link(entp->fts_path, to.p_path) != 0) {
156 			warn("%s", to.p_path);
157 			rval = 1;
158 		}
159 		goto done;
160 	}
161 
162 	if (sflag) {
163 		if (symlink(entp->fts_path, to.p_path) != 0) {
164 			warn("%s", to.p_path);
165 			rval = 1;
166 		}
167 		goto done;
168 	}
169 
170 	if (!dne) {
171 		/* overwrite existing destination file */
172 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
173 	} else {
174 		/* create new destination file */
175 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
176 		    fs->st_mode & ~(S_ISUID | S_ISGID));
177 	}
178 	if (to_fd == -1) {
179 		warn("%s", to.p_path);
180 		rval = 1;
181 		goto done;
182 	}
183 
184 	wtotal = 0;
185 	do {
186 		if (use_copy_file_range) {
187 			wcount = copy_file_range(from_fd, NULL,
188 			    to_fd, NULL, SSIZE_MAX, 0);
189 			if (wcount < 0 && errno == EINVAL) {
190 				/* probably a non-seekable descriptor */
191 				use_copy_file_range = 0;
192 			}
193 		}
194 		if (!use_copy_file_range) {
195 			wcount = copy_fallback(from_fd, to_fd);
196 		}
197 		wtotal += wcount;
198 		if (info) {
199 			info = 0;
200 			(void)fprintf(stderr,
201 			    "%s -> %s %3d%%\n",
202 			    entp->fts_path, to.p_path,
203 			    cp_pct(wtotal, fs->st_size));
204 		}
205 	} while (wcount > 0);
206 	if (wcount < 0) {
207 		warn("%s", entp->fts_path);
208 		rval = 1;
209 	}
210 
211 	/*
212 	 * Don't remove the target even after an error.  The target might
213 	 * not be a regular file, or its attributes might be important,
214 	 * or its contents might be irreplaceable.  It would only be safe
215 	 * to remove it if we created it and its length is 0.
216 	 */
217 	if (pflag && setfile(fs, to_fd))
218 		rval = 1;
219 	if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
220 		rval = 1;
221 	if (close(to_fd)) {
222 		warn("%s", to.p_path);
223 		rval = 1;
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 (!Nflag && (!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 			/*
358 			 * NFS doesn't support chflags; ignore errors unless
359 			 * there's reason to believe we're losing bits.  (Note,
360 			 * this still won't be right if the server supports
361 			 * flags and we were trying to *remove* flags on a file
362 			 * that we copied, i.e., that we didn't create.)
363 			 */
364 			if (errno != EOPNOTSUPP || fs->st_flags != 0) {
365 				warn("chflags: %s", to.p_path);
366 				rval = 1;
367 			}
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