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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #ifndef lint
31 #if 0
32 static char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD: src/bin/cp/utils.c,v 1.43 2004/04/06 20:06:44 markm Exp $");
35 #endif
36 #endif /* not lint */
37 
38 #define MSC_DO_64_BIT_IO
39 #include "config.h"
40 #ifndef _MSC_VER
41 # include <sys/param.h>
42 #endif
43 #include <sys/stat.h>
44 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
45 # include <sys/mman.h>
46 #endif
47 
48 #include "err.h"
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <fts.h>
52 #include <limits.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <signal.h>
56 #ifndef __HAIKU__
57 # include <sysexits.h>
58 #endif
59 #include <unistd.h>
60 #ifdef __sun__
61 # include "solfakes.h"
62 #endif
63 #ifdef __HAIKU__
64 # include "haikufakes.h"
65 #endif
66 #ifdef _MSC_VER
67 # include "mscfakes.h"
68 #else
69 # include <sys/time.h>
70 #endif
71 #include "cp_extern.h"
72 #include "cmp_extern.h"
73 
74 #define	cp_pct(x,y)	(int)(100.0 * (double)(x) / (double)(y))
75 
76 #ifndef MAXBSIZE
77 # define MAXBSIZE 0x20000
78 #endif
79 #ifndef O_BINARY
80 # define O_BINARY 0
81 #endif
82 
83 #ifndef S_ISVTX
84 # define S_ISVTX 0
85 #endif
86 
87 
88 int
copy_file(const FTSENT * entp,int dne,int changed_only,int * pcopied)89 copy_file(const FTSENT *entp, int dne, int changed_only, int *pcopied)
90 {
91 	static char buf[MAXBSIZE];
92 	struct stat *fs;
93 	int ch, checkch, from_fd, rcount, rval, to_fd;
94 	ssize_t wcount;
95 	size_t wresid;
96 	size_t wtotal;
97 	char *bufp;
98 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
99 	char *p;
100 #endif
101 
102 	*pcopied = 0;
103 
104 	if ((from_fd = open(entp->fts_path, O_RDONLY | O_BINARY, 0)) == -1) {
105 		warn("open: %s", entp->fts_path);
106 		return (1);
107 	}
108 
109 	fs = entp->fts_statp;
110 
111 	/*
112 	 * If the file exists and we're interactive, verify with the user.
113 	 * If the file DNE, set the mode to be the from file, minus setuid
114 	 * bits, modified by the umask; arguably wrong, but it makes copying
115 	 * executables work right and it's been that way forever.  (The
116 	 * other choice is 666 or'ed with the execute bits on the from file
117 	 * modified by the umask.)
118 	 */
119 	if (!dne) {
120 		/* compare the files first if requested */
121 		if (changed_only) {
122                         if (cmp_fd_and_file(from_fd, entp->fts_path, to.p_path,
123 					    1 /* silent */, 0 /* lflag */,
124 					    0 /* special */) == OK_EXIT) {
125 				close(from_fd);
126 				return (0);
127 			}
128 			if (lseek(from_fd, 0, SEEK_SET) != 0) {
129     				close(from_fd);
130 				if ((from_fd = open(entp->fts_path, O_RDONLY | O_BINARY, 0)) == -1) {
131 					warn("open: %s", entp->fts_path);
132 					return (1);
133 				}
134 			}
135 		}
136 
137 #define YESNO "(y/n [n]) "
138 		if (nflag) {
139 			if (vflag)
140 				printf("%s not overwritten\n", to.p_path);
141 			return (0);
142 		} else if (iflag) {
143 			(void)fprintf(stderr, "overwrite %s? %s",
144 					to.p_path, YESNO);
145 			checkch = ch = getchar();
146 			while (ch != '\n' && ch != EOF)
147 				ch = getchar();
148 			if (checkch != 'y' && checkch != 'Y') {
149 				(void)close(from_fd);
150 				(void)fprintf(stderr, "not overwritten\n");
151 				return (1);
152 			}
153 		}
154 
155 		if (fflag) {
156 		    /* remove existing destination file name,
157 		     * create a new file  */
158 		    (void)unlink(to.p_path);
159 		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY,
160 				 fs->st_mode & ~(S_ISUID | S_ISGID));
161 		} else
162 		    /* overwrite existing destination file name */
163 		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_BINARY, 0);
164 	} else
165 		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY,
166 		    fs->st_mode & ~(S_ISUID | S_ISGID));
167 
168 	if (to_fd == -1) {
169 		warn("open: %s", to.p_path);
170 		(void)close(from_fd);
171 		return (1);
172 	}
173 
174 	rval = 0;
175 	*pcopied = 1;
176 
177 	/*
178 	 * Mmap and write if less than 8M (the limit is so we don't totally
179 	 * trash memory on big files.  This is really a minor hack, but it
180 	 * wins some CPU back.
181 	 */
182 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
183 	if (S_ISREG(fs->st_mode) && fs->st_size > 0 &&
184 	    fs->st_size <= 8 * 1048576) {
185 		if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
186 		    MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
187 			warn("mmap: %s", entp->fts_path);
188 			rval = 1;
189 		} else {
190 			wtotal = 0;
191 			for (bufp = p, wresid = fs->st_size; ;
192 			    bufp += wcount, wresid -= (size_t)wcount) {
193 				wcount = write(to_fd, bufp, wresid);
194 				wtotal += wcount;
195 				if (info) {
196 					info = 0;
197 					(void)fprintf(stderr,
198 						"%s -> %s %3d%%\n",
199 						entp->fts_path, to.p_path,
200 						cp_pct(wtotal, fs->st_size));
201 
202 				}
203 				if (wcount >= (ssize_t)wresid || wcount <= 0)
204 					break;
205 			}
206 			if (wcount != (ssize_t)wresid) {
207 				warn("write[%zd != %zu]: %s", wcount, wresid, to.p_path);
208 				rval = 1;
209 			}
210 			/* Some systems don't unmap on close(2). */
211 			if (munmap(p, fs->st_size) < 0) {
212 				warn("munmap: %s", entp->fts_path);
213 				rval = 1;
214 			}
215 		}
216 	} else
217 #endif
218 	{
219 		wtotal = 0;
220 		while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
221 			for (bufp = buf, wresid = rcount; ;
222 			    bufp += wcount, wresid -= wcount) {
223 				wcount = write(to_fd, bufp, wresid);
224 				wtotal += wcount;
225 				if (info) {
226 					info = 0;
227 					(void)fprintf(stderr,
228 						"%s -> %s %3d%%\n",
229 						entp->fts_path, to.p_path,
230 						cp_pct(wtotal, fs->st_size));
231 
232 				}
233 				if (wcount >= (ssize_t)wresid || wcount <= 0)
234 					break;
235 			}
236 			if (wcount != (ssize_t)wresid) {
237 				warn("write[%zd != %zu]: %s", wcount, wresid, to.p_path);
238 				rval = 1;
239 				break;
240 			}
241 		}
242 		if (rcount < 0) {
243 			warn("read: %s", entp->fts_path);
244 			rval = 1;
245 		}
246 	}
247 
248 	/*
249 	 * Don't remove the target even after an error.  The target might
250 	 * not be a regular file, or its attributes might be important,
251 	 * or its contents might be irreplaceable.  It would only be safe
252 	 * to remove it if we created it and its length is 0.
253 	 */
254 
255 	if (pflag && setfile(fs, to_fd))
256 		rval = 1;
257 	(void)close(from_fd);
258 	if (close(to_fd)) {
259 		warn("close: %s", to.p_path);
260 		rval = 1;
261 	}
262 	return (rval);
263 }
264 
265 int
copy_link(const FTSENT * p,int exists)266 copy_link(const FTSENT *p, int exists)
267 {
268 	int len;
269 	char llink[PATH_MAX];
270 
271 	if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
272 		warn("readlink: %s", p->fts_path);
273 		return (1);
274 	}
275 	llink[len] = '\0';
276 	if (exists && unlink(to.p_path)) {
277 		warn("unlink: %s", to.p_path);
278 		return (1);
279 	}
280 	if (symlink(llink, to.p_path)) {
281 		warn("symlink: %s", llink);
282 		return (1);
283 	}
284 	return (pflag ? setfile(p->fts_statp, -1) : 0);
285 }
286 
287 int
copy_fifo(struct stat * from_stat,int exists)288 copy_fifo(struct stat *from_stat, int exists)
289 {
290 	if (exists && unlink(to.p_path)) {
291 		warn("unlink: %s", to.p_path);
292 		return (1);
293 	}
294 	if (mkfifo(to.p_path, from_stat->st_mode)) {
295 		warn("mkfifo: %s", to.p_path);
296 		return (1);
297 	}
298 	return (pflag ? setfile(from_stat, -1) : 0);
299 }
300 
301 int
copy_special(struct stat * from_stat,int exists)302 copy_special(struct stat *from_stat, int exists)
303 {
304 	if (exists && unlink(to.p_path)) {
305 		warn("unlink: %s", to.p_path);
306 		return (1);
307 	}
308 	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
309 		warn("mknod: %s", to.p_path);
310 		return (1);
311 	}
312 	return (pflag ? setfile(from_stat, -1) : 0);
313 }
314 
315 int
setfile(struct stat * fs,int fd)316 setfile(struct stat *fs, int fd)
317 {
318 	static struct timeval tv[2];
319 	struct stat ts;
320 	int rval, gotstat, islink, fdval;
321 
322 	rval = 0;
323 	fdval = fd != -1;
324 	islink = !fdval && S_ISLNK(fs->st_mode);
325 	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
326 		       S_IRWXU | S_IRWXG | S_IRWXO;
327 
328 #ifdef HAVE_ST_TIMESPEC
329 	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
330 	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
331 #else
332         tv[0].tv_sec = fs->st_atime;
333         tv[1].tv_sec = fs->st_mtime;
334         tv[0].tv_usec = tv[1].tv_usec = 0;
335 #endif
336 	if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
337 		warn("%sutimes: %s", islink ? "l" : "", to.p_path);
338 		rval = 1;
339 	}
340 	if (fdval ? fstat(fd, &ts) :
341 	    (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
342 		gotstat = 0;
343 	else {
344 		gotstat = 1;
345 		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
346 			      S_IRWXU | S_IRWXG | S_IRWXO;
347 	}
348 	/*
349 	 * Changing the ownership probably won't succeed, unless we're root
350 	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
351 	 * the mode; current BSD behavior is to remove all setuid bits on
352 	 * chown.  If chown fails, lose setuid/setgid bits.
353 	 */
354 	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
355 		if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
356 		    (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
357 		    chown(to.p_path, fs->st_uid, fs->st_gid))) {
358 			if (errno != EPERM) {
359 				warn("chown: %s", to.p_path);
360 				rval = 1;
361 			}
362 			fs->st_mode &= ~(S_ISUID | S_ISGID);
363 		}
364 
365 	if (!gotstat || fs->st_mode != ts.st_mode)
366 		if (fdval ? fchmod(fd, fs->st_mode) :
367 		    (islink ? lchmod(to.p_path, fs->st_mode) :
368 		    chmod(to.p_path, fs->st_mode))) {
369 			warn("chmod: %s", to.p_path);
370 			rval = 1;
371 		}
372 
373 #ifdef HAVE_ST_FLAGS
374 	if (!gotstat || fs->st_flags != ts.st_flags)
375 		if (fdval ?
376 		    fchflags(fd, fs->st_flags) :
377 		    (islink ? (errno = ENOSYS) :
378 		    chflags(to.p_path, fs->st_flags))) {
379 			warn("chflags: %s", to.p_path);
380 			rval = 1;
381 		}
382 #endif
383 
384 	return (rval);
385 }
386 
387