xref: /freebsd/bin/cp/utils.c (revision 6c6c03be2ddb04c54e455122799923deaefa4114)
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 		 * Some filesystems, such as smbnetfs, don't support mmap,
141 		 * so this is a best-effort attempt.
142 		 */
143 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
144 		if (S_ISREG(fs->st_mode) && fs->st_size > 0 &&
145 	    	    fs->st_size <= 8 * 1024 * 1024 &&
146 		    (p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
147 		    MAP_SHARED, from_fd, (off_t)0)) != MAP_FAILED) {
148 			wtotal = 0;
149 			for (bufp = p, wresid = fs->st_size; ;
150 			bufp += wcount, wresid -= (size_t)wcount) {
151 				wcount = write(to_fd, bufp, wresid);
152 				if (wcount <= 0)
153 					break;
154 				wtotal += wcount;
155 				if (info) {
156 					info = 0;
157 					(void)fprintf(stderr,
158 					    "%s -> %s %3d%%\n",
159 					    entp->fts_path, to.p_path,
160 					    cp_pct(wtotal, fs->st_size));
161 				}
162 				if (wcount >= (ssize_t)wresid)
163 					break;
164 			}
165 			if (wcount != (ssize_t)wresid) {
166 				warn("%s", to.p_path);
167 				rval = 1;
168 			}
169 			/* Some systems don't unmap on close(2). */
170 			if (munmap(p, fs->st_size) < 0) {
171 				warn("%s", entp->fts_path);
172 				rval = 1;
173 			}
174 		} else
175 #endif
176 		{
177 			wtotal = 0;
178 			while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
179 				for (bufp = buf, wresid = rcount; ;
180 			    	bufp += wcount, wresid -= wcount) {
181 					wcount = write(to_fd, bufp, wresid);
182 					if (wcount <= 0)
183 						break;
184 					wtotal += wcount;
185 					if (info) {
186 						info = 0;
187 						(void)fprintf(stderr,
188 						    "%s -> %s %3d%%\n",
189 						    entp->fts_path, to.p_path,
190 						    cp_pct(wtotal, fs->st_size));
191 					}
192 					if (wcount >= (ssize_t)wresid)
193 						break;
194 				}
195 				if (wcount != (ssize_t)wresid) {
196 					warn("%s", to.p_path);
197 					rval = 1;
198 					break;
199 				}
200 			}
201 			if (rcount < 0) {
202 				warn("%s", entp->fts_path);
203 				rval = 1;
204 			}
205 		}
206 	} else {
207 		if (link(entp->fts_path, to.p_path)) {
208 			warn("%s", to.p_path);
209 			rval = 1;
210 		}
211 	}
212 
213 	/*
214 	 * Don't remove the target even after an error.  The target might
215 	 * not be a regular file, or its attributes might be important,
216 	 * or its contents might be irreplaceable.  It would only be safe
217 	 * to remove it if we created it and its length is 0.
218 	 */
219 
220 	if (!lflag) {
221 		if (pflag && setfile(fs, to_fd))
222 			rval = 1;
223 		if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
224 			rval = 1;
225 		if (close(to_fd)) {
226 			warn("%s", to.p_path);
227 			rval = 1;
228 		}
229 	}
230 
231 	(void)close(from_fd);
232 
233 	return (rval);
234 }
235 
236 int
237 copy_link(const FTSENT *p, int exists)
238 {
239 	int len;
240 	char llink[PATH_MAX];
241 
242 	if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
243 		warn("readlink: %s", p->fts_path);
244 		return (1);
245 	}
246 	llink[len] = '\0';
247 	if (exists && unlink(to.p_path)) {
248 		warn("unlink: %s", to.p_path);
249 		return (1);
250 	}
251 	if (symlink(llink, to.p_path)) {
252 		warn("symlink: %s", llink);
253 		return (1);
254 	}
255 	return (pflag ? setfile(p->fts_statp, -1) : 0);
256 }
257 
258 int
259 copy_fifo(struct stat *from_stat, int exists)
260 {
261 	if (exists && unlink(to.p_path)) {
262 		warn("unlink: %s", to.p_path);
263 		return (1);
264 	}
265 	if (mkfifo(to.p_path, from_stat->st_mode)) {
266 		warn("mkfifo: %s", to.p_path);
267 		return (1);
268 	}
269 	return (pflag ? setfile(from_stat, -1) : 0);
270 }
271 
272 int
273 copy_special(struct stat *from_stat, int exists)
274 {
275 	if (exists && unlink(to.p_path)) {
276 		warn("unlink: %s", to.p_path);
277 		return (1);
278 	}
279 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
280 		warn("mknod: %s", to.p_path);
281 		return (1);
282 	}
283 	return (pflag ? setfile(from_stat, -1) : 0);
284 }
285 
286 int
287 setfile(struct stat *fs, int fd)
288 {
289 	static struct timeval tv[2];
290 	struct stat ts;
291 	int rval, gotstat, islink, fdval;
292 
293 	rval = 0;
294 	fdval = fd != -1;
295 	islink = !fdval && S_ISLNK(fs->st_mode);
296 	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
297 		       S_IRWXU | S_IRWXG | S_IRWXO;
298 
299 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
300 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
301 	if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
302 		warn("%sutimes: %s", islink ? "l" : "", to.p_path);
303 		rval = 1;
304 	}
305 	if (fdval ? fstat(fd, &ts) :
306 	    (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
307 		gotstat = 0;
308 	else {
309 		gotstat = 1;
310 		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
311 			      S_IRWXU | S_IRWXG | S_IRWXO;
312 	}
313 	/*
314 	 * Changing the ownership probably won't succeed, unless we're root
315 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
316 	 * the mode; current BSD behavior is to remove all setuid bits on
317 	 * chown.  If chown fails, lose setuid/setgid bits.
318 	 */
319 	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
320 		if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
321 		    (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
322 		    chown(to.p_path, fs->st_uid, fs->st_gid))) {
323 			if (errno != EPERM) {
324 				warn("chown: %s", to.p_path);
325 				rval = 1;
326 			}
327 			fs->st_mode &= ~(S_ISUID | S_ISGID);
328 		}
329 
330 	if (!gotstat || fs->st_mode != ts.st_mode)
331 		if (fdval ? fchmod(fd, fs->st_mode) :
332 		    (islink ? lchmod(to.p_path, fs->st_mode) :
333 		    chmod(to.p_path, fs->st_mode))) {
334 			warn("chmod: %s", to.p_path);
335 			rval = 1;
336 		}
337 
338 	if (!gotstat || fs->st_flags != ts.st_flags)
339 		if (fdval ?
340 		    fchflags(fd, fs->st_flags) :
341 		    (islink ? (errno = ENOSYS) :
342 		    chflags(to.p_path, fs->st_flags))) {
343 			warn("chflags: %s", to.p_path);
344 			rval = 1;
345 		}
346 
347 	return (rval);
348 }
349 
350 int
351 preserve_fd_acls(int source_fd, int dest_fd)
352 {
353 	struct acl *aclp;
354 	acl_t acl;
355 
356 	if (fpathconf(source_fd, _PC_ACL_EXTENDED) != 1 ||
357 	    fpathconf(dest_fd, _PC_ACL_EXTENDED) != 1)
358 		return (0);
359 	acl = acl_get_fd(source_fd);
360 	if (acl == NULL) {
361 		warn("failed to get acl entries while setting %s", to.p_path);
362 		return (1);
363 	}
364 	aclp = &acl->ats_acl;
365 	if (aclp->acl_cnt == 3)
366 		return (0);
367 	if (acl_set_fd(dest_fd, acl) < 0) {
368 		warn("failed to set acl entries for %s", to.p_path);
369 		return (1);
370 	}
371 	return (0);
372 }
373 
374 int
375 preserve_dir_acls(struct stat *fs, char *source_dir, char *dest_dir)
376 {
377 	acl_t (*aclgetf)(const char *, acl_type_t);
378 	int (*aclsetf)(const char *, acl_type_t, acl_t);
379 	struct acl *aclp;
380 	acl_t acl;
381 
382 	if (pathconf(source_dir, _PC_ACL_EXTENDED) != 1 ||
383 	    pathconf(dest_dir, _PC_ACL_EXTENDED) != 1)
384 		return (0);
385 	/*
386 	 * If the file is a link we will not follow it
387 	 */
388 	if (S_ISLNK(fs->st_mode)) {
389 		aclgetf = acl_get_link_np;
390 		aclsetf = acl_set_link_np;
391 	} else {
392 		aclgetf = acl_get_file;
393 		aclsetf = acl_set_file;
394 	}
395 	/*
396 	 * Even if there is no ACL_TYPE_DEFAULT entry here, a zero
397 	 * size ACL will be returned. So it is not safe to simply
398 	 * check the pointer to see if the default ACL is present.
399 	 */
400 	acl = aclgetf(source_dir, ACL_TYPE_DEFAULT);
401 	if (acl == NULL) {
402 		warn("failed to get default acl entries on %s",
403 		    source_dir);
404 		return (1);
405 	}
406 	aclp = &acl->ats_acl;
407 	if (aclp->acl_cnt != 0 && aclsetf(dest_dir,
408 	    ACL_TYPE_DEFAULT, acl) < 0) {
409 		warn("failed to set default acl entries on %s",
410 		    dest_dir);
411 		return (1);
412 	}
413 	acl = aclgetf(source_dir, ACL_TYPE_ACCESS);
414 	if (acl == NULL) {
415 		warn("failed to get acl entries on %s", source_dir);
416 		return (1);
417 	}
418 	aclp = &acl->ats_acl;
419 	if (aclsetf(dest_dir, ACL_TYPE_ACCESS, acl) < 0) {
420 		warn("failed to set acl entries on %s", dest_dir);
421 		return (1);
422 	}
423 	return (0);
424 }
425 
426 void
427 usage(void)
428 {
429 
430 	(void)fprintf(stderr, "%s\n%s\n",
431 "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpv] source_file target_file",
432 "       cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpv] source_file ... "
433 "target_directory");
434 	exit(EX_USAGE);
435 }
436