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