xref: /freebsd/bin/cp/utils.c (revision f95c930e6701aa675377bc5871ea490dd565eeba)
1 /*-
2  * Copyright (c) 1991, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #ifndef lint
31 #if 0
32 static char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
33 #endif
34 #endif /* not lint */
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include <sys/types.h>
39 #include <sys/acl.h>
40 #include <sys/param.h>
41 #include <sys/stat.h>
42 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
43 #include <sys/mman.h>
44 #endif
45 
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <fts.h>
50 #include <limits.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <sysexits.h>
54 #include <unistd.h>
55 
56 #include "extern.h"
57 
58 #define	cp_pct(x, y)	((y == 0) ? 0 : (int)(100.0 * (x) / (y)))
59 
60 /* Memory strategy threshold, in pages: if physmem is larger then this, use a
61  * large buffer */
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 /* Small (default) buffer size in bytes. It's inefficient for this to be
68  * smaller than MAXPHYS */
69 #define BUFSIZE_SMALL (MAXPHYS)
70 
71 int
72 copy_file(const FTSENT *entp, int dne)
73 {
74 	static char *buf = NULL;
75 	static size_t bufsize;
76 	struct stat *fs;
77 	ssize_t wcount;
78 	size_t wresid;
79 	off_t wtotal;
80 	int ch, checkch, from_fd = 0, rcount, rval, to_fd = 0;
81 	char *bufp;
82 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
83 	char *p;
84 #endif
85 
86 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
87 		warn("%s", entp->fts_path);
88 		return (1);
89 	}
90 
91 	fs = entp->fts_statp;
92 
93 	/*
94 	 * If the file exists and we're interactive, verify with the user.
95 	 * If the file DNE, set the mode to be the from file, minus setuid
96 	 * bits, modified by the umask; arguably wrong, but it makes copying
97 	 * executables work right and it's been that way forever.  (The
98 	 * other choice is 666 or'ed with the execute bits on the from file
99 	 * modified by the umask.)
100 	 */
101 	if (!dne) {
102 #define YESNO "(y/n [n]) "
103 		if (nflag) {
104 			if (vflag)
105 				printf("%s not overwritten\n", to.p_path);
106 			(void)close(from_fd);
107 			return (1);
108 		} else if (iflag) {
109 			(void)fprintf(stderr, "overwrite %s? %s",
110 					to.p_path, YESNO);
111 			checkch = ch = getchar();
112 			while (ch != '\n' && ch != EOF)
113 				ch = getchar();
114 			if (checkch != 'y' && checkch != 'Y') {
115 				(void)close(from_fd);
116 				(void)fprintf(stderr, "not overwritten\n");
117 				return (1);
118 			}
119 		}
120 
121 		if (fflag) {
122 		    /* remove existing destination file name,
123 		     * create a new file  */
124 		    (void)unlink(to.p_path);
125 				if (!lflag)
126 		    	to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
127 				  fs->st_mode & ~(S_ISUID | S_ISGID));
128 		} else {
129 				if (!lflag)
130 		    	/* overwrite existing destination file name */
131 		    	to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
132 		}
133 	} else {
134 		if (!lflag)
135 			to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
136 		  fs->st_mode & ~(S_ISUID | S_ISGID));
137 	}
138 
139 	if (to_fd == -1) {
140 		warn("%s", to.p_path);
141 		(void)close(from_fd);
142 		return (1);
143 	}
144 
145 	rval = 0;
146 
147 	if (!lflag) {
148 		/*
149 		 * Mmap and write if less than 8M (the limit is so we don't totally
150 		 * trash memory on big files.  This is really a minor hack, but it
151 		 * wins some CPU back.
152 		 * Some filesystems, such as smbnetfs, don't support mmap,
153 		 * so this is a best-effort attempt.
154 		 */
155 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
156 		if (S_ISREG(fs->st_mode) && fs->st_size > 0 &&
157 	    	    fs->st_size <= 8 * 1024 * 1024 &&
158 		    (p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
159 		    MAP_SHARED, from_fd, (off_t)0)) != MAP_FAILED) {
160 			wtotal = 0;
161 			for (bufp = p, wresid = fs->st_size; ;
162 			bufp += wcount, wresid -= (size_t)wcount) {
163 				wcount = write(to_fd, bufp, wresid);
164 				if (wcount <= 0)
165 					break;
166 				wtotal += wcount;
167 				if (info) {
168 					info = 0;
169 					(void)fprintf(stderr,
170 					    "%s -> %s %3d%%\n",
171 					    entp->fts_path, to.p_path,
172 					    cp_pct(wtotal, fs->st_size));
173 				}
174 				if (wcount >= (ssize_t)wresid)
175 					break;
176 			}
177 			if (wcount != (ssize_t)wresid) {
178 				warn("%s", to.p_path);
179 				rval = 1;
180 			}
181 			/* Some systems don't unmap on close(2). */
182 			if (munmap(p, fs->st_size) < 0) {
183 				warn("%s", entp->fts_path);
184 				rval = 1;
185 			}
186 		} else
187 #endif
188 		{
189 			if (buf == NULL) {
190 				/*
191 				 * Note that buf and bufsize are static. If
192 				 * malloc() fails, it will fail at the start
193 				 * and not copy only some files.
194 				 */
195 				if (sysconf(_SC_PHYS_PAGES) >
196 				    PHYSPAGES_THRESHOLD)
197 					bufsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
198 				else
199 					bufsize = BUFSIZE_SMALL;
200 				buf = malloc(bufsize);
201 				if (buf == NULL)
202 					err(1, "Not enough memory");
203 			}
204 			wtotal = 0;
205 			while ((rcount = read(from_fd, buf, bufsize)) > 0) {
206 				for (bufp = buf, wresid = rcount; ;
207 			    	bufp += wcount, wresid -= wcount) {
208 					wcount = write(to_fd, bufp, wresid);
209 					if (wcount <= 0)
210 						break;
211 					wtotal += wcount;
212 					if (info) {
213 						info = 0;
214 						(void)fprintf(stderr,
215 						    "%s -> %s %3d%%\n",
216 						    entp->fts_path, to.p_path,
217 						    cp_pct(wtotal, fs->st_size));
218 					}
219 					if (wcount >= (ssize_t)wresid)
220 						break;
221 				}
222 				if (wcount != (ssize_t)wresid) {
223 					warn("%s", to.p_path);
224 					rval = 1;
225 					break;
226 				}
227 			}
228 			if (rcount < 0) {
229 				warn("%s", entp->fts_path);
230 				rval = 1;
231 			}
232 		}
233 	} else {
234 		if (link(entp->fts_path, to.p_path)) {
235 			warn("%s", to.p_path);
236 			rval = 1;
237 		}
238 	}
239 
240 	/*
241 	 * Don't remove the target even after an error.  The target might
242 	 * not be a regular file, or its attributes might be important,
243 	 * or its contents might be irreplaceable.  It would only be safe
244 	 * to remove it if we created it and its length is 0.
245 	 */
246 
247 	if (!lflag) {
248 		if (pflag && setfile(fs, to_fd))
249 			rval = 1;
250 		if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
251 			rval = 1;
252 		if (close(to_fd)) {
253 			warn("%s", to.p_path);
254 			rval = 1;
255 		}
256 	}
257 
258 	(void)close(from_fd);
259 
260 	return (rval);
261 }
262 
263 int
264 copy_link(const FTSENT *p, int exists)
265 {
266 	int len;
267 	char llink[PATH_MAX];
268 
269 	if (exists && nflag) {
270 		if (vflag)
271 			printf("%s not overwritten\n", to.p_path);
272 		return (1);
273 	}
274 	if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
275 		warn("readlink: %s", p->fts_path);
276 		return (1);
277 	}
278 	llink[len] = '\0';
279 	if (exists && unlink(to.p_path)) {
280 		warn("unlink: %s", to.p_path);
281 		return (1);
282 	}
283 	if (symlink(llink, to.p_path)) {
284 		warn("symlink: %s", llink);
285 		return (1);
286 	}
287 	return (pflag ? setfile(p->fts_statp, -1) : 0);
288 }
289 
290 int
291 copy_fifo(struct stat *from_stat, int exists)
292 {
293 
294 	if (exists && nflag) {
295 		if (vflag)
296 			printf("%s not overwritten\n", to.p_path);
297 		return (1);
298 	}
299 	if (exists && unlink(to.p_path)) {
300 		warn("unlink: %s", to.p_path);
301 		return (1);
302 	}
303 	if (mkfifo(to.p_path, from_stat->st_mode)) {
304 		warn("mkfifo: %s", to.p_path);
305 		return (1);
306 	}
307 	return (pflag ? setfile(from_stat, -1) : 0);
308 }
309 
310 int
311 copy_special(struct stat *from_stat, int exists)
312 {
313 
314 	if (exists && nflag) {
315 		if (vflag)
316 			printf("%s not overwritten\n", to.p_path);
317 		return (1);
318 	}
319 	if (exists && unlink(to.p_path)) {
320 		warn("unlink: %s", to.p_path);
321 		return (1);
322 	}
323 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
324 		warn("mknod: %s", to.p_path);
325 		return (1);
326 	}
327 	return (pflag ? setfile(from_stat, -1) : 0);
328 }
329 
330 int
331 setfile(struct stat *fs, int fd)
332 {
333 	static struct timespec tspec[2];
334 	struct stat ts;
335 	int rval, gotstat, islink, fdval;
336 
337 	rval = 0;
338 	fdval = fd != -1;
339 	islink = !fdval && S_ISLNK(fs->st_mode);
340 	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
341 		       S_IRWXU | S_IRWXG | S_IRWXO;
342 
343 	tspec[0] = fs->st_atim;
344 	tspec[1] = fs->st_mtim;
345 	if (fdval ? futimens(fd, tspec) : utimensat(AT_FDCWD, to.p_path, tspec,
346 	    islink ? AT_SYMLINK_NOFOLLOW : 0)) {
347 		warn("utimensat: %s", to.p_path);
348 		rval = 1;
349 	}
350 	if (fdval ? fstat(fd, &ts) :
351 	    (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
352 		gotstat = 0;
353 	else {
354 		gotstat = 1;
355 		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
356 			      S_IRWXU | S_IRWXG | S_IRWXO;
357 	}
358 	/*
359 	 * Changing the ownership probably won't succeed, unless we're root
360 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
361 	 * the mode; current BSD behavior is to remove all setuid bits on
362 	 * chown.  If chown fails, lose setuid/setgid bits.
363 	 */
364 	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
365 		if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
366 		    (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
367 		    chown(to.p_path, fs->st_uid, fs->st_gid))) {
368 			if (errno != EPERM) {
369 				warn("chown: %s", to.p_path);
370 				rval = 1;
371 			}
372 			fs->st_mode &= ~(S_ISUID | S_ISGID);
373 		}
374 
375 	if (!gotstat || fs->st_mode != ts.st_mode)
376 		if (fdval ? fchmod(fd, fs->st_mode) :
377 		    (islink ? lchmod(to.p_path, fs->st_mode) :
378 		    chmod(to.p_path, fs->st_mode))) {
379 			warn("chmod: %s", to.p_path);
380 			rval = 1;
381 		}
382 
383 	if (!gotstat || fs->st_flags != ts.st_flags)
384 		if (fdval ?
385 		    fchflags(fd, fs->st_flags) :
386 		    (islink ? lchflags(to.p_path, fs->st_flags) :
387 		    chflags(to.p_path, fs->st_flags))) {
388 			warn("chflags: %s", to.p_path);
389 			rval = 1;
390 		}
391 
392 	return (rval);
393 }
394 
395 int
396 preserve_fd_acls(int source_fd, int dest_fd)
397 {
398 	acl_t acl;
399 	acl_type_t acl_type;
400 	int acl_supported = 0, ret, trivial;
401 
402 	ret = fpathconf(source_fd, _PC_ACL_NFS4);
403 	if (ret > 0 ) {
404 		acl_supported = 1;
405 		acl_type = ACL_TYPE_NFS4;
406 	} else if (ret < 0 && errno != EINVAL) {
407 		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", to.p_path);
408 		return (1);
409 	}
410 	if (acl_supported == 0) {
411 		ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
412 		if (ret > 0 ) {
413 			acl_supported = 1;
414 			acl_type = ACL_TYPE_ACCESS;
415 		} else if (ret < 0 && errno != EINVAL) {
416 			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
417 			    to.p_path);
418 			return (1);
419 		}
420 	}
421 	if (acl_supported == 0)
422 		return (0);
423 
424 	acl = acl_get_fd_np(source_fd, acl_type);
425 	if (acl == NULL) {
426 		warn("failed to get acl entries while setting %s", to.p_path);
427 		return (1);
428 	}
429 	if (acl_is_trivial_np(acl, &trivial)) {
430 		warn("acl_is_trivial() failed for %s", to.p_path);
431 		acl_free(acl);
432 		return (1);
433 	}
434 	if (trivial) {
435 		acl_free(acl);
436 		return (0);
437 	}
438 	if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
439 		warn("failed to set acl entries for %s", to.p_path);
440 		acl_free(acl);
441 		return (1);
442 	}
443 	acl_free(acl);
444 	return (0);
445 }
446 
447 int
448 preserve_dir_acls(struct stat *fs, char *source_dir, char *dest_dir)
449 {
450 	acl_t (*aclgetf)(const char *, acl_type_t);
451 	int (*aclsetf)(const char *, acl_type_t, acl_t);
452 	struct acl *aclp;
453 	acl_t acl;
454 	acl_type_t acl_type;
455 	int acl_supported = 0, ret, trivial;
456 
457 	ret = pathconf(source_dir, _PC_ACL_NFS4);
458 	if (ret > 0) {
459 		acl_supported = 1;
460 		acl_type = ACL_TYPE_NFS4;
461 	} else if (ret < 0 && errno != EINVAL) {
462 		warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", source_dir);
463 		return (1);
464 	}
465 	if (acl_supported == 0) {
466 		ret = pathconf(source_dir, _PC_ACL_EXTENDED);
467 		if (ret > 0) {
468 			acl_supported = 1;
469 			acl_type = ACL_TYPE_ACCESS;
470 		} else if (ret < 0 && errno != EINVAL) {
471 			warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
472 			    source_dir);
473 			return (1);
474 		}
475 	}
476 	if (acl_supported == 0)
477 		return (0);
478 
479 	/*
480 	 * If the file is a link we will not follow it
481 	 */
482 	if (S_ISLNK(fs->st_mode)) {
483 		aclgetf = acl_get_link_np;
484 		aclsetf = acl_set_link_np;
485 	} else {
486 		aclgetf = acl_get_file;
487 		aclsetf = acl_set_file;
488 	}
489 	if (acl_type == ACL_TYPE_ACCESS) {
490 		/*
491 		 * Even if there is no ACL_TYPE_DEFAULT entry here, a zero
492 		 * size ACL will be returned. So it is not safe to simply
493 		 * check the pointer to see if the default ACL is present.
494 		 */
495 		acl = aclgetf(source_dir, ACL_TYPE_DEFAULT);
496 		if (acl == NULL) {
497 			warn("failed to get default acl entries on %s",
498 			    source_dir);
499 			return (1);
500 		}
501 		aclp = &acl->ats_acl;
502 		if (aclp->acl_cnt != 0 && aclsetf(dest_dir,
503 		    ACL_TYPE_DEFAULT, acl) < 0) {
504 			warn("failed to set default acl entries on %s",
505 			    dest_dir);
506 			acl_free(acl);
507 			return (1);
508 		}
509 		acl_free(acl);
510 	}
511 	acl = aclgetf(source_dir, acl_type);
512 	if (acl == NULL) {
513 		warn("failed to get acl entries on %s", source_dir);
514 		return (1);
515 	}
516 	if (acl_is_trivial_np(acl, &trivial)) {
517 		warn("acl_is_trivial() failed on %s", source_dir);
518 		acl_free(acl);
519 		return (1);
520 	}
521 	if (trivial) {
522 		acl_free(acl);
523 		return (0);
524 	}
525 	if (aclsetf(dest_dir, acl_type, acl) < 0) {
526 		warn("failed to set acl entries on %s", dest_dir);
527 		acl_free(acl);
528 		return (1);
529 	}
530 	acl_free(acl);
531 	return (0);
532 }
533 
534 void
535 usage(void)
536 {
537 
538 	(void)fprintf(stderr, "%s\n%s\n",
539 "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpvx] source_file target_file",
540 "       cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpvx] source_file ... "
541 "target_directory");
542 	exit(EX_USAGE);
543 }
544