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