xref: /netbsd-src/bin/cp/utils.c (revision 4817a0b0b8fe9612e8ebe21a9bf2d97b95038a97)
1 /* $NetBSD: utils.c,v 1.37 2010/12/21 20:56:01 christos 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.37 2010/12/21 20:56:01 christos 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 
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <fts.h>
50 #include <stdbool.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 
56 #include "extern.h"
57 
58 #define	MMAP_MAX_SIZE	(8 * 1048576)
59 #define	MMAP_MAX_WRITE	(64 * 1024)
60 
61 int
62 set_utimes(const char *file, struct stat *fs)
63 {
64     static struct timeval tv[2];
65 
66     TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
67     TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
68 
69     if (lutimes(file, tv)) {
70 	warn("lutimes: %s", file);
71 	return (1);
72     }
73     return (0);
74 }
75 
76 int
77 copy_file(FTSENT *entp, int dne)
78 {
79 	static char buf[MAXBSIZE];
80 	struct stat to_stat, *fs;
81 	int ch, checkch, from_fd, rcount, rval, to_fd, tolnk, wcount;
82 	char *p;
83 
84 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
85 		warn("%s", entp->fts_path);
86 		return (1);
87 	}
88 
89 	to_fd = -1;
90 	fs = entp->fts_statp;
91 	tolnk = ((Rflag && !(Lflag || Hflag)) || Pflag);
92 
93 	/*
94 	 * If the file exists and we're interactive, verify with the user.
95 	 * If the file DNE, set the mode to be the from file, minus setuid
96 	 * bits, modified by the umask; arguably wrong, but it makes copying
97 	 * executables work right and it's been that way forever.  (The
98 	 * other choice is 666 or'ed with the execute bits on the from file
99 	 * modified by the umask.)
100 	 */
101 	if (!dne) {
102 		struct stat sb;
103 		int sval;
104 
105 		if (iflag) {
106 			(void)fprintf(stderr, "overwrite %s? ", to.p_path);
107 			checkch = ch = getchar();
108 			while (ch != '\n' && ch != EOF)
109 				ch = getchar();
110 			if (checkch != 'y' && checkch != 'Y') {
111 				(void)close(from_fd);
112 				return (0);
113 			}
114 		}
115 
116 		sval = tolnk ?
117 			lstat(to.p_path, &sb) : stat(to.p_path, &sb);
118 		if (sval == -1) {
119 			warn("stat: %s", to.p_path);
120 			return (1);
121 		}
122 
123 		if (!(tolnk && S_ISLNK(sb.st_mode)))
124 			to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
125 	} else
126 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
127 		    fs->st_mode & ~(S_ISUID | S_ISGID));
128 
129 	if (to_fd == -1 && (fflag || tolnk)) {
130 		/*
131 		 * attempt to remove existing destination file name and
132 		 * create a new file
133 		 */
134 		(void)unlink(to.p_path);
135 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
136 			     fs->st_mode & ~(S_ISUID | S_ISGID));
137 	}
138 
139 	if (to_fd == -1) {
140 		warn("%s", to.p_path);
141 		(void)close(from_fd);
142 		return (1);
143 	}
144 
145 	rval = 0;
146 
147 	/*
148 	 * There's no reason to do anything other than close the file
149 	 * now if it's empty, so let's not bother.
150 	 */
151 
152 	if (fs->st_size > 0) {
153 		/*
154 		 * Mmap and write if less than 8M (the limit is so
155 		 * we don't totally trash memory on big files).
156 		 * This is really a minor hack, but it wins some CPU back.
157 		 */
158 		bool use_read;
159 
160 		use_read = true;
161 		if (fs->st_size <= MMAP_MAX_SIZE) {
162 			size_t fsize = (size_t)fs->st_size;
163 			p = mmap(NULL, fsize, PROT_READ, MAP_FILE|MAP_SHARED,
164 			    from_fd, (off_t)0);
165 			if (p != MAP_FAILED) {
166 				size_t remainder;
167 
168 				use_read = false;
169 
170 				(void) madvise(p, (size_t)fs->st_size,
171 				     MADV_SEQUENTIAL);
172 
173 				/*
174 				 * Write out the data in small chunks to
175 				 * avoid locking the output file for a
176 				 * long time if the reading the data from
177 				 * the source is slow.
178 				 */
179 				remainder = fsize;
180 				do {
181 					ssize_t chunk;
182 
183 					chunk = (remainder > MMAP_MAX_WRITE) ?
184 					    MMAP_MAX_WRITE : remainder;
185 					if (write(to_fd, &p[fsize - remainder],
186 					    chunk) != chunk) {
187 						warn("%s", to.p_path);
188 						rval = 1;
189 						break;
190 					}
191 					remainder -= chunk;
192 				} while (remainder > 0);
193 
194 				if (munmap(p, fsize) < 0) {
195 					warn("%s", entp->fts_path);
196 					rval = 1;
197 				}
198 			}
199 		}
200 
201 		if (use_read) {
202 			while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
203 				wcount = write(to_fd, buf, (size_t)rcount);
204 				if (rcount != wcount || wcount == -1) {
205 					warn("%s", to.p_path);
206 					rval = 1;
207 					break;
208 				}
209 			}
210 			if (rcount < 0) {
211 				warn("%s", entp->fts_path);
212 				rval = 1;
213 			}
214 		}
215 	}
216 
217 	if (rval == 1) {
218 		(void)close(from_fd);
219 		(void)close(to_fd);
220 		return (1);
221 	}
222 
223 	if (pflag && setfile(fs, to_fd))
224 		rval = 1;
225 	/*
226 	 * If the source was setuid or setgid, lose the bits unless the
227 	 * copy is owned by the same user and group.
228 	 */
229 #define	RETAINBITS \
230 	(S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
231 	if (!pflag && dne
232 	    && fs->st_mode & (S_ISUID | S_ISGID) && fs->st_uid == myuid) {
233 		if (fstat(to_fd, &to_stat)) {
234 			warn("%s", to.p_path);
235 			rval = 1;
236 		} else if (fs->st_gid == to_stat.st_gid &&
237 		    fchmod(to_fd, fs->st_mode & RETAINBITS & ~myumask)) {
238 			warn("%s", to.p_path);
239 			rval = 1;
240 		}
241 	}
242 	(void)close(from_fd);
243 	if (close(to_fd)) {
244 		warn("%s", to.p_path);
245 		rval = 1;
246 	}
247 	/* set the mod/access times now after close of the fd */
248 	if (pflag && set_utimes(to.p_path, fs)) {
249 	    rval = 1;
250 	}
251 	return (rval);
252 }
253 
254 int
255 copy_link(FTSENT *p, int exists)
256 {
257 	int len;
258 	char target[MAXPATHLEN];
259 
260 	if ((len = readlink(p->fts_path, target, sizeof(target)-1)) == -1) {
261 		warn("readlink: %s", p->fts_path);
262 		return (1);
263 	}
264 	target[len] = '\0';
265 	if (exists && unlink(to.p_path)) {
266 		warn("unlink: %s", to.p_path);
267 		return (1);
268 	}
269 	if (symlink(target, to.p_path)) {
270 		warn("symlink: %s", target);
271 		return (1);
272 	}
273 	return (pflag ? setfile(p->fts_statp, 0) : 0);
274 }
275 
276 int
277 copy_fifo(struct stat *from_stat, int exists)
278 {
279 	if (exists && unlink(to.p_path)) {
280 		warn("unlink: %s", to.p_path);
281 		return (1);
282 	}
283 	if (mkfifo(to.p_path, from_stat->st_mode)) {
284 		warn("mkfifo: %s", to.p_path);
285 		return (1);
286 	}
287 	return (pflag ? setfile(from_stat, 0) : 0);
288 }
289 
290 int
291 copy_special(struct stat *from_stat, int exists)
292 {
293 	if (exists && unlink(to.p_path)) {
294 		warn("unlink: %s", to.p_path);
295 		return (1);
296 	}
297 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
298 		warn("mknod: %s", to.p_path);
299 		return (1);
300 	}
301 	return (pflag ? setfile(from_stat, 0) : 0);
302 }
303 
304 
305 /*
306  * Function: setfile
307  *
308  * Purpose:
309  *   Set the owner/group/permissions for the "to" file to the information
310  *   in the stat structure.  If fd is zero, also call set_utimes() to set
311  *   the mod/access times.  If fd is non-zero, the caller must do a utimes
312  *   itself after close(fd).
313  */
314 int
315 setfile(struct stat *fs, int fd)
316 {
317 	int rval, islink;
318 
319 	rval = 0;
320 	islink = S_ISLNK(fs->st_mode);
321 	fs->st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
322 
323 	/*
324 	 * Changing the ownership probably won't succeed, unless we're root
325 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
326 	 * the mode; current BSD behavior is to remove all setuid bits on
327 	 * chown.  If chown fails, lose setuid/setgid bits.
328 	 */
329 	if (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
330 	    lchown(to.p_path, fs->st_uid, fs->st_gid)) {
331 		if (errno != EPERM) {
332 			warn("chown: %s", to.p_path);
333 			rval = 1;
334 		}
335 		fs->st_mode &= ~(S_ISUID | S_ISGID);
336 	}
337 	if (fd ? fchmod(fd, fs->st_mode) : lchmod(to.p_path, fs->st_mode)) {
338 		warn("chmod: %s", to.p_path);
339 		rval = 1;
340 	}
341 
342 	if (!islink && !Nflag) {
343 		unsigned long fflags = fs->st_flags;
344 		/*
345 		 * XXX
346 		 * NFS doesn't support chflags; ignore errors unless
347 		 * there's reason to believe we're losing bits.
348 		 * (Note, this still won't be right if the server
349 		 * supports flags and we were trying to *remove* flags
350 		 * on a file that we copied, i.e., that we didn't create.)
351 		 */
352 		errno = 0;
353 		if ((fd ? fchflags(fd, fflags) :
354 		    chflags(to.p_path, fflags)) == -1)
355 			if (errno != EOPNOTSUPP || fs->st_flags != 0) {
356 				warn("chflags: %s", to.p_path);
357 				rval = 1;
358 			}
359 	}
360 	/* if fd is non-zero, caller must call set_utimes() after close() */
361 	if (fd == 0 && set_utimes(to.p_path, fs))
362 	    rval = 1;
363 	return (rval);
364 }
365 
366 void
367 usage(void)
368 {
369 	(void)fprintf(stderr,
370 	    "usage: %s [-R [-H | -L | -P]] [-f | -i] [-aNpv] src target\n"
371 	    "       %s [-R [-H | -L | -P]] [-f | -i] [-aNpv] src1 ... srcN directory\n",
372 	    getprogname(), getprogname());
373 	exit(1);
374 	/* NOTREACHED */
375 }
376