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