xref: /openbsd-src/bin/cp/utils.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: utils.c,v 1.29 2007/09/22 21:10:49 sobrado Exp $	*/
2 /*	$NetBSD: utils.c,v 1.6 1997/02/26 14:40:51 cgd Exp $	*/
3 
4 /*-
5  * Copyright (c) 1991, 1993, 1994
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
36 #else
37 static char rcsid[] = "$OpenBSD: utils.c,v 1.29 2007/09/22 21:10:49 sobrado Exp $";
38 #endif
39 #endif /* not lint */
40 
41 #include <sys/param.h>
42 #include <sys/stat.h>
43 #include <sys/mman.h>
44 #include <sys/time.h>
45 
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <fts.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 
55 #include "extern.h"
56 
57 int
58 copy_file(FTSENT *entp, int dne)
59 {
60 	static char *buf;
61 	static char *zeroes;
62 	struct stat to_stat, *fs;
63 	int ch, checkch, from_fd, rcount, rval, to_fd, wcount;
64 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
65 	char *p;
66 #endif
67 
68 	if (!buf) {
69 		buf = malloc(MAXBSIZE);
70 		if (!buf)
71 			err(1, "malloc");
72 	}
73 	if (!zeroes) {
74 		zeroes = malloc(MAXBSIZE);
75 		if (!zeroes)
76 			err(1, "malloc");
77 		memset(zeroes, 0, MAXBSIZE);
78 	}
79 
80 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
81 		warn("%s", entp->fts_path);
82 		return (1);
83 	}
84 
85 	fs = entp->fts_statp;
86 
87 	/*
88 	 * In -f (force) mode, we always unlink the destination first
89 	 * if it exists.  Note that -i and -f are mutually exclusive.
90 	 */
91 	if (!dne && fflag)
92 		(void)unlink(to.p_path);
93 
94 	/*
95 	 * If the file exists and we're interactive, verify with the user.
96 	 * If the file DNE, set the mode to be the from file, minus setuid
97 	 * bits, modified by the umask; arguably wrong, but it makes copying
98 	 * executables work right and it's been that way forever.  (The
99 	 * other choice is 666 or'ed with the execute bits on the from file
100 	 * modified by the umask.)
101 	 */
102 	if (!dne && !fflag) {
103 		if (iflag) {
104 			(void)fprintf(stderr, "overwrite %s? ", to.p_path);
105 			checkch = ch = getchar();
106 			while (ch != '\n' && ch != EOF)
107 				ch = getchar();
108 			if (checkch != 'y' && checkch != 'Y') {
109 				(void)close(from_fd);
110 				return (0);
111 			}
112 		}
113 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
114 	} else
115 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
116 		    fs->st_mode & ~(S_ISTXT | S_ISUID | S_ISGID));
117 
118 	if (to_fd == -1) {
119 		warn("%s", to.p_path);
120 		(void)close(from_fd);
121 		return (1);
122 	}
123 
124 	rval = 0;
125 
126 	/*
127 	 * Mmap and write if less than 8M (the limit is so we don't totally
128 	 * trash memory on big files.  This is really a minor hack, but it
129 	 * wins some CPU back.
130 	 */
131 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
132 	if (fs->st_size <= 8 * 1048576) {
133 		if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
134 		    MAP_FILE|MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
135 			warn("mmap: %s", entp->fts_path);
136 			rval = 1;
137 		} else {
138 			madvise(p, fs->st_size, MADV_SEQUENTIAL);
139 			if (write(to_fd, p, fs->st_size) != fs->st_size) {
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 		int skipholes = 0;
153 		struct stat tosb;
154 		if (!fstat(to_fd, &tosb) && S_ISREG(tosb.st_mode))
155 			skipholes = 1;
156 		while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
157 			if (skipholes && memcmp(buf, zeroes, rcount) == 0)
158 				wcount = lseek(to_fd, rcount, SEEK_CUR) == -1 ? -1 : rcount;
159 			else
160 				wcount = write(to_fd, buf, rcount);
161 			if (rcount != wcount || wcount == -1) {
162 				warn("%s", to.p_path);
163 				rval = 1;
164 				break;
165 			}
166 		}
167 		if (skipholes && rcount >= 0)
168 			rcount = ftruncate(to_fd, fs->st_size);
169 		if (rcount < 0) {
170 			warn("%s", entp->fts_path);
171 			rval = 1;
172 		}
173 	}
174 
175 	if (rval == 1) {
176 		(void)close(from_fd);
177 		(void)close(to_fd);
178 		return (1);
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(FTSENT *p, int exists)
209 {
210 	int len;
211 	char link[MAXPATHLEN];
212 
213 	if ((len = readlink(p->fts_path, link, sizeof(link)-1)) == -1) {
214 		warn("readlink: %s", p->fts_path);
215 		return (1);
216 	}
217 	link[len] = '\0';
218 	if (exists && unlink(to.p_path)) {
219 		warn("unlink: %s", to.p_path);
220 		return (1);
221 	}
222 	if (symlink(link, to.p_path)) {
223 		warn("symlink: %s", link);
224 		return (1);
225 	}
226 	return (pflag ? setlink(p->fts_statp) : 0);
227 }
228 
229 int
230 copy_fifo(struct stat *from_stat, 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(struct stat *from_stat, int exists)
245 {
246 	if (exists && unlink(to.p_path)) {
247 		warn("unlink: %s", to.p_path);
248 		return (1);
249 	}
250 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
251 		warn("mknod: %s", to.p_path);
252 		return (1);
253 	}
254 	return (pflag ? setfile(from_stat, 0) : 0);
255 }
256 
257 
258 int
259 setfile(struct stat *fs, int fd)
260 {
261 	static struct timeval tv[2];
262 	int rval;
263 
264 	rval = 0;
265 	fs->st_mode &= S_ISTXT | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
266 
267 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
268 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
269 	if (utimes(to.p_path, tv)) {
270 		warn("utimes: %s", to.p_path);
271 		rval = 1;
272 	}
273 	/*
274 	 * Changing the ownership probably won't succeed, unless we're root
275 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
276 	 * the mode; current BSD behavior is to remove all setuid bits on
277 	 * chown.  If chown fails, lose setuid/setgid bits.
278 	 */
279 	if (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
280 	    chown(to.p_path, fs->st_uid, fs->st_gid)) {
281 		if (errno != EPERM) {
282 			warn("chown: %s", to.p_path);
283 			rval = 1;
284 		}
285 		fs->st_mode &= ~(S_ISTXT | S_ISUID | S_ISGID);
286 	}
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 	/*
293 	 * XXX
294 	 * NFS doesn't support chflags; ignore errors unless there's reason
295 	 * to believe we're losing bits.  (Note, this still won't be right
296 	 * if the server supports flags and we were trying to *remove* flags
297 	 * on a file that we copied, i.e., that we didn't create.)
298 	 */
299 	errno = 0;
300 	if (fd ? fchflags(fd, fs->st_flags) : chflags(to.p_path, fs->st_flags))
301 		if (errno != EOPNOTSUPP || fs->st_flags != 0) {
302 			warn("chflags: %s", to.p_path);
303 			rval = 1;
304 		}
305 	return (rval);
306 }
307 
308 
309 int
310 setlink(struct stat *fs)
311 {
312 
313 	if (lchown(to.p_path, fs->st_uid, fs->st_gid)) {
314 		if (errno != EPERM) {
315 			warn("lchown: %s", to.p_path);
316 			return (1);
317 		}
318 	}
319 	return (0);
320 }
321 
322 
323 void
324 usage(void)
325 {
326 	(void)fprintf(stderr,
327 	    "usage: %s [-fip] [-R [-H | -L | -P]] source target\n", __progname);
328 	(void)fprintf(stderr,
329 	    "       %s [-fip] [-R [-H | -L | -P]] source ... directory\n",
330 	    __progname);
331 	exit(1);
332 }
333