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