xref: /freebsd/bin/cp/utils.c (revision daf1cffce2e07931f27c6c6998652e90df6ba87e)
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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 #if 0
36 static char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
37 #endif
38 static const char rcsid[] =
39   "$FreeBSD$";
40 #endif /* not lint */
41 
42 #include <sys/param.h>
43 #include <sys/stat.h>
44 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
45 #include <sys/mman.h>
46 #endif
47 
48 #include <err.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <fts.h>
52 #include <stdio.h>
53 #include <sysexits.h>
54 #include <unistd.h>
55 
56 #include "extern.h"
57 
58 int
59 copy_file(entp, dne)
60 	FTSENT *entp;
61 	int dne;
62 {
63 	static char buf[MAXBSIZE];
64 	struct stat to_stat, *fs;
65 	int ch, checkch, from_fd, rcount, rval, to_fd, wcount, wresid;
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 (iflag) {
89 			(void)fprintf(stderr, "overwrite %s? %s",
90 					to.p_path, YESNO);
91 			checkch = ch = getchar();
92 			while (ch != '\n' && ch != EOF)
93 				ch = getchar();
94 			if (checkch != 'y' && checkch != 'Y') {
95 				(void)close(from_fd);
96 				(void)fprintf(stderr, "not overwritten\n");
97 				return (1);
98 			}
99 		}
100 
101 		if (fflag) {
102 		    /* remove existing destination file name,
103 		     * create a new file  */
104 		    (void)unlink(to.p_path);
105 		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
106 				 fs->st_mode & ~(S_ISUID | S_ISGID));
107 		} else
108 		    /* overwrite existing destination file name */
109 		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
110 	} else
111 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
112 		    fs->st_mode & ~(S_ISUID | S_ISGID));
113 
114 	if (to_fd == -1) {
115 		warn("%s", to.p_path);
116 		(void)close(from_fd);
117 		return (1);;
118 	}
119 
120 	rval = 0;
121 
122 	/*
123 	 * Mmap and write if less than 8M (the limit is so we don't totally
124 	 * trash memory on big files.  This is really a minor hack, but it
125 	 * wins some CPU back.
126 	 */
127 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
128 	if (S_ISREG(fs->st_mode) && fs->st_size <= 8 * 1048576) {
129 		if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
130 		    MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
131 			warn("%s", entp->fts_path);
132 			rval = 1;
133 		} else {
134 			for (bufp = p, wresid = fs->st_size; ;
135 			    bufp += wcount, wresid -= wcount) {
136 				wcount = write(to_fd, bufp, wresid);
137 				if (wcount >= wresid || wcount <= 0)
138 					break;
139 			}
140 			if (wcount != wresid) {
141 				warn("%s", to.p_path);
142 				rval = 1;
143 			}
144 			/* Some systems don't unmap on close(2). */
145 			if (munmap(p, fs->st_size) < 0) {
146 				warn("%s", entp->fts_path);
147 				rval = 1;
148 			}
149 		}
150 	} else
151 #endif
152 	{
153 		while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
154 			for (bufp = buf, wresid = rcount; ;
155 			    bufp += wcount, wresid -= wcount) {
156 				wcount = write(to_fd, bufp, wresid);
157 				if (wcount >= wresid || wcount <= 0)
158 					break;
159 			}
160 			if (wcount != wresid) {
161 				warn("%s", to.p_path);
162 				rval = 1;
163 				break;
164 			}
165 		}
166 		if (rcount < 0) {
167 			warn("%s", entp->fts_path);
168 			rval = 1;
169 		}
170 	}
171 
172 	/*
173 	 * Don't remove the target even after an error.  The target might
174 	 * not be a regular file, or its attributes might be important,
175 	 * or its contents might be irreplaceable.  It would only be safe
176 	 * to remove it if we created it and its length is 0.
177 	 */
178 
179 	if (pflag && setfile(fs, to_fd))
180 		rval = 1;
181 	/*
182 	 * If the source was setuid or setgid, lose the bits unless the
183 	 * copy is owned by the same user and group.
184 	 */
185 #define	RETAINBITS \
186 	(S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
187 	else if (fs->st_mode & (S_ISUID | S_ISGID) && fs->st_uid == myuid) {
188 		if (fstat(to_fd, &to_stat)) {
189 			warn("%s", to.p_path);
190 			rval = 1;
191 		} else if (fs->st_gid == to_stat.st_gid &&
192 		    fchmod(to_fd, fs->st_mode & RETAINBITS & ~myumask)) {
193 			warn("%s", to.p_path);
194 			rval = 1;
195 		}
196 	}
197 	(void)close(from_fd);
198 	if (close(to_fd)) {
199 		warn("%s", to.p_path);
200 		rval = 1;
201 	}
202 	return (rval);
203 }
204 
205 int
206 copy_link(p, exists)
207 	FTSENT *p;
208 	int exists;
209 {
210 	int len;
211 	char link[MAXPATHLEN];
212 
213 	if ((len = readlink(p->fts_path, link, sizeof(link) - 1)) == -1) {
214 		warn("readlink: %s", p->fts_path);
215 		return (1);
216 	}
217 	link[len] = '\0';
218 	if (exists && unlink(to.p_path)) {
219 		warn("unlink: %s", to.p_path);
220 		return (1);
221 	}
222 	if (symlink(link, to.p_path)) {
223 		warn("symlink: %s", link);
224 		return (1);
225 	}
226 	return (0);
227 }
228 
229 int
230 copy_fifo(from_stat, exists)
231 	struct stat *from_stat;
232 	int exists;
233 {
234 	if (exists && unlink(to.p_path)) {
235 		warn("unlink: %s", to.p_path);
236 		return (1);
237 	}
238 	if (mkfifo(to.p_path, from_stat->st_mode)) {
239 		warn("mkfifo: %s", to.p_path);
240 		return (1);
241 	}
242 	return (pflag ? setfile(from_stat, 0) : 0);
243 }
244 
245 int
246 copy_special(from_stat, exists)
247 	struct stat *from_stat;
248 	int exists;
249 {
250 	if (exists && unlink(to.p_path)) {
251 		warn("unlink: %s", to.p_path);
252 		return (1);
253 	}
254 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
255 		warn("mknod: %s", to.p_path);
256 		return (1);
257 	}
258 	return (pflag ? setfile(from_stat, 0) : 0);
259 }
260 
261 
262 int
263 setfile(fs, fd)
264 	register struct stat *fs;
265 	int fd;
266 {
267 	static struct timeval tv[2];
268 	struct stat ts;
269 	int rval;
270 	int gotstat;
271 
272 	rval = 0;
273 	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
274 		       S_IRWXU | S_IRWXG | S_IRWXO;
275 
276 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
277 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
278 	if (utimes(to.p_path, tv)) {
279 		warn("utimes: %s", to.p_path);
280 		rval = 1;
281 	}
282 	if (fd ? fstat(fd, &ts) : stat(to.p_path, &ts))
283 		gotstat = 0;
284 	else {
285 		gotstat = 1;
286 		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
287 			      S_IRWXU | S_IRWXG | S_IRWXO;
288 	}
289 	/*
290 	 * Changing the ownership probably won't succeed, unless we're root
291 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
292 	 * the mode; current BSD behavior is to remove all setuid bits on
293 	 * chown.  If chown fails, lose setuid/setgid bits.
294 	 */
295 	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
296 		if (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
297 		    chown(to.p_path, fs->st_uid, fs->st_gid)) {
298 			if (errno != EPERM) {
299 				warn("chown: %s", to.p_path);
300 				rval = 1;
301 			}
302 			fs->st_mode &= ~(S_ISUID | S_ISGID);
303 		}
304 
305 	if (!gotstat || fs->st_mode != ts.st_mode)
306 		if (fd ? fchmod(fd, fs->st_mode) : chmod(to.p_path, fs->st_mode)) {
307 			warn("chown: %s", to.p_path);
308 			rval = 1;
309 		}
310 
311 	if (!gotstat || fs->st_flags != ts.st_flags)
312 		if (fd ?
313 		    fchflags(fd, fs->st_flags) : chflags(to.p_path, fs->st_flags)) {
314 			warn("chflags: %s", to.p_path);
315 			rval = 1;
316 		}
317 
318 	return (rval);
319 }
320 
321 void
322 usage()
323 {
324 
325 	(void)fprintf(stderr, "%s\n%s\n",
326 "usage: cp [-R [-H | -L | -P]] [-f | -i] [-pv] src target",
327 "       cp [-R [-H | -L | -P]] [-f | -i] [-pv] src1 ... srcN directory");
328 	exit(EX_USAGE);
329 }
330