xref: /freebsd/bin/cp/utils.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
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 	(void)close(from_fd);
215 
216 	/*
217 	 * Don't remove the target even after an error.  The target might
218 	 * not be a regular file, or its attributes might be important,
219 	 * or its contents might be irreplaceable.  It would only be safe
220 	 * to remove it if we created it and its length is 0.
221 	 */
222 
223 	if (!lflag) {
224 		if (pflag && setfile(fs, to_fd))
225 			rval = 1;
226 		if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
227 			rval = 1;
228 		(void)close(from_fd);
229 		if (close(to_fd)) {
230 			warn("%s", to.p_path);
231 			rval = 1;
232 		}
233 	}
234 	return (rval);
235 }
236 
237 int
238 copy_link(const FTSENT *p, int exists)
239 {
240 	int len;
241 	char llink[PATH_MAX];
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 	if (exists && unlink(to.p_path)) {
263 		warn("unlink: %s", to.p_path);
264 		return (1);
265 	}
266 	if (mkfifo(to.p_path, from_stat->st_mode)) {
267 		warn("mkfifo: %s", to.p_path);
268 		return (1);
269 	}
270 	return (pflag ? setfile(from_stat, -1) : 0);
271 }
272 
273 int
274 copy_special(struct stat *from_stat, int exists)
275 {
276 	if (exists && unlink(to.p_path)) {
277 		warn("unlink: %s", to.p_path);
278 		return (1);
279 	}
280 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
281 		warn("mknod: %s", to.p_path);
282 		return (1);
283 	}
284 	return (pflag ? setfile(from_stat, -1) : 0);
285 }
286 
287 int
288 setfile(struct stat *fs, int fd)
289 {
290 	static struct timeval tv[2];
291 	struct stat ts;
292 	int rval, gotstat, islink, fdval;
293 
294 	rval = 0;
295 	fdval = fd != -1;
296 	islink = !fdval && S_ISLNK(fs->st_mode);
297 	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
298 		       S_IRWXU | S_IRWXG | S_IRWXO;
299 
300 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
301 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
302 	if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
303 		warn("%sutimes: %s", islink ? "l" : "", to.p_path);
304 		rval = 1;
305 	}
306 	if (fdval ? fstat(fd, &ts) :
307 	    (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
308 		gotstat = 0;
309 	else {
310 		gotstat = 1;
311 		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
312 			      S_IRWXU | S_IRWXG | S_IRWXO;
313 	}
314 	/*
315 	 * Changing the ownership probably won't succeed, unless we're root
316 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
317 	 * the mode; current BSD behavior is to remove all setuid bits on
318 	 * chown.  If chown fails, lose setuid/setgid bits.
319 	 */
320 	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
321 		if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
322 		    (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
323 		    chown(to.p_path, fs->st_uid, fs->st_gid))) {
324 			if (errno != EPERM) {
325 				warn("chown: %s", to.p_path);
326 				rval = 1;
327 			}
328 			fs->st_mode &= ~(S_ISUID | S_ISGID);
329 		}
330 
331 	if (!gotstat || fs->st_mode != ts.st_mode)
332 		if (fdval ? fchmod(fd, fs->st_mode) :
333 		    (islink ? lchmod(to.p_path, fs->st_mode) :
334 		    chmod(to.p_path, fs->st_mode))) {
335 			warn("chmod: %s", to.p_path);
336 			rval = 1;
337 		}
338 
339 	if (!gotstat || fs->st_flags != ts.st_flags)
340 		if (fdval ?
341 		    fchflags(fd, fs->st_flags) :
342 		    (islink ? (errno = ENOSYS) :
343 		    chflags(to.p_path, fs->st_flags))) {
344 			warn("chflags: %s", to.p_path);
345 			rval = 1;
346 		}
347 
348 	return (rval);
349 }
350 
351 int
352 preserve_fd_acls(int source_fd, int dest_fd)
353 {
354 	struct acl *aclp;
355 	acl_t acl;
356 
357 	if (fpathconf(source_fd, _PC_ACL_EXTENDED) != 1 ||
358 	    fpathconf(dest_fd, _PC_ACL_EXTENDED) != 1)
359 		return (0);
360 	acl = acl_get_fd(source_fd);
361 	if (acl == NULL) {
362 		warn("failed to get acl entries while setting %s", to.p_path);
363 		return (1);
364 	}
365 	aclp = &acl->ats_acl;
366 	if (aclp->acl_cnt == 3)
367 		return (0);
368 	if (acl_set_fd(dest_fd, acl) < 0) {
369 		warn("failed to set acl entries for %s", to.p_path);
370 		return (1);
371 	}
372 	return (0);
373 }
374 
375 int
376 preserve_dir_acls(struct stat *fs, char *source_dir, char *dest_dir)
377 {
378 	acl_t (*aclgetf)(const char *, acl_type_t);
379 	int (*aclsetf)(const char *, acl_type_t, acl_t);
380 	struct acl *aclp;
381 	acl_t acl;
382 
383 	if (pathconf(source_dir, _PC_ACL_EXTENDED) != 1 ||
384 	    pathconf(dest_dir, _PC_ACL_EXTENDED) != 1)
385 		return (0);
386 	/*
387 	 * If the file is a link we will not follow it
388 	 */
389 	if (S_ISLNK(fs->st_mode)) {
390 		aclgetf = acl_get_link_np;
391 		aclsetf = acl_set_link_np;
392 	} else {
393 		aclgetf = acl_get_file;
394 		aclsetf = acl_set_file;
395 	}
396 	/*
397 	 * Even if there is no ACL_TYPE_DEFAULT entry here, a zero
398 	 * size ACL will be returned. So it is not safe to simply
399 	 * check the pointer to see if the default ACL is present.
400 	 */
401 	acl = aclgetf(source_dir, ACL_TYPE_DEFAULT);
402 	if (acl == NULL) {
403 		warn("failed to get default acl entries on %s",
404 		    source_dir);
405 		return (1);
406 	}
407 	aclp = &acl->ats_acl;
408 	if (aclp->acl_cnt != 0 && aclsetf(dest_dir,
409 	    ACL_TYPE_DEFAULT, acl) < 0) {
410 		warn("failed to set default acl entries on %s",
411 		    dest_dir);
412 		return (1);
413 	}
414 	acl = aclgetf(source_dir, ACL_TYPE_ACCESS);
415 	if (acl == NULL) {
416 		warn("failed to get acl entries on %s", source_dir);
417 		return (1);
418 	}
419 	aclp = &acl->ats_acl;
420 	if (aclsetf(dest_dir, ACL_TYPE_ACCESS, acl) < 0) {
421 		warn("failed to set acl entries on %s", dest_dir);
422 		return (1);
423 	}
424 	return (0);
425 }
426 
427 void
428 usage(void)
429 {
430 
431 	(void)fprintf(stderr, "%s\n%s\n",
432 "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-lpv] source_file target_file",
433 "       cp [-R [-H | -L | -P]] [-f | -i | -n] [-lpv] source_file ... "
434 "target_directory");
435 	exit(EX_USAGE);
436 }
437