xref: /freebsd/bin/cp/utils.c (revision 2357939bc239bd5334a169b62313806178dd8f30)
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/param.h>
39 #include <sys/stat.h>
40 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
41 #include <sys/mman.h>
42 #endif
43 
44 #include <err.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <fts.h>
48 #include <limits.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <sysexits.h>
52 #include <unistd.h>
53 
54 #include "extern.h"
55 #define	cp_pct(x,y)	(int)(100.0 * (double)(x) / (double)(y))
56 
57 int
58 copy_file(const FTSENT *entp, int dne)
59 {
60 	static char buf[MAXBSIZE];
61 	struct stat *fs;
62 	int ch, checkch, from_fd, rcount, rval, to_fd;
63 	ssize_t wcount;
64 	size_t wresid;
65 	size_t wtotal;
66 	char *bufp;
67 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
68 	char *p;
69 #endif
70 
71 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
72 		warn("%s", entp->fts_path);
73 		return (1);
74 	}
75 
76 	fs = entp->fts_statp;
77 
78 	/*
79 	 * If the file exists and we're interactive, verify with the user.
80 	 * If the file DNE, set the mode to be the from file, minus setuid
81 	 * bits, modified by the umask; arguably wrong, but it makes copying
82 	 * executables work right and it's been that way forever.  (The
83 	 * other choice is 666 or'ed with the execute bits on the from file
84 	 * modified by the umask.)
85 	 */
86 	if (!dne) {
87 #define YESNO "(y/n [n]) "
88 		if (nflag) {
89 			if (vflag)
90 				printf("%s not overwritten\n", to.p_path);
91 			return (0);
92 		} else if (iflag) {
93 			(void)fprintf(stderr, "overwrite %s? %s",
94 					to.p_path, YESNO);
95 			checkch = ch = getchar();
96 			while (ch != '\n' && ch != EOF)
97 				ch = getchar();
98 			if (checkch != 'y' && checkch != 'Y') {
99 				(void)close(from_fd);
100 				(void)fprintf(stderr, "not overwritten\n");
101 				return (1);
102 			}
103 		}
104 
105 		if (fflag) {
106 		    /* remove existing destination file name,
107 		     * create a new file  */
108 		    (void)unlink(to.p_path);
109 		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
110 				 fs->st_mode & ~(S_ISUID | S_ISGID));
111 		} else
112 		    /* overwrite existing destination file name */
113 		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
114 	} else
115 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
116 		    fs->st_mode & ~(S_ISUID | S_ISGID));
117 
118 	if (to_fd == -1) {
119 		warn("%s", to.p_path);
120 		(void)close(from_fd);
121 		return (1);
122 	}
123 
124 	rval = 0;
125 
126 	/*
127 	 * Mmap and write if less than 8M (the limit is so we don't totally
128 	 * trash memory on big files.  This is really a minor hack, but it
129 	 * wins some CPU back.
130 	 */
131 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
132 	if (S_ISREG(fs->st_mode) && fs->st_size > 0 &&
133 	    fs->st_size <= 8 * 1048576) {
134 		if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
135 		    MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
136 			warn("%s", entp->fts_path);
137 			rval = 1;
138 		} else {
139 			wtotal = 0;
140 			for (bufp = p, wresid = fs->st_size; ;
141 			    bufp += wcount, wresid -= (size_t)wcount) {
142 				wcount = write(to_fd, bufp, wresid);
143 				wtotal += wcount;
144 				if (info) {
145 					info = 0;
146 					(void)fprintf(stderr,
147 						"%s -> %s %3d%%\n",
148 						entp->fts_path, to.p_path,
149 						cp_pct(wtotal, fs->st_size));
150 
151 				}
152 				if (wcount >= (ssize_t)wresid || wcount <= 0)
153 					break;
154 			}
155 			if (wcount != (ssize_t)wresid) {
156 				warn("%s", to.p_path);
157 				rval = 1;
158 			}
159 			/* Some systems don't unmap on close(2). */
160 			if (munmap(p, fs->st_size) < 0) {
161 				warn("%s", entp->fts_path);
162 				rval = 1;
163 			}
164 		}
165 	} else
166 #endif
167 	{
168 		wtotal = 0;
169 		while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
170 			for (bufp = buf, wresid = rcount; ;
171 			    bufp += wcount, wresid -= wcount) {
172 				wcount = write(to_fd, bufp, wresid);
173 				wtotal += wcount;
174 				if (info) {
175 					info = 0;
176 					(void)fprintf(stderr,
177 						"%s -> %s %3d%%\n",
178 						entp->fts_path, to.p_path,
179 						cp_pct(wtotal, fs->st_size));
180 
181 				}
182 				if (wcount >= (ssize_t)wresid || wcount <= 0)
183 					break;
184 			}
185 			if (wcount != (ssize_t)wresid) {
186 				warn("%s", to.p_path);
187 				rval = 1;
188 				break;
189 			}
190 		}
191 		if (rcount < 0) {
192 			warn("%s", entp->fts_path);
193 			rval = 1;
194 		}
195 	}
196 
197 	/*
198 	 * Don't remove the target even after an error.  The target might
199 	 * not be a regular file, or its attributes might be important,
200 	 * or its contents might be irreplaceable.  It would only be safe
201 	 * to remove it if we created it and its length is 0.
202 	 */
203 
204 	if (pflag && setfile(fs, to_fd))
205 		rval = 1;
206 	(void)close(from_fd);
207 	if (close(to_fd)) {
208 		warn("%s", to.p_path);
209 		rval = 1;
210 	}
211 	return (rval);
212 }
213 
214 int
215 copy_link(const FTSENT *p, int exists)
216 {
217 	int len;
218 	char llink[PATH_MAX];
219 
220 	if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
221 		warn("readlink: %s", p->fts_path);
222 		return (1);
223 	}
224 	llink[len] = '\0';
225 	if (exists && unlink(to.p_path)) {
226 		warn("unlink: %s", to.p_path);
227 		return (1);
228 	}
229 	if (symlink(llink, to.p_path)) {
230 		warn("symlink: %s", llink);
231 		return (1);
232 	}
233 	return (pflag ? setfile(p->fts_statp, -1) : 0);
234 }
235 
236 int
237 copy_fifo(struct stat *from_stat, int exists)
238 {
239 	if (exists && unlink(to.p_path)) {
240 		warn("unlink: %s", to.p_path);
241 		return (1);
242 	}
243 	if (mkfifo(to.p_path, from_stat->st_mode)) {
244 		warn("mkfifo: %s", to.p_path);
245 		return (1);
246 	}
247 	return (pflag ? setfile(from_stat, -1) : 0);
248 }
249 
250 int
251 copy_special(struct stat *from_stat, int exists)
252 {
253 	if (exists && unlink(to.p_path)) {
254 		warn("unlink: %s", to.p_path);
255 		return (1);
256 	}
257 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
258 		warn("mknod: %s", to.p_path);
259 		return (1);
260 	}
261 	return (pflag ? setfile(from_stat, -1) : 0);
262 }
263 
264 int
265 setfile(struct stat *fs, int fd)
266 {
267 	static struct timeval tv[2];
268 	struct stat ts;
269 	int rval, gotstat, islink, fdval;
270 
271 	rval = 0;
272 	fdval = fd != -1;
273 	islink = !fdval && S_ISLNK(fs->st_mode);
274 	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
275 		       S_IRWXU | S_IRWXG | S_IRWXO;
276 
277 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
278 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
279 	if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
280 		warn("%sutimes: %s", islink ? "l" : "", to.p_path);
281 		rval = 1;
282 	}
283 	if (fdval ? fstat(fd, &ts) :
284 	    (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
285 		gotstat = 0;
286 	else {
287 		gotstat = 1;
288 		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
289 			      S_IRWXU | S_IRWXG | S_IRWXO;
290 	}
291 	/*
292 	 * Changing the ownership probably won't succeed, unless we're root
293 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
294 	 * the mode; current BSD behavior is to remove all setuid bits on
295 	 * chown.  If chown fails, lose setuid/setgid bits.
296 	 */
297 	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
298 		if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
299 		    (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
300 		    chown(to.p_path, fs->st_uid, fs->st_gid))) {
301 			if (errno != EPERM) {
302 				warn("chown: %s", to.p_path);
303 				rval = 1;
304 			}
305 			fs->st_mode &= ~(S_ISUID | S_ISGID);
306 		}
307 
308 	if (!gotstat || fs->st_mode != ts.st_mode)
309 		if (fdval ? fchmod(fd, fs->st_mode) :
310 		    (islink ? lchmod(to.p_path, fs->st_mode) :
311 		    chmod(to.p_path, fs->st_mode))) {
312 			warn("chmod: %s", to.p_path);
313 			rval = 1;
314 		}
315 
316 	if (!gotstat || fs->st_flags != ts.st_flags)
317 		if (fdval ?
318 		    fchflags(fd, fs->st_flags) :
319 		    (islink ? (errno = ENOSYS) :
320 		    chflags(to.p_path, fs->st_flags))) {
321 			warn("chflags: %s", to.p_path);
322 			rval = 1;
323 		}
324 
325 	return (rval);
326 }
327 
328 void
329 usage(void)
330 {
331 
332 	(void)fprintf(stderr, "%s\n%s\n",
333 "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-pv] src target",
334 "       cp [-R [-H | -L | -P]] [-f | -i | -n] [-pv] src1 ... srcN directory");
335 	exit(EX_USAGE);
336 }
337