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