file_cmds-287.11.1.tar.gz
[apple/file_cmds.git] / 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 #ifndef lint
31 #if 0
32 static char sccsid[] = "@(#)utils.c 8.3 (Berkeley) 4/1/94";
33 #endif
34 #endif /* not lint */
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD: src/bin/cp/utils.c,v 1.46 2005/09/05 04:36:08 csjp Exp $");
37
38 #include <sys/types.h>
39 #include <sys/acl.h>
40 #include <sys/param.h>
41 #include <sys/stat.h>
42 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
43 #include <sys/mman.h>
44 #endif
45
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <fts.h>
50 #include <limits.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <sysexits.h>
54 #include <unistd.h>
55 #include <locale.h>
56
57 #ifdef __APPLE__
58 #include <sys/time.h>
59 #include <copyfile.h>
60 #include <string.h>
61 #include <sys/mount.h>
62 #include <get_compat.h>
63 #include <sys/attr.h>
64 #include <sys/clonefile.h>
65 #else
66 #define COMPAT_MODE(a,b) (1)
67 #endif /* __APPLE__ */
68
69 #include "extern.h"
70 #define cp_pct(x,y) (int)(100.0 * (double)(x) / (double)(y))
71
72 int
73 copy_file(const FTSENT *entp, int dne)
74 {
75 static char buf[MAXBSIZE];
76 struct stat *fs;
77 int ch, checkch, from_fd, rval, to_fd;
78 ssize_t rcount;
79 ssize_t wcount;
80 size_t wresid;
81 off_t wtotal;
82 char *bufp;
83 char resp[] = {'\0', '\0'};
84 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
85 char *p;
86 #endif
87 mode_t mode = 0;
88 struct stat to_stat;
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 #define YESNO "(y/n [n]) "
107 if (nflag) {
108 if (vflag)
109 printf("%s not overwritten\n", to.p_path);
110 (void)close(from_fd);
111 return (1);
112 } else if (iflag) {
113 (void)fprintf(stderr, "overwrite %s? %s",
114 to.p_path, YESNO);
115
116 /* Load user specified locale */
117 setlocale(LC_MESSAGES, "");
118
119 checkch = ch = getchar();
120 while (ch != '\n' && ch != EOF)
121 ch = getchar();
122
123 /* only care about the first character */
124 resp[0] = checkch;
125
126 if (rpmatch(resp) != 1) {
127 (void)close(from_fd);
128 (void)fprintf(stderr, "not overwritten\n");
129 return (1);
130 }
131 }
132
133 if (cflag) {
134 (void)unlink(to.p_path);
135 int error = clonefile(entp->fts_path, to.p_path, 0);
136 if (error)
137 warn("%s: clonefile failed", to.p_path);
138 (void)close(from_fd);
139 return error == 0 ? 0 : 1;
140 }
141
142 if (COMPAT_MODE("bin/cp", "unix2003")) {
143 /* first try to overwrite existing destination file name */
144 to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
145 if (to_fd == -1) {
146 if (fflag) {
147 /* Only if it fails remove file and create a new one */
148 (void)unlink(to.p_path);
149 to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
150 fs->st_mode & ~(S_ISUID | S_ISGID));
151 }
152 }
153 } else {
154 if (fflag) {
155 /* remove existing destination file name,
156 * create a new file */
157 (void)unlink(to.p_path);
158 to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
159 fs->st_mode & ~(S_ISUID | S_ISGID));
160 } else
161 /* overwrite existing destination file name */
162 to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
163 }
164 } else {
165
166 if (cflag) {
167 int error = clonefile(entp->fts_path, to.p_path, 0);
168 if (error)
169 warn("%s: clonefile failed", to.p_path);
170 (void)close(from_fd);
171 return error == 0 ? 0 : 1;
172 }
173
174 to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
175 fs->st_mode & ~(S_ISUID | S_ISGID));
176 }
177
178 if (to_fd == -1) {
179 warn("%s", to.p_path);
180 (void)close(from_fd);
181 return (1);
182 }
183
184 rval = 0;
185
186 #ifdef __APPLE__
187 if (S_ISREG(fs->st_mode)) {
188 struct statfs sfs;
189
190 /*
191 * Pre-allocate blocks for the destination file if it
192 * resides on Xsan.
193 */
194 if (fstatfs(to_fd, &sfs) == 0 &&
195 strcmp(sfs.f_fstypename, "acfs") == 0) {
196 fstore_t fst;
197
198 fst.fst_flags = 0;
199 fst.fst_posmode = F_PEOFPOSMODE;
200 fst.fst_offset = 0;
201 fst.fst_length = fs->st_size;
202
203 (void) fcntl(to_fd, F_PREALLOCATE, &fst);
204 }
205 }
206 #endif /* __APPLE__ */
207
208 if (fstat(to_fd, &to_stat) != -1) {
209 mode = to_stat.st_mode;
210 if ((mode & (S_IRWXG|S_IRWXO))
211 && fchmod(to_fd, mode & ~(S_IRWXG|S_IRWXO))) {
212 if (errno != EPERM) /* we have write access but do not own the file */
213 warn("%s: fchmod failed", to.p_path);
214 mode = 0;
215 }
216 } else {
217 warn("%s", to.p_path);
218 }
219 /*
220 * Mmap and write if less than 8M (the limit is so we don't totally
221 * trash memory on big files. This is really a minor hack, but it
222 * wins some CPU back.
223 */
224 #ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
225 if (S_ISREG(fs->st_mode) && fs->st_size > 0 &&
226 fs->st_size <= 8 * 1048576) {
227 if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
228 MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
229 warn("%s", entp->fts_path);
230 rval = 1;
231 } else {
232 wtotal = 0;
233 for (bufp = p, wresid = fs->st_size; ;
234 bufp += wcount, wresid -= (size_t)wcount) {
235 wcount = write(to_fd, bufp, wresid);
236 wtotal += wcount;
237 if (info) {
238 info = 0;
239 (void)fprintf(stderr,
240 "%s -> %s %3d%%\n",
241 entp->fts_path, to.p_path,
242 cp_pct(wtotal, fs->st_size));
243
244 }
245 if (wcount >= (ssize_t)wresid || wcount <= 0)
246 break;
247 }
248 if (wcount != (ssize_t)wresid) {
249 warn("%s", to.p_path);
250 rval = 1;
251 }
252 /* Some systems don't unmap on close(2). */
253 if (munmap(p, fs->st_size) < 0) {
254 warn("%s", entp->fts_path);
255 rval = 1;
256 }
257 }
258 } else
259 #endif
260 {
261 wtotal = 0;
262 while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
263 for (bufp = buf, wresid = rcount; ;
264 bufp += wcount, wresid -= wcount) {
265 wcount = write(to_fd, bufp, wresid);
266 wtotal += wcount;
267 if (info) {
268 info = 0;
269 (void)fprintf(stderr,
270 "%s -> %s %3d%%\n",
271 entp->fts_path, to.p_path,
272 cp_pct(wtotal, fs->st_size));
273
274 }
275 if (wcount >= (ssize_t)wresid || wcount <= 0)
276 break;
277 }
278 if (wcount != (ssize_t)wresid) {
279 warn("%s", to.p_path);
280 rval = 1;
281 break;
282 }
283 }
284 if (rcount < 0) {
285 warn("%s", entp->fts_path);
286 rval = 1;
287 }
288 }
289
290 /*
291 * Don't remove the target even after an error. The target might
292 * not be a regular file, or its attributes might be important,
293 * or its contents might be irreplaceable. It would only be safe
294 * to remove it if we created it and its length is 0.
295 */
296 if (mode != 0)
297 if (fchmod(to_fd, mode))
298 warn("%s: fchmod failed", to.p_path);
299 #ifdef __APPLE__
300 /* do these before setfile in case copyfile changes mtime */
301 if (!Xflag && S_ISREG(fs->st_mode)) { /* skip devices, etc */
302 if (fcopyfile(from_fd, to_fd, NULL, COPYFILE_XATTR) < 0)
303 warn("%s: could not copy extended attributes to %s", entp->fts_path, to.p_path);
304 }
305 if (pflag && setfile(fs, to_fd))
306 rval = 1;
307 if (pflag) {
308 /* If this ACL denies writeattr then setfile will fail... */
309 if (fcopyfile(from_fd, to_fd, NULL, COPYFILE_ACL) < 0)
310 warn("%s: could not copy ACL to %s", entp->fts_path, to.p_path);
311 }
312 #else /* !__APPLE__ */
313 if (pflag && setfile(fs, to_fd))
314 rval = 1;
315 if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
316 rval = 1;
317 #endif /* __APPLE__ */
318 (void)close(from_fd);
319 if (close(to_fd)) {
320 warn("%s", to.p_path);
321 rval = 1;
322 }
323 return (rval);
324 }
325
326 int
327 copy_link(const FTSENT *p, int exists)
328 {
329 ssize_t len;
330 char llink[PATH_MAX];
331
332 if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
333 warn("readlink: %s", p->fts_path);
334 return (1);
335 }
336 llink[len] = '\0';
337 if (exists && unlink(to.p_path)) {
338 warn("unlink: %s", to.p_path);
339 return (1);
340 }
341 if (symlink(llink, to.p_path)) {
342 warn("symlink: %s", llink);
343 return (1);
344 }
345 #ifdef __APPLE__
346 if (!Xflag)
347 if (copyfile(p->fts_path, to.p_path, NULL, COPYFILE_XATTR | COPYFILE_NOFOLLOW_SRC) <0)
348 warn("%s: could not copy extended attributes to %s",
349 p->fts_path, to.p_path);
350 #endif
351 return (pflag ? setfile(p->fts_statp, -1) : 0);
352 }
353
354 int
355 copy_fifo(struct stat *from_stat, int exists)
356 {
357 if (exists && unlink(to.p_path)) {
358 warn("unlink: %s", to.p_path);
359 return (1);
360 }
361 if (mkfifo(to.p_path, from_stat->st_mode)) {
362 warn("mkfifo: %s", to.p_path);
363 return (1);
364 }
365 return (pflag ? setfile(from_stat, -1) : 0);
366 }
367
368 int
369 copy_special(struct stat *from_stat, int exists)
370 {
371 if (exists && unlink(to.p_path)) {
372 warn("unlink: %s", to.p_path);
373 return (1);
374 }
375 if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
376 warn("mknod: %s", to.p_path);
377 return (1);
378 }
379 return (pflag ? setfile(from_stat, -1) : 0);
380 }
381
382 int
383 setfile(struct stat *fs, int fd)
384 {
385 static struct timeval tv[2];
386 struct stat ts;
387 int rval, gotstat, islink, fdval;
388
389 rval = 0;
390 fdval = fd != -1;
391 islink = !fdval && S_ISLNK(fs->st_mode);
392 fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO;
393
394 TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
395 TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
396 if (fdval ? futimes(fd, tv) : (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv))) {
397 warn("%sutimes: %s", fdval ? "f" : (islink ? "l" : ""), to.p_path);
398 rval = 1;
399 }
400 if (fdval ? fstat(fd, &ts) : (islink ? lstat(to.p_path, &ts) :
401 stat(to.p_path, &ts))) {
402 gotstat = 0;
403 } else {
404 gotstat = 1;
405 ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO;
406 }
407 /*
408 * Changing the ownership probably won't succeed, unless we're root
409 * or POSIX_CHOWN_RESTRICTED is not set. Set uid/gid before setting
410 * the mode; current BSD behavior is to remove all setuid bits on
411 * chown. If chown fails, lose setuid/setgid bits.
412 */
413 if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid) {
414 if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) : (islink ?
415 lchown(to.p_path, fs->st_uid, fs->st_gid) :
416 chown(to.p_path, fs->st_uid, fs->st_gid))) {
417 if (errno != EPERM) {
418 warn("%schown: %s", fdval ? "f" : (islink ? "l" : ""), to.p_path);
419 rval = 1;
420 }
421 fs->st_mode &= ~(S_ISUID | S_ISGID);
422 }
423 }
424
425 if (!gotstat || fs->st_mode != ts.st_mode) {
426 if (fdval ? fchmod(fd, fs->st_mode) : (islink ?
427 lchmod(to.p_path, fs->st_mode) :
428 chmod(to.p_path, fs->st_mode))) {
429 warn("%schmod: %s", fdval ? "f" : (islink ? "l" : ""), to.p_path);
430 rval = 1;
431 }
432 }
433
434 if (!gotstat || fs->st_flags != ts.st_flags) {
435 if (fdval ? fchflags(fd, fs->st_flags) : (islink ?
436 lchflags(to.p_path, fs->st_flags) :
437 chflags(to.p_path, fs->st_flags))) {
438 if (errno != EPERM) {
439 warn("%schflags: %s", fdval ? "f" : (islink ? "l" : ""), to.p_path);
440 rval = 1;
441 }
442 }
443 }
444 return (rval);
445 }
446
447 #ifndef __APPLE__
448 int
449 preserve_fd_acls(int source_fd, int dest_fd)
450 {
451 struct acl *aclp;
452 acl_t acl;
453
454 if (fpathconf(source_fd, _PC_ACL_EXTENDED) != 1 ||
455 fpathconf(dest_fd, _PC_ACL_EXTENDED) != 1)
456 return (0);
457 acl = acl_get_fd(source_fd);
458 if (acl == NULL) {
459 warn("failed to get acl entries while setting %s", to.p_path);
460 return (1);
461 }
462 aclp = &acl->ats_acl;
463 if (aclp->acl_cnt == 3)
464 return (0);
465 if (acl_set_fd(dest_fd, acl) < 0) {
466 warn("failed to set acl entries for %s", to.p_path);
467 return (1);
468 }
469 return (0);
470 }
471
472 int
473 preserve_dir_acls(struct stat *fs, char *source_dir, char *dest_dir)
474 {
475 acl_t (*aclgetf)(const char *, acl_type_t);
476 int (*aclsetf)(const char *, acl_type_t, acl_t);
477 struct acl *aclp;
478 acl_t acl;
479
480 if (pathconf(source_dir, _PC_ACL_EXTENDED) != 1 ||
481 pathconf(dest_dir, _PC_ACL_EXTENDED) != 1)
482 return (0);
483 /*
484 * If the file is a link we will not follow it
485 */
486 if (S_ISLNK(fs->st_mode)) {
487 aclgetf = acl_get_link_np;
488 aclsetf = acl_set_link_np;
489 } else {
490 aclgetf = acl_get_file;
491 aclsetf = acl_set_file;
492 }
493 /*
494 * Even if there is no ACL_TYPE_DEFAULT entry here, a zero
495 * size ACL will be returned. So it is not safe to simply
496 * check the pointer to see if the default ACL is present.
497 */
498 acl = aclgetf(source_dir, ACL_TYPE_DEFAULT);
499 if (acl == NULL) {
500 warn("failed to get default acl entries on %s",
501 source_dir);
502 return (1);
503 }
504 aclp = &acl->ats_acl;
505 if (aclp->acl_cnt != 0 && aclsetf(dest_dir,
506 ACL_TYPE_DEFAULT, acl) < 0) {
507 warn("failed to set default acl entries on %s",
508 dest_dir);
509 return (1);
510 }
511 acl = aclgetf(source_dir, ACL_TYPE_ACCESS);
512 if (acl == NULL) {
513 warn("failed to get acl entries on %s", source_dir);
514 return (1);
515 }
516 aclp = &acl->ats_acl;
517 if (aclsetf(dest_dir, ACL_TYPE_ACCESS, acl) < 0) {
518 warn("failed to set acl entries on %s", dest_dir);
519 return (1);
520 }
521 return (0);
522 }
523 #endif /* !__APPLE__ */
524
525 void
526 usage(void)
527 {
528
529 if (COMPAT_MODE("bin/cp", "unix2003")) {
530 (void)fprintf(stderr, "%s\n%s\n",
531 "usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file target_file",
532 " cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file ... "
533 "target_directory");
534 } else {
535 (void)fprintf(stderr, "%s\n%s\n",
536 "usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-apvXc] source_file target_file",
537 " cp [-R [-H | -L | -P]] [-f | -i | -n] [-apvXc] source_file ... "
538 "target_directory");
539 }
540 exit(EX_USAGE);
541 }