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