xref: /netbsd-src/bin/cp/utils.c (revision 481fca6e59249d8ffcf24fef7cfbe7b131bfb080)
1 /*	$NetBSD: utils.c,v 1.17 1999/03/01 18:57:29 mjl 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. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 #if 0
39 static char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
40 #else
41 __RCSID("$NetBSD: utils.c,v 1.17 1999/03/01 18:57:29 mjl Exp $");
42 #endif
43 #endif /* not lint */
44 
45 #include <sys/param.h>
46 #include <sys/stat.h>
47 #include <sys/mman.h>
48 #include <sys/time.h>
49 
50 #include <err.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <fts.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 
59 #include "extern.h"
60 
61 int
62 set_utimes(file, fs)
63 	const char * file;
64 	struct stat * fs;
65 {
66     static struct timeval tv[2];
67 
68     TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
69     TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
70 
71     if (lutimes(file, tv)) {
72 	warn("lutimes: %s", file);
73 	return (1);
74     }
75     return (0);
76 }
77 
78 int
79 copy_file(entp, dne)
80 	FTSENT *entp;
81 	int dne;
82 {
83 	static char buf[MAXBSIZE];
84 	struct stat to_stat, *fs;
85 	int ch, checkch, from_fd, rcount, rval, to_fd, wcount;
86 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
87 	char *p;
88 #endif
89 
90 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
91 		warn("%s", entp->fts_path);
92 		return (1);
93 	}
94 
95 	fs = entp->fts_statp;
96 
97 	/*
98 	 * If the file exists and we're interactive, verify with the user.
99 	 * If the file DNE, set the mode to be the from file, minus setuid
100 	 * bits, modified by the umask; arguably wrong, but it makes copying
101 	 * executables work right and it's been that way forever.  (The
102 	 * other choice is 666 or'ed with the execute bits on the from file
103 	 * modified by the umask.)
104 	 */
105 	if (!dne) {
106 		if (iflag) {
107 			(void)fprintf(stderr, "overwrite %s? ", to.p_path);
108 			checkch = ch = getchar();
109 			while (ch != '\n' && ch != EOF)
110 				ch = getchar();
111 			if (checkch != 'y' && checkch != 'Y') {
112 				(void)close(from_fd);
113 				return (0);
114 			}
115 		}
116 		/* overwrite existing destination file name */
117 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
118 	} else
119 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
120 		    fs->st_mode & ~(S_ISUID | S_ISGID));
121 
122 	if (to_fd == -1 && fflag) {
123 		/*
124 		 * attempt to remove existing destination file name and
125 		 * create a new file
126 		 */
127 		(void)unlink(to.p_path);
128 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
129 			     fs->st_mode & ~(S_ISUID | S_ISGID));
130 	}
131 
132 	if (to_fd == -1) {
133 		warn("%s", to.p_path);
134 		(void)close(from_fd);
135 		return (1);;
136 	}
137 
138 	rval = 0;
139 
140 	/*
141 	 * There's no reason to do anything other than close the file
142 	 * now if it's empty, so let's not bother.
143 	 */
144 	if (fs->st_size > 0) {
145 		/*
146 		 * Mmap and write if less than 8M (the limit is so we don't totally
147 		 * trash memory on big files).  This is really a minor hack, but it
148 		 * wins some CPU back.
149 		 */
150 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
151 		if (fs->st_size <= 8 * 1048576) {
152 			if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
153 			    MAP_FILE|MAP_SHARED, from_fd, (off_t)0)) == (char *)-1) {
154 				warn("%s", entp->fts_path);
155 				rval = 1;
156 			} else {
157 				if (write(to_fd, p, fs->st_size) != fs->st_size) {
158 					warn("%s", to.p_path);
159 					rval = 1;
160 				}
161 				/* Some systems don't unmap on close(2). */
162 				if (munmap(p, fs->st_size) < 0) {
163 					warn("%s", entp->fts_path);
164 					rval = 1;
165 				}
166 			}
167 		} else
168 #endif
169 		{
170 			while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
171 				wcount = write(to_fd, buf, rcount);
172 				if (rcount != wcount || wcount == -1) {
173 					warn("%s", to.p_path);
174 					rval = 1;
175 					break;
176 				}
177 			}
178 			if (rcount < 0) {
179 				warn("%s", entp->fts_path);
180 				rval = 1;
181 			}
182 		}
183 	}
184 
185 	if (rval == 1) {
186 		(void)close(from_fd);
187 		(void)close(to_fd);
188 		return (1);
189 	}
190 
191 	if (pflag && setfile(fs, to_fd))
192 		rval = 1;
193 	/*
194 	 * If the source was setuid or setgid, lose the bits unless the
195 	 * copy is owned by the same user and group.
196 	 */
197 #define	RETAINBITS \
198 	(S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
199 	else if (fs->st_mode & (S_ISUID | S_ISGID) && fs->st_uid == myuid) {
200 		if (fstat(to_fd, &to_stat)) {
201 			warn("%s", to.p_path);
202 			rval = 1;
203 		} else if (fs->st_gid == to_stat.st_gid &&
204 		    fchmod(to_fd, fs->st_mode & RETAINBITS & ~myumask)) {
205 			warn("%s", to.p_path);
206 			rval = 1;
207 		}
208 	}
209 	(void)close(from_fd);
210 	if (close(to_fd)) {
211 		warn("%s", to.p_path);
212 		rval = 1;
213 	}
214 	/* set the mod/access times now after close of the fd */
215 	if (pflag && set_utimes(to.p_path, fs)) {
216 	    rval = 1;
217 	}
218 	return (rval);
219 }
220 
221 int
222 copy_link(p, exists)
223 	FTSENT *p;
224 	int exists;
225 {
226 	int len;
227 	char target[MAXPATHLEN];
228 
229 	if ((len = readlink(p->fts_path, target, sizeof(target))) == -1) {
230 		warn("readlink: %s", p->fts_path);
231 		return (1);
232 	}
233 	target[len] = '\0';
234 	if (exists && unlink(to.p_path)) {
235 		warn("unlink: %s", to.p_path);
236 		return (1);
237 	}
238 	if (symlink(target, to.p_path)) {
239 		warn("symlink: %s", target);
240 		return (1);
241 	}
242 	return (pflag ? setfile(p->fts_statp, 0) : 0);
243 }
244 
245 int
246 copy_fifo(from_stat, exists)
247 	struct stat *from_stat;
248 	int exists;
249 {
250 	if (exists && unlink(to.p_path)) {
251 		warn("unlink: %s", to.p_path);
252 		return (1);
253 	}
254 	if (mkfifo(to.p_path, from_stat->st_mode)) {
255 		warn("mkfifo: %s", to.p_path);
256 		return (1);
257 	}
258 	return (pflag ? setfile(from_stat, 0) : 0);
259 }
260 
261 int
262 copy_special(from_stat, exists)
263 	struct stat *from_stat;
264 	int exists;
265 {
266 	if (exists && unlink(to.p_path)) {
267 		warn("unlink: %s", to.p_path);
268 		return (1);
269 	}
270 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
271 		warn("mknod: %s", to.p_path);
272 		return (1);
273 	}
274 	return (pflag ? setfile(from_stat, 0) : 0);
275 }
276 
277 
278 /*
279  * Function: setfile
280  *
281  * Purpose:
282  *   Set the owner/group/permissions for the "to" file to the information
283  *   in the stat structure.  If fd is zero, also call set_utimes() to set
284  *   the mod/access times.  If fd is non-zero, the caller must do a utimes
285  *   itself after close(fd).
286  */
287 int
288 setfile(fs, fd)
289 	struct stat *fs;
290 	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) {
318 		/*
319 		 * XXX
320 		 * NFS doesn't support chflags; ignore errors unless
321 		 * there's reason to believe we're losing bits.
322 		 * (Note, this still won't be right if the server
323 		 * supports flags and we were trying to *remove* flags
324 		 * on a file that we copied, i.e., that we didn't create.)
325 		 */
326 		errno = 0;
327 		if (fd ? fchflags(fd, fs->st_flags) :
328 		    chflags(to.p_path, fs->st_flags))
329 			if (errno != EOPNOTSUPP || fs->st_flags != 0) {
330 				warn("chflags: %s", to.p_path);
331 				rval = 1;
332 			}
333 	}
334 	/* if fd is non-zero, caller must call set_utimes() after close() */
335 	if (fd == 0 && set_utimes(to.p_path, fs))
336 	    rval = 1;
337 	return (rval);
338 }
339 
340 void
341 usage()
342 {
343 	(void)fprintf(stderr, "%s\n%s\n",
344 	    "usage: cp [-R [-H | -L | -P]] [-f | -i] [-p] src target",
345 	    "       cp [-R [-H | -L | -P]] [-f | -i] [-p] src1 ... srcN directory");
346 	exit(1);
347 	/* NOTREACHED */
348 }
349