55356fb4ae4fc6954db8bb044ac15b9e5d25078a
[dragonfly.git] / bin / cp / utils.c
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 #include <sys/param.h>
31 #include <sys/stat.h>
32 #include <sys/time.h>
33 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
34 #include <sys/mman.h>
35 #endif
36
37 #include <err.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <fts.h>
41 #include <limits.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <sysexits.h>
45 #include <unistd.h>
46
47 #include "extern.h"
48
49 #define cp_pct(x, y)    ((y == 0) ? 0 : (int)(100.0 * (x) / (y)))
50
51
52 int
53 copy_file(const FTSENT *entp, int dne)
54 {
55         static char buf[MAXBSIZE];
56         struct stat *fs;
57         ssize_t wcount, rcount;
58         size_t wresid;
59         off_t wtotal;
60         int ch, checkch, from_fd = 0, rval, to_fd = 0;
61         char *bufp;
62 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
63         char *p;
64 #endif
65
66         if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
67                 warn("%s", entp->fts_path);
68                 return (1);
69         }
70
71         fs = entp->fts_statp;
72
73         /*
74          * If the file exists and we're interactive, verify with the user.
75          * If the file DNE, set the mode to be the from file, minus setuid
76          * bits, modified by the umask; arguably wrong, but it makes copying
77          * executables work right and it's been that way forever.  (The
78          * other choice is 666 or'ed with the execute bits on the from file
79          * modified by the umask.)
80          */
81         if (!dne) {
82 #define YESNO "(y/n [n]) "
83                 if (nflag) {
84                         if (vflag)
85                                 printf("%s not overwritten\n", to.p_path);
86                         (void)close(from_fd);
87                         return (0);
88                 } else if (iflag) {
89                         (void)fprintf(stderr, "overwrite %s? %s",
90                                         to.p_path, YESNO);
91                         checkch = ch = getchar();
92                         while (ch != '\n' && ch != EOF)
93                                 ch = getchar();
94                         if (checkch != 'y' && checkch != 'Y') {
95                                 (void)close(from_fd);
96                                 (void)fprintf(stderr, "not overwritten\n");
97                                 return (1);
98                         }
99                 }
100                 
101                 if (fflag) {
102                     /* remove existing destination file name, 
103                      * create a new file  */
104                     (void)unlink(to.p_path);
105                     if (!lflag)
106                         to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
107                             fs->st_mode & ~(S_ISUID | S_ISGID));
108                 } else {
109                     if (!lflag)
110                         /* overwrite existing destination file name */
111                             to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
112                 }
113         } else {
114                 if (!lflag)
115                         to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
116                             fs->st_mode & ~(S_ISUID | S_ISGID));
117         }
118
119         if (to_fd == -1) {
120                 warn("%s", to.p_path);
121                 (void)close(from_fd);
122                 return (1);
123         }
124
125         rval = 0;
126
127         if (!lflag) {
128         /*
129                  * Mmap and write if less than 8M (the limit is so we don't totally
130                  * trash memory on big files.  This is really a minor hack, but it
131                  * wins some CPU back.
132                  * Some filesystems, such as smbnetfs, don't support mmap,
133                  * so this is a best-effort attempt.
134          */
135 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
136                 if (S_ISREG(fs->st_mode) && fs->st_size > 0 &&
137                     fs->st_size <= 8 * 1024 * 1024 &&
138                     (p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
139                     MAP_SHARED, from_fd, (off_t)0)) != MAP_FAILED) {
140                         wtotal = 0;
141                         for (bufp = p, wresid = fs->st_size; ;
142                             bufp += wcount, wresid -= (size_t)wcount) {
143                                 wcount = write(to_fd, bufp, wresid);
144                                 if (wcount <= 0)
145                                         break;
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                                 if (wcount >= (ssize_t)wresid)
155                                         break;
156                         }
157                         if (wcount != (ssize_t)wresid) {
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                 } else
167 #endif
168                 {
169                         wtotal = 0;
170                         while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
171                                 for (bufp = buf, wresid = rcount; ;
172                                     bufp += wcount, wresid -= wcount) {
173                                         wcount = write(to_fd, bufp, wresid);
174                                         if (wcount <= 0)
175                                                 break;
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                                         if (wcount >= (ssize_t)wresid)
185                                                 break;
186                                 }
187                                 if (wcount != (ssize_t)wresid) {
188                                         warn("%s", to.p_path);
189                                         rval = 1;
190                                         break;
191                                 }
192                         }
193                         if (rcount < 0) {
194                                 warn("%s", entp->fts_path);
195                                 rval = 1;
196                         }
197                 }
198         } else {
199                 if (link(entp->fts_path, to.p_path)) {
200                         warn("%s", to.p_path);
201                         rval = 1;
202                 }
203         }
204
205         /*
206          * Don't remove the target even after an error.  The target might
207          * not be a regular file, or its attributes might be important,
208          * or its contents might be irreplaceable.  It would only be safe
209          * to remove it if we created it and its length is 0.
210          */
211
212         if (!lflag) {
213                 if (pflag && setfile(fs, to_fd))
214                         rval = 1;
215                 if (close(to_fd)) {
216                         warn("%s", to.p_path);
217                         rval = 1;
218                 }
219         }
220
221         (void)close(from_fd);
222
223         return (rval);
224 }
225
226 int
227 copy_link(const FTSENT *p, int exists)
228 {
229         int len;
230         char llink[PATH_MAX];
231
232         if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
233                 warn("readlink: %s", p->fts_path);
234                 return (1);
235         }
236         llink[len] = '\0';
237         if (exists && unlink(to.p_path)) {
238                 warn("unlink: %s", to.p_path);
239                 return (1);
240         }
241         if (symlink(llink, to.p_path)) {
242                 warn("symlink: %s", llink);
243                 return (1);
244         }
245         return (pflag ? setfile(p->fts_statp, -1) : 0);
246 }
247
248 int
249 copy_fifo(struct stat *from_stat, int exists)
250 {
251         if (exists && unlink(to.p_path)) {
252                 warn("unlink: %s", to.p_path);
253                 return (1);
254         }
255         if (mkfifo(to.p_path, from_stat->st_mode)) {
256                 warn("mkfifo: %s", to.p_path);
257                 return (1);
258         }
259         return (pflag ? setfile(from_stat, -1) : 0);
260 }
261
262 int
263 copy_special(struct stat *from_stat, int exists)
264 {
265         if (exists && unlink(to.p_path)) {
266                 warn("unlink: %s", to.p_path);
267                 return (1);
268         }
269         if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
270                 warn("mknod: %s", to.p_path);
271                 return (1);
272         }
273         return (pflag ? setfile(from_stat, -1) : 0);
274 }
275
276 int
277 setfile(struct stat *fs, int fd)
278 {
279         static struct timeval tv[2];
280         struct stat ts;
281         int rval, gotstat, islink, fdval;
282
283         rval = 0;
284         fdval = fd != -1;
285         islink = !fdval && S_ISLNK(fs->st_mode);
286         fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
287                        S_IRWXU | S_IRWXG | S_IRWXO;
288
289         TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
290         TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
291         if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
292                 warn("%sutimes: %s", islink ? "l" : "", to.p_path);
293                 rval = 1;
294         }
295         if (fdval ? fstat(fd, &ts) :
296             (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
297                 gotstat = 0;
298         else {
299                 gotstat = 1;
300                 ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
301                               S_IRWXU | S_IRWXG | S_IRWXO;
302         }
303         /*
304          * Changing the ownership probably won't succeed, unless we're root
305          * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
306          * the mode; current BSD behavior is to remove all setuid bits on
307          * chown.  If chown fails, lose setuid/setgid bits.
308          */
309         if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
310                 if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
311                     (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
312                     chown(to.p_path, fs->st_uid, fs->st_gid))) {
313                         if (errno != EPERM) {
314                                 warn("chown: %s", to.p_path);
315                                 rval = 1;
316                         }
317                         fs->st_mode &= ~(S_ISUID | S_ISGID);
318                 }
319
320         if (!gotstat || fs->st_mode != ts.st_mode)
321                 if (fdval ? fchmod(fd, fs->st_mode) :
322                     (islink ? lchmod(to.p_path, fs->st_mode) :
323                     chmod(to.p_path, fs->st_mode))) {
324                         warn("chmod: %s", to.p_path);
325                         rval = 1;
326                 }
327
328         if (!gotstat || fs->st_flags != ts.st_flags)
329                 if (fdval ?
330                     fchflags(fd, fs->st_flags) :
331                     (islink ? lchflags(to.p_path, fs->st_flags) :
332                     chflags(to.p_path, fs->st_flags))) {
333                         warn("chflags: %s", to.p_path);
334                         rval = 1;
335                 }
336
337         return (rval);
338 }
339
340 void
341 usage(void)
342 {
343
344         (void)fprintf(stderr, "%s\n%s\n",
345 "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpvx] source_file target_file",
346 "       cp [-R [-H | -L | -P]] [-f | -i | -n] [-alpvx] source_file ... "
347 "target_directory");
348         exit(EX_USAGE);
349 }