xref: /openbsd/bin/cp/utils.c (revision 09467b48)
1 /*	$OpenBSD: utils.c,v 1.48 2019/06/28 13:34:58 deraadt 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 #include <sys/param.h>		/* MAXBSIZE */
34 #include <sys/stat.h>
35 #include <sys/mman.h>
36 #include <sys/time.h>
37 
38 #include <err.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <fts.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <limits.h>
47 
48 #include "extern.h"
49 
50 int copy_overwrite(void);
51 
52 int
53 copy_file(FTSENT *entp, int exists)
54 {
55 	static char *buf;
56 	static char *zeroes;
57 	struct stat to_stat, *fs;
58 	int from_fd, rcount, rval, to_fd, wcount;
59 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
60 	char *p;
61 #endif
62 
63 	if (!buf) {
64 		buf = malloc(MAXBSIZE);
65 		if (!buf)
66 			err(1, "malloc");
67 	}
68 	if (!zeroes) {
69 		zeroes = calloc(1, MAXBSIZE);
70 		if (!zeroes)
71 			err(1, "calloc");
72 	}
73 
74 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
75 		warn("%s", entp->fts_path);
76 		return (1);
77 	}
78 
79 	fs = entp->fts_statp;
80 
81 	/*
82 	 * In -f (force) mode, we always unlink the destination first
83 	 * if it exists.  Note that -i and -f are mutually exclusive.
84 	 */
85 	if (exists && fflag)
86 		(void)unlink(to.p_path);
87 
88 	/*
89 	 * If the file DNE, set the mode to be the from file, minus setuid
90 	 * bits, modified by the umask; arguably wrong, but it makes copying
91 	 * executables work right and it's been that way forever.  (The
92 	 * other choice is 666 or'ed with the execute bits on the from file
93 	 * modified by the umask.)
94 	 */
95 	if (exists && !fflag) {
96 		if (!copy_overwrite()) {
97 			(void)close(from_fd);
98 			return 2;
99  		}
100 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
101 	} else
102 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
103 		    fs->st_mode & ~(S_ISTXT | S_ISUID | S_ISGID));
104 
105 	if (to_fd == -1) {
106 		warn("%s", to.p_path);
107 		(void)close(from_fd);
108 		return (1);
109 	}
110 
111 	rval = 0;
112 
113 	/*
114 	 * Mmap and write if less than 8M (the limit is so we don't totally
115 	 * trash memory on big files.  This is really a minor hack, but it
116 	 * wins some CPU back.
117 	 */
118 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
119 	/* XXX broken for 0-size mmap */
120 	if (fs->st_size <= 8 * 1048576) {
121 		if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
122 		    MAP_FILE|MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
123 			warn("mmap: %s", entp->fts_path);
124 			rval = 1;
125 		} else {
126 			madvise(p, fs->st_size, MADV_SEQUENTIAL);
127 			if (write(to_fd, p, fs->st_size) != fs->st_size) {
128 				warn("%s", to.p_path);
129 				rval = 1;
130 			}
131 			/* Some systems don't unmap on close(2). */
132 			if (munmap(p, fs->st_size) == -1) {
133 				warn("%s", entp->fts_path);
134 				rval = 1;
135 			}
136 		}
137 	} else
138 #endif
139 	{
140 		int skipholes = 0;
141 		struct stat tosb;
142 		if (!fstat(to_fd, &tosb) && S_ISREG(tosb.st_mode))
143 			skipholes = 1;
144 		while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
145 			if (skipholes && memcmp(buf, zeroes, rcount) == 0)
146 				wcount = lseek(to_fd, rcount, SEEK_CUR) == -1 ? -1 : rcount;
147 			else
148 				wcount = write(to_fd, buf, rcount);
149 			if (rcount != wcount || wcount == -1) {
150 				warn("%s", to.p_path);
151 				rval = 1;
152 				break;
153 			}
154 		}
155 		if (skipholes && rcount != -1)
156 			rcount = ftruncate(to_fd, lseek(to_fd, 0, SEEK_CUR));
157 		if (rcount == -1) {
158 			warn("%s", entp->fts_path);
159 			rval = 1;
160 		}
161 	}
162 
163 	if (rval == 1) {
164 		(void)close(from_fd);
165 		(void)close(to_fd);
166 		return (1);
167 	}
168 
169 	if (pflag && setfile(fs, to_fd))
170 		rval = 1;
171 	/*
172 	 * If the source was setuid or setgid, lose the bits unless the
173 	 * copy is owned by the same user and group.
174 	 */
175 #define	RETAINBITS \
176 	(S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
177 	if (!pflag && !exists &&
178 	    fs->st_mode & (S_ISUID | S_ISGID) && fs->st_uid == myuid) {
179 		if (fstat(to_fd, &to_stat)) {
180 			warn("%s", to.p_path);
181 			rval = 1;
182 		} else if (fs->st_gid == to_stat.st_gid &&
183 		    fchmod(to_fd, fs->st_mode & RETAINBITS & ~myumask)) {
184 			warn("%s", to.p_path);
185 			rval = 1;
186 		}
187 	}
188 	(void)close(from_fd);
189 	if (close(to_fd)) {
190 		warn("%s", to.p_path);
191 		rval = 1;
192 	}
193 	return (rval);
194 }
195 
196 int
197 copy_link(FTSENT *p, int exists)
198 {
199 	int len;
200 	char name[PATH_MAX];
201 
202 	if (exists && !copy_overwrite())
203 		return (2);
204 	if ((len = readlink(p->fts_path, name, sizeof(name)-1)) == -1) {
205 		warn("readlink: %s", p->fts_path);
206 		return (1);
207 	}
208 	name[len] = '\0';
209 	if (exists && unlink(to.p_path)) {
210 		warn("unlink: %s", to.p_path);
211 		return (1);
212 	}
213 	if (symlink(name, to.p_path)) {
214 		warn("symlink: %s", name);
215 		return (1);
216 	}
217 	return (pflag ? setfile(p->fts_statp, -1) : 0);
218 }
219 
220 int
221 copy_fifo(struct stat *from_stat, int exists)
222 {
223 	if (exists && !copy_overwrite())
224 		return (2);
225 	if (exists && unlink(to.p_path)) {
226 		warn("unlink: %s", to.p_path);
227 		return (1);
228 	}
229 	if (mkfifo(to.p_path, from_stat->st_mode)) {
230 		warn("mkfifo: %s", to.p_path);
231 		return (1);
232 	}
233 	return (pflag ? setfile(from_stat, -1) : 0);
234 }
235 
236 int
237 copy_special(struct stat *from_stat, int exists)
238 {
239 	if (exists && !copy_overwrite())
240 		return (2);
241 	if (exists && unlink(to.p_path)) {
242 		warn("unlink: %s", to.p_path);
243 		return (1);
244 	}
245 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
246 		warn("mknod: %s", to.p_path);
247 		return (1);
248 	}
249 	return (pflag ? setfile(from_stat, -1) : 0);
250 }
251 
252 /*
253  * If the file exists and we're interactive, verify with the user.
254  */
255 int
256 copy_overwrite(void)
257 {
258 	int ch, checkch;
259 
260 	if (iflag) {
261 		(void)fprintf(stderr, "overwrite %s? ", to.p_path);
262 		checkch = ch = getchar();
263 		while (ch != '\n' && ch != EOF)
264 			ch = getchar();
265 		if (checkch != 'y' && checkch != 'Y')
266 			return (0);
267 	}
268 	return 1;
269 }
270 
271 int
272 setfile(struct stat *fs, int fd)
273 {
274 	struct timespec ts[2];
275 	int rval;
276 
277 	rval = 0;
278 	fs->st_mode &= S_ISTXT | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
279 
280 	ts[0] = fs->st_atim;
281 	ts[1] = fs->st_mtim;
282 	if (fd >= 0 ? futimens(fd, ts) :
283 	    utimensat(AT_FDCWD, to.p_path, ts, AT_SYMLINK_NOFOLLOW)) {
284 		warn("update times: %s", to.p_path);
285 		rval = 1;
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 (fd >= 0 ? fchown(fd, fs->st_uid, fs->st_gid) :
294 	    lchown(to.p_path, fs->st_uid, fs->st_gid)) {
295 		if (errno != EPERM) {
296 			warn("chown: %s", to.p_path);
297 			rval = 1;
298 		}
299 		fs->st_mode &= ~(S_ISTXT | S_ISUID | S_ISGID);
300 	}
301 	if (fd >= 0 ? fchmod(fd, fs->st_mode) :
302 	    fchmodat(AT_FDCWD, to.p_path, fs->st_mode, AT_SYMLINK_NOFOLLOW)) {
303 		warn("chmod: %s", to.p_path);
304 		rval = 1;
305 	}
306 
307 	/*
308 	 * XXX
309 	 * NFS doesn't support chflags; ignore errors unless there's reason
310 	 * to believe we're losing bits.  (Note, this still won't be right
311 	 * if the server supports flags and we were trying to *remove* flags
312 	 * on a file that we copied, i.e., that we didn't create.)
313 	 */
314 	errno = 0;
315 	if (fd >= 0 ? fchflags(fd, fs->st_flags) :
316 	    chflagsat(AT_FDCWD, to.p_path, fs->st_flags, AT_SYMLINK_NOFOLLOW))
317 		if (errno != EOPNOTSUPP || fs->st_flags != 0) {
318 			warn("chflags: %s", to.p_path);
319 			rval = 1;
320 		}
321 	return (rval);
322 }
323 
324 
325 void
326 usage(void)
327 {
328 	(void)fprintf(stderr,
329 	    "usage: %s [-afipv] [-R [-H | -L | -P]] source target\n", __progname);
330 	(void)fprintf(stderr,
331 	    "       %s [-afipv] [-R [-H | -L | -P]] source ... directory\n",
332 	    __progname);
333 	exit(1);
334 }
335