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