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