xref: /freebsd/bin/cp/utils.c (revision a8445737e740901f5f2c8d24c12ef7fc8b00134e)
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 	"$Id: utils.c,v 1.19 1998/06/09 03:38:26 imp Exp $";
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 (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 irreplacable.  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 	(void)close(from_fd);
196 	if (close(to_fd)) {
197 		warn("%s", to.p_path);
198 		rval = 1;
199 	}
200 	return (rval);
201 }
202 
203 int
204 copy_link(p, exists)
205 	FTSENT *p;
206 	int exists;
207 {
208 	int len;
209 	char link[MAXPATHLEN];
210 
211 	if ((len = readlink(p->fts_path, link, sizeof(link) - 1)) == -1) {
212 		warn("readlink: %s", p->fts_path);
213 		return (1);
214 	}
215 	link[len] = '\0';
216 	if (exists && unlink(to.p_path)) {
217 		warn("unlink: %s", to.p_path);
218 		return (1);
219 	}
220 	if (symlink(link, to.p_path)) {
221 		warn("symlink: %s", link);
222 		return (1);
223 	}
224 	return (0);
225 }
226 
227 int
228 copy_fifo(from_stat, exists)
229 	struct stat *from_stat;
230 	int exists;
231 {
232 	if (exists && unlink(to.p_path)) {
233 		warn("unlink: %s", to.p_path);
234 		return (1);
235 	}
236 	if (mkfifo(to.p_path, from_stat->st_mode)) {
237 		warn("mkfifo: %s", to.p_path);
238 		return (1);
239 	}
240 	return (pflag ? setfile(from_stat, 0) : 0);
241 }
242 
243 int
244 copy_special(from_stat, exists)
245 	struct stat *from_stat;
246 	int exists;
247 {
248 	if (exists && unlink(to.p_path)) {
249 		warn("unlink: %s", to.p_path);
250 		return (1);
251 	}
252 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
253 		warn("mknod: %s", to.p_path);
254 		return (1);
255 	}
256 	return (pflag ? setfile(from_stat, 0) : 0);
257 }
258 
259 
260 int
261 setfile(fs, fd)
262 	register struct stat *fs;
263 	int fd;
264 {
265 	static struct timeval tv[2];
266 	struct stat ts;
267 	int rval;
268 	int gotstat;
269 
270 	rval = 0;
271 	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
272 		       S_IRWXU | S_IRWXG | S_IRWXO;
273 
274 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
275 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
276 	if (utimes(to.p_path, tv)) {
277 		warn("utimes: %s", to.p_path);
278 		rval = 1;
279 	}
280 	if (fd ? fstat(fd, &ts) : stat(to.p_path, &ts))
281 		gotstat = 0;
282 	else {
283 		gotstat = 1;
284 		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
285 			      S_IRWXU | S_IRWXG | S_IRWXO;
286 	}
287 	/*
288 	 * Changing the ownership probably won't succeed, unless we're root
289 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
290 	 * the mode; current BSD behavior is to remove all setuid bits on
291 	 * chown.  If chown fails, lose setuid/setgid bits.
292 	 */
293 	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
294 		if (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
295 		    chown(to.p_path, fs->st_uid, fs->st_gid)) {
296 			if (errno != EPERM) {
297 				warn("chown: %s", to.p_path);
298 				rval = 1;
299 			}
300 			fs->st_mode &= ~(S_ISUID | S_ISGID);
301 		}
302 
303 	if (!gotstat || fs->st_mode != ts.st_mode)
304 		if (fd ? fchmod(fd, fs->st_mode) : chmod(to.p_path, fs->st_mode)) {
305 			warn("chown: %s", to.p_path);
306 			rval = 1;
307 		}
308 
309 	if (!gotstat || fs->st_flags != ts.st_flags)
310 		if (fd ?
311 		    fchflags(fd, fs->st_flags) : chflags(to.p_path, fs->st_flags)) {
312 			warn("chflags: %s", to.p_path);
313 			rval = 1;
314 		}
315 
316 	return (rval);
317 }
318 
319 void
320 usage()
321 {
322 	(void)fprintf(stderr, "%s\n%s\n",
323 "usage: cp [-R [-H | -L | -P]] [-f | -i] [-p] src target",
324 "       cp [-R [-H | -L | -P]] [-f | -i] [-p] src1 ... srcN directory");
325 	exit(1);
326 }
327