xref: /freebsd/bin/cp/utils.c (revision 33b77e2decd50e53798014b70bf7ca3bdc4c0c7e)
1 /*-
2  * Copyright (c) 1991, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	$Id: utils.c,v 1.14 1997/10/03 18:11:14 wosch Exp $
34  */
35 
36 #ifndef lint
37 static char const sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
38 #endif /* not lint */
39 
40 #include <sys/param.h>
41 #include <sys/stat.h>
42 #include <sys/mman.h>
43 #include <sys/time.h>
44 
45 #include <err.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <fts.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 
54 #include "extern.h"
55 
56 int
57 copy_file(entp, dne)
58 	FTSENT *entp;
59 	int dne;
60 {
61 	static char buf[MAXBSIZE];
62 	struct stat to_stat, *fs;
63 	int ch, checkch, from_fd, rcount, rval, to_fd, wcount, wresid;
64 	char *bufp;
65 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
66 	char *p;
67 #endif
68 
69 	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
70 		warn("%s", entp->fts_path);
71 		return (1);
72 	}
73 
74 	fs = entp->fts_statp;
75 
76 	/*
77 	 * If the file exists and we're interactive, verify with the user.
78 	 * If the file DNE, set the mode to be the from file, minus setuid
79 	 * bits, modified by the umask; arguably wrong, but it makes copying
80 	 * executables work right and it's been that way forever.  (The
81 	 * other choice is 666 or'ed with the execute bits on the from file
82 	 * modified by the umask.)
83 	 */
84 	if (!dne) {
85 #define YESNO "(y/n [n]) "
86 		if (iflag) {
87 			(void)fprintf(stderr, "overwrite %s? %s",
88 					to.p_path, YESNO);
89 			checkch = ch = getchar();
90 			while (ch != '\n' && ch != EOF)
91 				ch = getchar();
92 			if (checkch != 'y' && checkch != 'Y') {
93 				(void)close(from_fd);
94 				(void)fprintf(stderr, "not overwritten\n");
95 				return (0);
96 			}
97 		}
98 
99 		if (fflag) {
100 		    /* remove existing destination file name,
101 		     * create a new file  */
102 		    (void)unlink(to.p_path);
103 		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
104 				 fs->st_mode & ~(S_ISUID | S_ISGID));
105 		} else
106 		    /* overwrite existing destination file name */
107 		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
108 	} else
109 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
110 		    fs->st_mode & ~(S_ISUID | S_ISGID));
111 
112 	if (to_fd == -1) {
113 		warn("%s", to.p_path);
114 		(void)close(from_fd);
115 		return (1);;
116 	}
117 
118 	rval = 0;
119 
120 	/*
121 	 * Mmap and write if less than 8M (the limit is so we don't totally
122 	 * trash memory on big files.  This is really a minor hack, but it
123 	 * wins some CPU back.
124 	 */
125 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
126 	if (fs->st_size <= 8 * 1048576) {
127 		if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
128 		    MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
129 			warn("%s", entp->fts_path);
130 			rval = 1;
131 		} else {
132 			for (bufp = p, wresid = fs->st_size; ;
133 			    bufp += wcount, wresid -= wcount)
134 				wcount = write(to_fd, bufp, wresid);
135 				if (wcount >= wresid || wcount <= 0)
136 					break;
137 			}
138 			if (wcount != wresid) {
139 				warn("%s", to.p_path);
140 				rval = 1;
141 			}
142 			/* Some systems don't unmap on close(2). */
143 			if (munmap(p, fs->st_size) < 0) {
144 				warn("%s", entp->fts_path);
145 				rval = 1;
146 			}
147 		}
148 	} else
149 #endif
150 	{
151 		while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
152 			for (bufp = buf, wresid = rcount; ;
153 			    bufp += wcount, wresid -= wcount) {
154 				wcount = write(to_fd, bufp, wresid);
155 				if (wcount >= wresid || wcount <= 0)
156 					break;
157 			}
158 			if (wcount != wresid) {
159 				warn("%s", to.p_path);
160 				rval = 1;
161 				break;
162 			}
163 		}
164 		if (rcount < 0) {
165 			warn("%s", entp->fts_path);
166 			rval = 1;
167 		}
168 	}
169 
170 	/*
171 	 * Don't remove the target even after an error.  The target might
172 	 * not be a regular file, or its attributes might be important,
173 	 * or its contents might be irreplacable.  It would only be safe
174 	 * to remove it if we created it and its length is 0.
175 	 */
176 
177 	if (pflag && setfile(fs, to_fd))
178 		rval = 1;
179 	/*
180 	 * If the source was setuid or setgid, lose the bits unless the
181 	 * copy is owned by the same user and group.
182 	 */
183 #define	RETAINBITS \
184 	(S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
185 	else if (fs->st_mode & (S_ISUID | S_ISGID) && fs->st_uid == myuid)
186 		if (fstat(to_fd, &to_stat)) {
187 			warn("%s", to.p_path);
188 			rval = 1;
189 		} else if (fs->st_gid == to_stat.st_gid &&
190 		    fchmod(to_fd, fs->st_mode & RETAINBITS & ~myumask)) {
191 			warn("%s", to.p_path);
192 			rval = 1;
193 		}
194 	(void)close(from_fd);
195 	if (close(to_fd)) {
196 		warn("%s", to.p_path);
197 		rval = 1;
198 	}
199 	return (rval);
200 }
201 
202 int
203 copy_link(p, exists)
204 	FTSENT *p;
205 	int exists;
206 {
207 	int len;
208 	char link[MAXPATHLEN];
209 
210 	if ((len = readlink(p->fts_path, link, sizeof(link))) == -1) {
211 		warn("readlink: %s", p->fts_path);
212 		return (1);
213 	}
214 	link[len] = '\0';
215 	if (exists && unlink(to.p_path)) {
216 		warn("unlink: %s", to.p_path);
217 		return (1);
218 	}
219 	if (symlink(link, to.p_path)) {
220 		warn("symlink: %s", link);
221 		return (1);
222 	}
223 	return (0);
224 }
225 
226 int
227 copy_fifo(from_stat, exists)
228 	struct stat *from_stat;
229 	int exists;
230 {
231 	if (exists && unlink(to.p_path)) {
232 		warn("unlink: %s", to.p_path);
233 		return (1);
234 	}
235 	if (mkfifo(to.p_path, from_stat->st_mode)) {
236 		warn("mkfifo: %s", to.p_path);
237 		return (1);
238 	}
239 	return (pflag ? setfile(from_stat, 0) : 0);
240 }
241 
242 int
243 copy_special(from_stat, exists)
244 	struct stat *from_stat;
245 	int exists;
246 {
247 	if (exists && unlink(to.p_path)) {
248 		warn("unlink: %s", to.p_path);
249 		return (1);
250 	}
251 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
252 		warn("mknod: %s", to.p_path);
253 		return (1);
254 	}
255 	return (pflag ? setfile(from_stat, 0) : 0);
256 }
257 
258 
259 int
260 setfile(fs, fd)
261 	register struct stat *fs;
262 	int fd;
263 {
264 	static struct timeval tv[2];
265 	int rval;
266 
267 	rval = 0;
268 	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
269 		       S_IRWXU | S_IRWXG | S_IRWXO;
270 
271 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
272 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
273 	if (utimes(to.p_path, tv)) {
274 		warn("utimes: %s", to.p_path);
275 		rval = 1;
276 	}
277 	/*
278 	 * Changing the ownership probably won't succeed, unless we're root
279 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
280 	 * the mode; current BSD behavior is to remove all setuid bits on
281 	 * chown.  If chown fails, lose setuid/setgid bits.
282 	 */
283 	if (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
284 	    chown(to.p_path, fs->st_uid, fs->st_gid)) {
285 		if (errno != EPERM) {
286 			warn("chown: %s", to.p_path);
287 			rval = 1;
288 		}
289 		fs->st_mode &= ~(S_ISUID | S_ISGID);
290 	}
291 	if (fd ? fchmod(fd, fs->st_mode) : chmod(to.p_path, fs->st_mode)) {
292 		warn("chown: %s", to.p_path);
293 		rval = 1;
294 	}
295 
296 	if (fd ?
297 	    fchflags(fd, fs->st_flags) : chflags(to.p_path, fs->st_flags)) {
298 		warn("chflags: %s", to.p_path);
299 		rval = 1;
300 	}
301 	return (rval);
302 }
303 
304 void
305 usage()
306 {
307 	(void)fprintf(stderr, "%s\n%s\n",
308 "usage: cp [-R [-H | -L | -P]] [-f | -i] [-p] src target",
309 "       cp [-R [-H | -L | -P]] [-f | -i] [-p] src1 ... srcN directory");
310 	exit(1);
311 }
312