xref: /netbsd-src/bin/cp/utils.c (revision 6cf6fe02a981b55727c49c3d37b0d8191a98c0ee)
1 /* $NetBSD: utils.c,v 1.42 2013/12/11 06:00:11 dholland Exp $ */
2 
3 /*-
4  * Copyright (c) 1991, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
36 #else
37 __RCSID("$NetBSD: utils.c,v 1.42 2013/12/11 06:00:11 dholland Exp $");
38 #endif
39 #endif /* not lint */
40 
41 #include <sys/mman.h>
42 #include <sys/param.h>
43 #include <sys/stat.h>
44 #include <sys/time.h>
45 #include <sys/extattr.h>
46 
47 #include <err.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <fts.h>
51 #include <stdbool.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 #include "extern.h"
58 
59 #define	MMAP_MAX_SIZE	(8 * 1048576)
60 #define	MMAP_MAX_WRITE	(64 * 1024)
61 
62 int
63 set_utimes(const char *file, struct stat *fs)
64 {
65     static struct timeval tv[2];
66 
67     TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
68     TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
69 
70     if (lutimes(file, tv)) {
71 	warn("lutimes: %s", file);
72 	return (1);
73     }
74     return (0);
75 }
76 
77 struct finfo {
78 	const char *from;
79 	const char *to;
80 	size_t size;
81 };
82 
83 static void
84 progress(const struct finfo *fi, size_t written)
85 {
86 	int pcent = (int)((100.0 * written) / fi->size);
87 
88 	pinfo = 0;
89 	(void)fprintf(stderr, "%s => %s %zu/%zu bytes %d%% written\n",
90 	    fi->from, fi->to, written, fi->size, pcent);
91 }
92 
93 int
94 copy_file(FTSENT *entp, int dne)
95 {
96 	static char buf[MAXBSIZE];
97 	struct stat to_stat, *fs;
98 	int ch, checkch, from_fd, rcount, rval, to_fd, tolnk, wcount;
99 	char *p;
100 	size_t ptotal = 0;
101 
102 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
103 		warn("%s", entp->fts_path);
104 		return (1);
105 	}
106 
107 	to_fd = -1;
108 	fs = entp->fts_statp;
109 	tolnk = ((Rflag && !(Lflag || Hflag)) || Pflag);
110 
111 	/*
112 	 * If the file exists and we're interactive, verify with the user.
113 	 * If the file DNE, set the mode to be the from file, minus setuid
114 	 * bits, modified by the umask; arguably wrong, but it makes copying
115 	 * executables work right and it's been that way forever.  (The
116 	 * other choice is 666 or'ed with the execute bits on the from file
117 	 * modified by the umask.)
118 	 */
119 	if (!dne) {
120 		struct stat sb;
121 		int sval;
122 
123 		if (iflag) {
124 			(void)fprintf(stderr, "overwrite %s? ", to.p_path);
125 			checkch = ch = getchar();
126 			while (ch != '\n' && ch != EOF)
127 				ch = getchar();
128 			if (checkch != 'y' && checkch != 'Y') {
129 				(void)close(from_fd);
130 				return (0);
131 			}
132 		}
133 
134 		sval = tolnk ?
135 			lstat(to.p_path, &sb) : stat(to.p_path, &sb);
136 		if (sval == -1) {
137 			warn("stat: %s", to.p_path);
138 			(void)close(from_fd);
139 			return (1);
140 		}
141 
142 		if (!(tolnk && S_ISLNK(sb.st_mode)))
143 			to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
144 	} else
145 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
146 		    fs->st_mode & ~(S_ISUID | S_ISGID));
147 
148 	if (to_fd == -1 && (fflag || tolnk)) {
149 		/*
150 		 * attempt to remove existing destination file name and
151 		 * create a new file
152 		 */
153 		(void)unlink(to.p_path);
154 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
155 			     fs->st_mode & ~(S_ISUID | S_ISGID));
156 	}
157 
158 	if (to_fd == -1) {
159 		warn("%s", to.p_path);
160 		(void)close(from_fd);
161 		return (1);
162 	}
163 
164 	rval = 0;
165 
166 	/* if hard linking then simply close the open fds, link and return */
167 	if (lflag) {
168 		(void)close(from_fd);
169 		(void)close(to_fd);
170 		(void)unlink(to.p_path);
171 		if (link(entp->fts_path, to.p_path)) {
172 			warn("%s", to.p_path);
173 			return (1);
174 		}
175 		return (0);
176 	}
177 
178 	/*
179 	 * There's no reason to do anything other than close the file
180 	 * now if it's empty, so let's not bother.
181 	 */
182 	if (fs->st_size > 0) {
183 		struct finfo fi;
184 
185 		fi.from = entp->fts_path;
186 		fi.to = to.p_path;
187 		fi.size = (size_t)fs->st_size;
188 
189 		/*
190 		 * Mmap and write if less than 8M (the limit is so
191 		 * we don't totally trash memory on big files).
192 		 * This is really a minor hack, but it wins some CPU back.
193 		 */
194 		bool use_read;
195 
196 		use_read = true;
197 		if (fs->st_size <= MMAP_MAX_SIZE) {
198 			size_t fsize = (size_t)fs->st_size;
199 			p = mmap(NULL, fsize, PROT_READ, MAP_FILE|MAP_SHARED,
200 			    from_fd, (off_t)0);
201 			if (p != MAP_FAILED) {
202 				size_t remainder;
203 
204 				use_read = false;
205 
206 				(void) madvise(p, (size_t)fs->st_size,
207 				     MADV_SEQUENTIAL);
208 
209 				/*
210 				 * Write out the data in small chunks to
211 				 * avoid locking the output file for a
212 				 * long time if the reading the data from
213 				 * the source is slow.
214 				 */
215 				remainder = fsize;
216 				do {
217 					ssize_t chunk;
218 
219 					chunk = (remainder > MMAP_MAX_WRITE) ?
220 					    MMAP_MAX_WRITE : remainder;
221 					if (write(to_fd, &p[fsize - remainder],
222 					    chunk) != chunk) {
223 						warn("%s", to.p_path);
224 						rval = 1;
225 						break;
226 					}
227 					remainder -= chunk;
228 					ptotal += chunk;
229 					if (pinfo)
230 						progress(&fi, ptotal);
231 				} while (remainder > 0);
232 
233 				if (munmap(p, fsize) < 0) {
234 					warn("%s", entp->fts_path);
235 					rval = 1;
236 				}
237 			}
238 		}
239 
240 		if (use_read) {
241 			while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
242 				wcount = write(to_fd, buf, (size_t)rcount);
243 				if (rcount != wcount || wcount == -1) {
244 					warn("%s", to.p_path);
245 					rval = 1;
246 					break;
247 				}
248 				ptotal += wcount;
249 				if (pinfo)
250 					progress(&fi, ptotal);
251 			}
252 			if (rcount < 0) {
253 				warn("%s", entp->fts_path);
254 				rval = 1;
255 			}
256 		}
257 	}
258 
259 	if (pflag && (fcpxattr(from_fd, to_fd) != 0))
260 		warn("%s: error copying extended attributes", to.p_path);
261 
262 	(void)close(from_fd);
263 
264 	if (rval == 1) {
265 		(void)close(to_fd);
266 		return (1);
267 	}
268 
269 	if (pflag && setfile(fs, to_fd))
270 		rval = 1;
271 	/*
272 	 * If the source was setuid or setgid, lose the bits unless the
273 	 * copy is owned by the same user and group.
274 	 */
275 #define	RETAINBITS \
276 	(S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
277 	if (!pflag && dne
278 	    && fs->st_mode & (S_ISUID | S_ISGID) && fs->st_uid == myuid) {
279 		if (fstat(to_fd, &to_stat)) {
280 			warn("%s", to.p_path);
281 			rval = 1;
282 		} else if (fs->st_gid == to_stat.st_gid &&
283 		    fchmod(to_fd, fs->st_mode & RETAINBITS & ~myumask)) {
284 			warn("%s", to.p_path);
285 			rval = 1;
286 		}
287 	}
288 	if (close(to_fd)) {
289 		warn("%s", to.p_path);
290 		rval = 1;
291 	}
292 	/* set the mod/access times now after close of the fd */
293 	if (pflag && set_utimes(to.p_path, fs)) {
294 	    rval = 1;
295 	}
296 	return (rval);
297 }
298 
299 int
300 copy_link(FTSENT *p, int exists)
301 {
302 	int len;
303 	char target[MAXPATHLEN];
304 
305 	if ((len = readlink(p->fts_path, target, sizeof(target)-1)) == -1) {
306 		warn("readlink: %s", p->fts_path);
307 		return (1);
308 	}
309 	target[len] = '\0';
310 	if (exists && unlink(to.p_path)) {
311 		warn("unlink: %s", to.p_path);
312 		return (1);
313 	}
314 	if (symlink(target, to.p_path)) {
315 		warn("symlink: %s", target);
316 		return (1);
317 	}
318 	return (pflag ? setfile(p->fts_statp, 0) : 0);
319 }
320 
321 int
322 copy_fifo(struct stat *from_stat, int exists)
323 {
324 	if (exists && unlink(to.p_path)) {
325 		warn("unlink: %s", to.p_path);
326 		return (1);
327 	}
328 	if (mkfifo(to.p_path, from_stat->st_mode)) {
329 		warn("mkfifo: %s", to.p_path);
330 		return (1);
331 	}
332 	return (pflag ? setfile(from_stat, 0) : 0);
333 }
334 
335 int
336 copy_special(struct stat *from_stat, int exists)
337 {
338 	if (exists && unlink(to.p_path)) {
339 		warn("unlink: %s", to.p_path);
340 		return (1);
341 	}
342 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
343 		warn("mknod: %s", to.p_path);
344 		return (1);
345 	}
346 	return (pflag ? setfile(from_stat, 0) : 0);
347 }
348 
349 
350 /*
351  * Function: setfile
352  *
353  * Purpose:
354  *   Set the owner/group/permissions for the "to" file to the information
355  *   in the stat structure.  If fd is zero, also call set_utimes() to set
356  *   the mod/access times.  If fd is non-zero, the caller must do a utimes
357  *   itself after close(fd).
358  */
359 int
360 setfile(struct stat *fs, int fd)
361 {
362 	int rval, islink;
363 
364 	rval = 0;
365 	islink = S_ISLNK(fs->st_mode);
366 	fs->st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
367 
368 	/*
369 	 * Changing the ownership probably won't succeed, unless we're root
370 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
371 	 * the mode; current BSD behavior is to remove all setuid bits on
372 	 * chown.  If chown fails, lose setuid/setgid bits.
373 	 */
374 	if (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
375 	    lchown(to.p_path, fs->st_uid, fs->st_gid)) {
376 		if (errno != EPERM) {
377 			warn("chown: %s", to.p_path);
378 			rval = 1;
379 		}
380 		fs->st_mode &= ~(S_ISUID | S_ISGID);
381 	}
382 	if (fd ? fchmod(fd, fs->st_mode) : lchmod(to.p_path, fs->st_mode)) {
383 		warn("chmod: %s", to.p_path);
384 		rval = 1;
385 	}
386 
387 	if (!islink && !Nflag) {
388 		unsigned long fflags = fs->st_flags;
389 		/*
390 		 * XXX
391 		 * NFS doesn't support chflags; ignore errors unless
392 		 * there's reason to believe we're losing bits.
393 		 * (Note, this still won't be right if the server
394 		 * supports flags and we were trying to *remove* flags
395 		 * on a file that we copied, i.e., that we didn't create.)
396 		 */
397 		errno = 0;
398 		if ((fd ? fchflags(fd, fflags) :
399 		    chflags(to.p_path, fflags)) == -1)
400 			if (errno != EOPNOTSUPP || fs->st_flags != 0) {
401 				warn("chflags: %s", to.p_path);
402 				rval = 1;
403 			}
404 	}
405 	/* if fd is non-zero, caller must call set_utimes() after close() */
406 	if (fd == 0 && set_utimes(to.p_path, fs))
407 	    rval = 1;
408 	return (rval);
409 }
410 
411 void
412 usage(void)
413 {
414 	(void)fprintf(stderr,
415 	    "usage: %s [-R [-H | -L | -P]] [-f | -i] [-alNpv] src target\n"
416 	    "       %s [-R [-H | -L | -P]] [-f | -i] [-alNpv] src1 ... srcN directory\n",
417 	    getprogname(), getprogname());
418 	exit(1);
419 	/* NOTREACHED */
420 }
421