xref: /freebsd/bin/cp/utils.c (revision 4a5216a6dc0c3ce4cf5f2d3ee8af0c3ff3402c4f)
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 int
61 copy_file(const FTSENT *entp, int dne)
62 {
63 	static char buf[MAXBSIZE];
64 	struct stat *fs;
65 	ssize_t wcount;
66 	size_t wresid;
67 	off_t wtotal;
68 	int ch, checkch, from_fd = 0, rcount, rval, to_fd = 0;
69 	char *bufp;
70 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
71 	char *p;
72 #endif
73 
74 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
75 		warn("%s", entp->fts_path);
76 		return (1);
77 	}
78 
79 	fs = entp->fts_statp;
80 
81 	/*
82 	 * If the file exists and we're interactive, verify with the user.
83 	 * If the file DNE, set the mode to be the from file, minus setuid
84 	 * bits, modified by the umask; arguably wrong, but it makes copying
85 	 * executables work right and it's been that way forever.  (The
86 	 * other choice is 666 or'ed with the execute bits on the from file
87 	 * modified by the umask.)
88 	 */
89 	if (!dne) {
90 #define YESNO "(y/n [n]) "
91 		if (nflag) {
92 			if (vflag)
93 				printf("%s not overwritten\n", to.p_path);
94 			(void)close(from_fd);
95 			return (0);
96 		} else if (iflag) {
97 			(void)fprintf(stderr, "overwrite %s? %s",
98 					to.p_path, YESNO);
99 			checkch = ch = getchar();
100 			while (ch != '\n' && ch != EOF)
101 				ch = getchar();
102 			if (checkch != 'y' && checkch != 'Y') {
103 				(void)close(from_fd);
104 				(void)fprintf(stderr, "not overwritten\n");
105 				return (1);
106 			}
107 		}
108 
109 		if (fflag) {
110 		    /* remove existing destination file name,
111 		     * create a new file  */
112 		    (void)unlink(to.p_path);
113 				if (!lflag)
114 		    	to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
115 				  fs->st_mode & ~(S_ISUID | S_ISGID));
116 		} else {
117 				if (!lflag)
118 		    	/* overwrite existing destination file name */
119 		    	to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
120 		}
121 	} else {
122 		if (!lflag)
123 			to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
124 		  fs->st_mode & ~(S_ISUID | S_ISGID));
125 	}
126 
127 	if (to_fd == -1) {
128 		warn("%s", to.p_path);
129 		(void)close(from_fd);
130 		return (1);
131 	}
132 
133 	rval = 0;
134 
135 	if (!lflag) {
136 		/*
137 		 * Mmap and write if less than 8M (the limit is so we don't totally
138 		 * trash memory on big files.  This is really a minor hack, but it
139 		 * wins some CPU back.
140 		 */
141 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
142 		if (S_ISREG(fs->st_mode) && fs->st_size > 0 &&
143 	    	fs->st_size <= 8 * 1048576) {
144 			if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
145 		    	MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
146 				warn("%s", entp->fts_path);
147 				rval = 1;
148 			} else {
149 				wtotal = 0;
150 				for (bufp = p, wresid = fs->st_size; ;
151 			    	bufp += wcount, wresid -= (size_t)wcount) {
152 					wcount = write(to_fd, bufp, wresid);
153 					if (wcount <= 0)
154 						break;
155 					wtotal += wcount;
156 					if (info) {
157 						info = 0;
158 						(void)fprintf(stderr,
159 						    "%s -> %s %3d%%\n",
160 						    entp->fts_path, to.p_path,
161 						    cp_pct(wtotal, fs->st_size));
162 					}
163 					if (wcount >= (ssize_t)wresid)
164 						break;
165 				}
166 				if (wcount != (ssize_t)wresid) {
167 					warn("%s", to.p_path);
168 					rval = 1;
169 				}
170 				/* Some systems don't unmap on close(2). */
171 				if (munmap(p, fs->st_size) < 0) {
172 					warn("%s", entp->fts_path);
173 					rval = 1;
174 				}
175 			}
176 		} else
177 #endif
178 		{
179 			wtotal = 0;
180 			while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
181 				for (bufp = buf, wresid = rcount; ;
182 			    	bufp += wcount, wresid -= wcount) {
183 					wcount = write(to_fd, bufp, wresid);
184 					if (wcount <= 0)
185 						break;
186 					wtotal += wcount;
187 					if (info) {
188 						info = 0;
189 						(void)fprintf(stderr,
190 						    "%s -> %s %3d%%\n",
191 						    entp->fts_path, to.p_path,
192 						    cp_pct(wtotal, fs->st_size));
193 					}
194 					if (wcount >= (ssize_t)wresid)
195 						break;
196 				}
197 				if (wcount != (ssize_t)wresid) {
198 					warn("%s", to.p_path);
199 					rval = 1;
200 					break;
201 				}
202 			}
203 			if (rcount < 0) {
204 				warn("%s", entp->fts_path);
205 				rval = 1;
206 			}
207 		}
208 	} else {
209 		if (link(entp->fts_path, to.p_path)) {
210 			warn("%s", to.p_path);
211 			rval = 1;
212 		}
213 	}
214 
215 	/*
216 	 * Don't remove the target even after an error.  The target might
217 	 * not be a regular file, or its attributes might be important,
218 	 * or its contents might be irreplaceable.  It would only be safe
219 	 * to remove it if we created it and its length is 0.
220 	 */
221 
222 	if (!lflag) {
223 		if (pflag && setfile(fs, to_fd))
224 			rval = 1;
225 		if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
226 			rval = 1;
227 		if (close(to_fd)) {
228 			warn("%s", to.p_path);
229 			rval = 1;
230 		}
231 	}
232 
233 	(void)close(from_fd);
234 
235 	return (rval);
236 }
237 
238 int
239 copy_link(const FTSENT *p, int exists)
240 {
241 	int len;
242 	char llink[PATH_MAX];
243 
244 	if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
245 		warn("readlink: %s", p->fts_path);
246 		return (1);
247 	}
248 	llink[len] = '\0';
249 	if (exists && unlink(to.p_path)) {
250 		warn("unlink: %s", to.p_path);
251 		return (1);
252 	}
253 	if (symlink(llink, to.p_path)) {
254 		warn("symlink: %s", llink);
255 		return (1);
256 	}
257 	return (pflag ? setfile(p->fts_statp, -1) : 0);
258 }
259 
260 int
261 copy_fifo(struct stat *from_stat, int exists)
262 {
263 	if (exists && unlink(to.p_path)) {
264 		warn("unlink: %s", to.p_path);
265 		return (1);
266 	}
267 	if (mkfifo(to.p_path, from_stat->st_mode)) {
268 		warn("mkfifo: %s", to.p_path);
269 		return (1);
270 	}
271 	return (pflag ? setfile(from_stat, -1) : 0);
272 }
273 
274 int
275 copy_special(struct stat *from_stat, int exists)
276 {
277 	if (exists && unlink(to.p_path)) {
278 		warn("unlink: %s", to.p_path);
279 		return (1);
280 	}
281 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
282 		warn("mknod: %s", to.p_path);
283 		return (1);
284 	}
285 	return (pflag ? setfile(from_stat, -1) : 0);
286 }
287 
288 int
289 setfile(struct stat *fs, int fd)
290 {
291 	static struct timeval tv[2];
292 	struct stat ts;
293 	int rval, gotstat, islink, fdval;
294 
295 	rval = 0;
296 	fdval = fd != -1;
297 	islink = !fdval && S_ISLNK(fs->st_mode);
298 	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
299 		       S_IRWXU | S_IRWXG | S_IRWXO;
300 
301 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
302 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
303 	if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
304 		warn("%sutimes: %s", islink ? "l" : "", to.p_path);
305 		rval = 1;
306 	}
307 	if (fdval ? fstat(fd, &ts) :
308 	    (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
309 		gotstat = 0;
310 	else {
311 		gotstat = 1;
312 		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
313 			      S_IRWXU | S_IRWXG | S_IRWXO;
314 	}
315 	/*
316 	 * Changing the ownership probably won't succeed, unless we're root
317 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
318 	 * the mode; current BSD behavior is to remove all setuid bits on
319 	 * chown.  If chown fails, lose setuid/setgid bits.
320 	 */
321 	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
322 		if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
323 		    (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
324 		    chown(to.p_path, fs->st_uid, fs->st_gid))) {
325 			if (errno != EPERM) {
326 				warn("chown: %s", to.p_path);
327 				rval = 1;
328 			}
329 			fs->st_mode &= ~(S_ISUID | S_ISGID);
330 		}
331 
332 	if (!gotstat || fs->st_mode != ts.st_mode)
333 		if (fdval ? fchmod(fd, fs->st_mode) :
334 		    (islink ? lchmod(to.p_path, fs->st_mode) :
335 		    chmod(to.p_path, fs->st_mode))) {
336 			warn("chmod: %s", to.p_path);
337 			rval = 1;
338 		}
339 
340 	if (!gotstat || fs->st_flags != ts.st_flags)
341 		if (fdval ?
342 		    fchflags(fd, fs->st_flags) :
343 		    (islink ? (errno = ENOSYS) :
344 		    chflags(to.p_path, fs->st_flags))) {
345 			warn("chflags: %s", to.p_path);
346 			rval = 1;
347 		}
348 
349 	return (rval);
350 }
351 
352 int
353 preserve_fd_acls(int source_fd, int dest_fd)
354 {
355 	struct acl *aclp;
356 	acl_t acl;
357 
358 	if (fpathconf(source_fd, _PC_ACL_EXTENDED) != 1 ||
359 	    fpathconf(dest_fd, _PC_ACL_EXTENDED) != 1)
360 		return (0);
361 	acl = acl_get_fd(source_fd);
362 	if (acl == NULL) {
363 		warn("failed to get acl entries while setting %s", to.p_path);
364 		return (1);
365 	}
366 	aclp = &acl->ats_acl;
367 	if (aclp->acl_cnt == 3)
368 		return (0);
369 	if (acl_set_fd(dest_fd, acl) < 0) {
370 		warn("failed to set acl entries for %s", to.p_path);
371 		return (1);
372 	}
373 	return (0);
374 }
375 
376 int
377 preserve_dir_acls(struct stat *fs, char *source_dir, char *dest_dir)
378 {
379 	acl_t (*aclgetf)(const char *, acl_type_t);
380 	int (*aclsetf)(const char *, acl_type_t, acl_t);
381 	struct acl *aclp;
382 	acl_t acl;
383 
384 	if (pathconf(source_dir, _PC_ACL_EXTENDED) != 1 ||
385 	    pathconf(dest_dir, _PC_ACL_EXTENDED) != 1)
386 		return (0);
387 	/*
388 	 * If the file is a link we will not follow it
389 	 */
390 	if (S_ISLNK(fs->st_mode)) {
391 		aclgetf = acl_get_link_np;
392 		aclsetf = acl_set_link_np;
393 	} else {
394 		aclgetf = acl_get_file;
395 		aclsetf = acl_set_file;
396 	}
397 	/*
398 	 * Even if there is no ACL_TYPE_DEFAULT entry here, a zero
399 	 * size ACL will be returned. So it is not safe to simply
400 	 * check the pointer to see if the default ACL is present.
401 	 */
402 	acl = aclgetf(source_dir, ACL_TYPE_DEFAULT);
403 	if (acl == NULL) {
404 		warn("failed to get default acl entries on %s",
405 		    source_dir);
406 		return (1);
407 	}
408 	aclp = &acl->ats_acl;
409 	if (aclp->acl_cnt != 0 && aclsetf(dest_dir,
410 	    ACL_TYPE_DEFAULT, acl) < 0) {
411 		warn("failed to set default acl entries on %s",
412 		    dest_dir);
413 		return (1);
414 	}
415 	acl = aclgetf(source_dir, ACL_TYPE_ACCESS);
416 	if (acl == NULL) {
417 		warn("failed to get acl entries on %s", source_dir);
418 		return (1);
419 	}
420 	aclp = &acl->ats_acl;
421 	if (aclsetf(dest_dir, ACL_TYPE_ACCESS, acl) < 0) {
422 		warn("failed to set acl entries on %s", dest_dir);
423 		return (1);
424 	}
425 	return (0);
426 }
427 
428 void
429 usage(void)
430 {
431 
432 	(void)fprintf(stderr, "%s\n%s\n",
433 "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpv] source_file target_file",
434 "       cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpv] source_file ... "
435 "target_directory");
436 	exit(EX_USAGE);
437 }
438