utils.c revision 116673
1155240Simp/*-
2155240Simp * Copyright (c) 1991, 1993, 1994
3155240Simp *	The Regents of the University of California.  All rights reserved.
4155240Simp *
5155240Simp * Redistribution and use in source and binary forms, with or without
6155240Simp * modification, are permitted provided that the following conditions
730638Speter * are met:
8155240Simp * 1. Redistributions of source code must retain the above copyright
9155240Simp *    notice, this list of conditions and the following disclaimer.
10155240Simp * 2. Redistributions in binary form must reproduce the above copyright
11155240Simp *    notice, this list of conditions and the following disclaimer in the
12155240Simp *    documentation and/or other materials provided with the distribution.
1330638Speter * 3. All advertising materials mentioning features or use of this software
14152162Speter *    must display the following acknowledgement:
15152162Speter *	This product includes software developed by the University of
1630638Speter *	California, Berkeley and its contributors.
17152162Speter * 4. Neither the name of the University nor the names of its contributors
18152164Srwatson *    may be used to endorse or promote products derived from this software
19152162Speter *    without specific prior written permission.
20152162Speter *
21152162Speter * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22152162Speter * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23152162Speter * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24152162Speter * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25152162Speter * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26152162Speter * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27152162Speter * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28152162Speter * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29215034Sbrucec * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30152162Speter * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31152162Speter * SUCH DAMAGE.
32155240Simp */
33152162Speter
34155240Simp#ifndef lint
35155240Simp#if 0
36152162Speterstatic char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
37155240Simp#endif
38155240Simp#endif /* not lint */
39155240Simp#include <sys/cdefs.h>
40155240Simp__FBSDID("$FreeBSD: head/bin/cp/utils.c 116673 2003-06-22 07:02:17Z jmg $");
41155240Simp
42155240Simp#include <sys/param.h>
43155240Simp#include <sys/stat.h>
44155240Simp#ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
45155240Simp#include <sys/mman.h>
46155240Simp#endif
47155240Simp
48155240Simp#include <err.h>
49155240Simp#include <errno.h>
5050479Speter#include <fcntl.h>
5130638Speter#include <fts.h>
52277624Swill#include <limits.h>
53155240Simp#include <stdio.h>
54#include <stdlib.h>
55#include <sysexits.h>
56#include <unistd.h>
57
58#include "extern.h"
59#define	cp_pct(x,y)	(int)(100.0 * (double)(x) / (double)(y))
60
61int
62copy_file(const FTSENT *entp, int dne)
63{
64	static char buf[MAXBSIZE];
65	struct stat *fs;
66	int ch, checkch, from_fd, rcount, rval, to_fd;
67	ssize_t wcount;
68	size_t wresid;
69	size_t wtotal;
70	char *bufp;
71#ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
72	char *p;
73#endif
74
75	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
76		warn("%s", entp->fts_path);
77		return (1);
78	}
79
80	fs = entp->fts_statp;
81
82	/*
83	 * If the file exists and we're interactive, verify with the user.
84	 * If the file DNE, set the mode to be the from file, minus setuid
85	 * bits, modified by the umask; arguably wrong, but it makes copying
86	 * executables work right and it's been that way forever.  (The
87	 * other choice is 666 or'ed with the execute bits on the from file
88	 * modified by the umask.)
89	 */
90	if (!dne) {
91#define YESNO "(y/n [n]) "
92		if (nflag) {
93			if (vflag)
94				printf("%s not overwritten\n", to.p_path);
95			return (0);
96		} else if (iflag) {
97			(void)fprintf(stderr, "overwrite %s? %s",
98					to.p_path, YESNO);
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				(void)fprintf(stderr, "not overwritten\n");
105				return (1);
106			}
107		}
108
109		if (fflag) {
110		    /* remove existing destination file name,
111		     * create a new file  */
112		    (void)unlink(to.p_path);
113		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
114				 fs->st_mode & ~(S_ISUID | S_ISGID));
115		} else
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) {
123		warn("%s", to.p_path);
124		(void)close(from_fd);
125		return (1);
126	}
127
128	rval = 0;
129
130	/*
131	 * Mmap and write if less than 8M (the limit is so we don't totally
132	 * trash memory on big files.  This is really a minor hack, but it
133	 * wins some CPU back.
134	 */
135#ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
136	if (S_ISREG(fs->st_mode) && fs->st_size <= 8 * 1048576) {
137		if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
138		    MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
139			warn("%s", entp->fts_path);
140			rval = 1;
141		} else {
142			wtotal = 0;
143			for (bufp = p, wresid = fs->st_size; ;
144			    bufp += wcount, wresid -= (size_t)wcount) {
145				wcount = write(to_fd, bufp, wresid);
146				wtotal += wcount;
147				if (info) {
148					info = 0;
149					(void)fprintf(stderr,
150						"%s -> %s %3d%%\n",
151						entp->fts_path, to.p_path,
152						cp_pct(wtotal, fs->st_size));
153
154				}
155				if (wcount >= (ssize_t)wresid || wcount <= 0)
156					break;
157			}
158			if (wcount != (ssize_t)wresid) {
159				warn("%s", to.p_path);
160				rval = 1;
161			}
162			/* Some systems don't unmap on close(2). */
163			if (munmap(p, fs->st_size) < 0) {
164				warn("%s", entp->fts_path);
165				rval = 1;
166			}
167		}
168	} else
169#endif
170	{
171		wtotal = 0;
172		while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
173			for (bufp = buf, wresid = rcount; ;
174			    bufp += wcount, wresid -= wcount) {
175				wcount = write(to_fd, bufp, wresid);
176				wtotal += wcount;
177				if (info) {
178					info = 0;
179					(void)fprintf(stderr,
180						"%s -> %s %3d%%\n",
181						entp->fts_path, to.p_path,
182						cp_pct(wtotal, fs->st_size));
183
184				}
185				if (wcount >= (ssize_t)wresid || wcount <= 0)
186					break;
187			}
188			if (wcount != (ssize_t)wresid) {
189				warn("%s", to.p_path);
190				rval = 1;
191				break;
192			}
193		}
194		if (rcount < 0) {
195			warn("%s", entp->fts_path);
196			rval = 1;
197		}
198	}
199
200	/*
201	 * Don't remove the target even after an error.  The target might
202	 * not be a regular file, or its attributes might be important,
203	 * or its contents might be irreplaceable.  It would only be safe
204	 * to remove it if we created it and its length is 0.
205	 */
206
207	if (pflag && setfile(fs, to_fd))
208		rval = 1;
209	(void)close(from_fd);
210	if (close(to_fd)) {
211		warn("%s", to.p_path);
212		rval = 1;
213	}
214	return (rval);
215}
216
217int
218copy_link(const FTSENT *p, int exists)
219{
220	int len;
221	char llink[PATH_MAX];
222
223	if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
224		warn("readlink: %s", p->fts_path);
225		return (1);
226	}
227	llink[len] = '\0';
228	if (exists && unlink(to.p_path)) {
229		warn("unlink: %s", to.p_path);
230		return (1);
231	}
232	if (symlink(llink, to.p_path)) {
233		warn("symlink: %s", llink);
234		return (1);
235	}
236	return (pflag ? setfile(p->fts_statp, -1) : 0);
237}
238
239int
240copy_fifo(struct stat *from_stat, int exists)
241{
242	if (exists && unlink(to.p_path)) {
243		warn("unlink: %s", to.p_path);
244		return (1);
245	}
246	if (mkfifo(to.p_path, from_stat->st_mode)) {
247		warn("mkfifo: %s", to.p_path);
248		return (1);
249	}
250	return (pflag ? setfile(from_stat, -1) : 0);
251}
252
253int
254copy_special(struct stat *from_stat, int exists)
255{
256	if (exists && unlink(to.p_path)) {
257		warn("unlink: %s", to.p_path);
258		return (1);
259	}
260	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
261		warn("mknod: %s", to.p_path);
262		return (1);
263	}
264	return (pflag ? setfile(from_stat, -1) : 0);
265}
266
267int
268setfile(struct stat *fs, int fd)
269{
270	static struct timeval tv[2];
271	struct stat ts;
272	int rval, gotstat, islink, fdval;
273
274	rval = 0;
275	fdval = fd != -1;
276	islink = !fdval && S_ISLNK(fs->st_mode);
277	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
278		       S_IRWXU | S_IRWXG | S_IRWXO;
279
280	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
281	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
282	if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
283		warn("%sutimes: %s", islink ? "l" : "", to.p_path);
284		rval = 1;
285	}
286	if (fdval ? fstat(fd, &ts) :
287	    (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
288		gotstat = 0;
289	else {
290		gotstat = 1;
291		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
292			      S_IRWXU | S_IRWXG | S_IRWXO;
293	}
294	/*
295	 * Changing the ownership probably won't succeed, unless we're root
296	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
297	 * the mode; current BSD behavior is to remove all setuid bits on
298	 * chown.  If chown fails, lose setuid/setgid bits.
299	 */
300	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
301		if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
302		    (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
303		    chown(to.p_path, fs->st_uid, fs->st_gid))) {
304			if (errno != EPERM) {
305				warn("chown: %s", to.p_path);
306				rval = 1;
307			}
308			fs->st_mode &= ~(S_ISUID | S_ISGID);
309		}
310
311	if (!gotstat || fs->st_mode != ts.st_mode)
312		if (fdval ? fchmod(fd, fs->st_mode) :
313		    (islink ? lchmod(to.p_path, fs->st_mode) :
314		    chmod(to.p_path, fs->st_mode))) {
315			warn("chmod: %s", to.p_path);
316			rval = 1;
317		}
318
319	if (!gotstat || fs->st_flags != ts.st_flags)
320		if (fdval ?
321		    fchflags(fd, fs->st_flags) :
322		    (islink ? (errno = ENOSYS) :
323		    chflags(to.p_path, fs->st_flags))) {
324			warn("chflags: %s", to.p_path);
325			rval = 1;
326		}
327
328	return (rval);
329}
330
331void
332usage(void)
333{
334
335	(void)fprintf(stderr, "%s\n%s\n",
336"usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-pv] src target",
337"       cp [-R [-H | -L | -P]] [-f | -i | -n] [-pv] src1 ... srcN directory");
338	exit(EX_USAGE);
339}
340