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