]> arthur.barton.de Git - netatalk.git/blob - bin/ad/ad_cp.c
CNID fixes
[netatalk.git] / bin / ad / ad_cp.c
1 /*
2  * Copyright (c) 2010, Frank Lahm <franklahm@googlemail.com>
3  * Copyright (c) 1988, 1993, 1994
4  * The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * David Hitz of Auspex Systems Inc.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
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
34 /*
35  * Cp copies source files to target files.
36  *
37  * The global PATH_T structure "to" always contains the path to the
38  * current target file.  Since fts(3) does not change directories,
39  * this path can be either absolute or dot-relative.
40  *
41  * The basic algorithm is to initialize "to" and use fts(3) to traverse
42  * the file hierarchy rooted in the argument list.  A trivial case is the
43  * case of 'cp file1 file2'.  The more interesting case is the case of
44  * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
45  * path (relative to the root of the traversal) is appended to dir (stored
46  * in "to") to form the final target path.
47  */
48
49 #ifdef HAVE_CONFIG_H
50 #include "config.h"
51 #endif /* HAVE_CONFIG_H */
52
53 #include <sys/types.h>
54 #include <sys/stat.h>
55 #include <errno.h>
56 #include <limits.h>
57 #include <signal.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62
63 #include <atalk/ftw.h>
64 #include <atalk/adouble.h>
65 #include <atalk/vfs.h>
66 #include <atalk/util.h>
67 #include <atalk/unix.h>
68 #include <atalk/volume.h>
69 #include <atalk/volinfo.h>
70 #include <atalk/bstrlib.h>
71 #include <atalk/bstradd.h>
72 #include <atalk/queue.h>
73  
74 #include "ad.h"
75
76 #define STRIP_TRAILING_SLASH(p) {                                   \
77         while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')  \
78             *--(p).p_end = 0;                                       \
79     }
80
81 static char emptystring[] = "";
82
83 PATH_T to = { to.p_path, emptystring, "" };
84 enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
85
86 int fflag, iflag, lflag, nflag, pflag, vflag;
87 mode_t mask;
88
89 cnid_t pdid, did; /* current dir CNID and parent did*/
90
91 static afpvol_t svolume, dvolume;
92 static enum op type;
93 static int Rflag;
94 volatile sig_atomic_t sigint;
95 static int badcp, rval;
96 static int ftw_options = FTW_MOUNT | FTW_PHYS | FTW_ACTIONRETVAL;
97
98 static char           *netatalk_dirs[] = {
99     ".AppleDouble",
100     ".AppleDB",
101     ".AppleDesktop",
102     NULL
103 };
104
105 /* Forward declarations */
106 static int copy(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf);
107 static void siginfo(int _U_);
108 static int ftw_copy_file(const struct FTW *, const char *, const struct stat *, int);
109 static int ftw_copy_link(const struct FTW *, const char *, const struct stat *, int);
110 static int setfile(const struct stat *, int);
111 static int preserve_dir_acls(const struct stat *, char *, char *);
112 static int preserve_fd_acls(int, int);
113
114 /*
115   Check for netatalk special folders e.g. ".AppleDB" or ".AppleDesktop"
116   Returns pointer to name or NULL.
117 */
118 static const char *check_netatalk_dirs(const char *name)
119 {
120     int c;
121
122     for (c=0; netatalk_dirs[c]; c++) {
123         if ((strcmp(name, netatalk_dirs[c])) == 0)
124             return netatalk_dirs[c];
125     }
126     return NULL;
127 }
128
129 static void upfunc(void)
130 {
131     did = pdid;
132 }
133
134 static void usage_cp(void)
135 {
136     printf(
137         "Usage: ad cp [-R [-P]] [-pvf] <source_file> <target_file>\n"
138         "Usage: ad cp [-R [-P]] [-pvfx] <source_file [source_file ...]> <target_directory>\n"
139         );
140     exit(EXIT_FAILURE);
141 }
142
143 int ad_cp(int argc, char *argv[])
144 {
145     struct stat to_stat, tmp_stat;
146     int r, ch, have_trailing_slash;
147     char *target;
148 #if 0
149     afpvol_t srcvol;
150     afpvol_t dstvol;
151 #endif
152
153     while ((ch = getopt(argc, argv, "Rafilnpvx")) != -1)
154         switch (ch) {
155         case 'R':
156             Rflag = 1;
157             break;
158         case 'a':
159             pflag = 1;
160             Rflag = 1;
161             break;
162         case 'f':
163             fflag = 1;
164             iflag = nflag = 0;
165             break;
166         case 'i':
167             iflag = 1;
168             fflag = nflag = 0;
169             break;
170         case 'l':
171             lflag = 1;
172             break;
173         case 'n':
174             nflag = 1;
175             fflag = iflag = 0;
176             break;
177         case 'p':
178             pflag = 1;
179             break;
180         case 'v':
181             vflag = 1;
182             break;
183         case 'x':
184             ftw_options |= FTW_MOUNT;
185             break;
186         default:
187             usage_cp();
188             break;
189         }
190     argc -= optind;
191     argv += optind;
192
193     if (argc < 2)
194         usage_cp();
195
196     (void)signal(SIGINT, siginfo);
197
198     cnid_init();
199
200     /* Save the target base in "to". */
201     target = argv[--argc];
202     if ((strlcpy(to.p_path, target, PATH_MAX)) >= PATH_MAX)
203         ERROR("%s: name too long", target);
204
205     to.p_end = to.p_path + strlen(to.p_path);
206     if (to.p_path == to.p_end) {
207         *to.p_end++ = '.';
208         *to.p_end = 0;
209     }
210     have_trailing_slash = (to.p_end[-1] == '/');
211     if (have_trailing_slash)
212         STRIP_TRAILING_SLASH(to);
213     to.target_end = to.p_end;
214
215     /* Set end of argument list */
216     argv[argc] = NULL;
217
218     /*
219      * Cp has two distinct cases:
220      *
221      * cp [-R] source target
222      * cp [-R] source1 ... sourceN directory
223      *
224      * In both cases, source can be either a file or a directory.
225      *
226      * In (1), the target becomes a copy of the source. That is, if the
227      * source is a file, the target will be a file, and likewise for
228      * directories.
229      *
230      * In (2), the real target is not directory, but "directory/source".
231      */
232     r = stat(to.p_path, &to_stat);
233     if (r == -1 && errno != ENOENT)
234         ERROR("%s", to.p_path);
235     if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
236         /*
237          * Case (1).  Target is not a directory.
238          */
239         if (argc > 1)
240             ERROR("%s is not a directory", to.p_path);
241
242         /*
243          * Need to detect the case:
244          *cp -R dir foo
245          * Where dir is a directory and foo does not exist, where
246          * we want pathname concatenations turned on but not for
247          * the initial mkdir().
248          */
249         if (r == -1) {
250             lstat(*argv, &tmp_stat);
251
252             if (S_ISDIR(tmp_stat.st_mode) && Rflag)
253                 type = DIR_TO_DNE;
254             else
255                 type = FILE_TO_FILE;
256         } else
257             type = FILE_TO_FILE;
258
259         if (have_trailing_slash && type == FILE_TO_FILE) {
260             if (r == -1)
261                 ERROR("directory %s does not exist", to.p_path);
262             else
263                 ERROR("%s is not a directory", to.p_path);
264         }
265     } else
266         /*
267          * Case (2).  Target is a directory.
268          */
269         type = FILE_TO_DIR;
270
271     /*
272      * Keep an inverted copy of the umask, for use in correcting
273      * permissions on created directories when not using -p.
274      */
275     mask = ~umask(0777);
276     umask(~mask);
277
278 #if 0
279     /* Inhereting perms in ad_mkdir etc requires this */
280     ad_setfuid(0);
281 #endif
282
283     /* Load .volinfo file for destination*/
284     openvol(to.p_path, &dvolume);
285
286     for (int i = 0; argv[i] != NULL; i++) { 
287         /* Load .volinfo file for source */
288         openvol(to.p_path, &svolume);
289
290         if (nftw(argv[i], copy, upfunc, 20, ftw_options) == -1) {
291             ERROR("%s: %s", argv[i], strerror(errno));
292             exit(EXIT_FAILURE);
293         }
294
295
296     }
297     return rval;
298 }
299
300 static int copy(const char *path,
301                 const struct stat *statp,
302                 int tflag,
303                 struct FTW *ftw)
304 {
305     struct stat to_stat;
306     int base = 0, dne;
307     size_t nlen;
308     const char *p;
309     char *target_mid;
310
311     const char *dir = strrchr(path, '/');
312     if (dir == NULL)
313         dir = path;
314     else
315         dir++;
316     if (check_netatalk_dirs(dir) != NULL) {
317         SLOG("Skipping Netatalk dir %s", path);
318         return FTW_SKIP_SUBTREE;
319     }
320
321     /*
322      * If we are in case (2) above, we need to append the
323      * source name to the target name.
324      */
325     if (type != FILE_TO_FILE) {
326         /*
327          * Need to remember the roots of traversals to create
328          * correct pathnames.  If there's a directory being
329          * copied to a non-existent directory, e.g.
330          *     cp -R a/dir noexist
331          * the resulting path name should be noexist/foo, not
332          * noexist/dir/foo (where foo is a file in dir), which
333          * is the case where the target exists.
334          *
335          * Also, check for "..".  This is for correct path
336          * concatenation for paths ending in "..", e.g.
337          *     cp -R .. /tmp
338          * Paths ending in ".." are changed to ".".  This is
339          * tricky, but seems the easiest way to fix the problem.
340          *
341          * XXX
342          * Since the first level MUST be FTS_ROOTLEVEL, base
343          * is always initialized.
344          */
345         if (ftw->level == 0) {
346             if (type != DIR_TO_DNE) {
347                 base = ftw->base;
348
349                 if (strcmp(&path[base], "..") == 0)
350                     base += 1;
351             } else
352                 base = strlen(path);
353         }
354
355         p = &path[base];
356         nlen = strlen(path) - base;
357         target_mid = to.target_end;
358         if (*p != '/' && target_mid[-1] != '/')
359             *target_mid++ = '/';
360         *target_mid = 0;
361         if (target_mid - to.p_path + nlen >= PATH_MAX) {
362             SLOG("%s%s: name too long (not copied)", to.p_path, p);
363             badcp = rval = 1;
364             return 0;
365         }
366         (void)strncat(target_mid, p, nlen);
367         to.p_end = target_mid + nlen;
368         *to.p_end = 0;
369         STRIP_TRAILING_SLASH(to);
370     }
371
372     /* Not an error but need to remember it happened */
373     if (stat(to.p_path, &to_stat) == -1)
374         dne = 1;
375     else {
376         if (to_stat.st_dev == statp->st_dev &&
377             to_stat.st_ino == statp->st_ino) {
378             SLOG("%s and %s are identical (not copied).",
379                 to.p_path, path);
380             badcp = rval = 1;
381             if (S_ISDIR(statp->st_mode))
382                 /* without using glibc extension FTW_ACTIONRETVAL cant handle this */
383                 return -1;
384         }
385         if (!S_ISDIR(statp->st_mode) &&
386             S_ISDIR(to_stat.st_mode)) {
387             SLOG("cannot overwrite directory %s with "
388                 "non-directory %s",
389                 to.p_path, path);
390                 badcp = rval = 1;
391                 return 0;
392         }
393         dne = 0;
394     }
395
396     switch (statp->st_mode & S_IFMT) {
397     case S_IFLNK:
398         if (ftw_copy_link(ftw, path, statp, !dne))
399             badcp = rval = 1;
400         break;
401     case S_IFDIR:
402         if (!Rflag) {
403             SLOG("%s is a directory", path);
404             badcp = rval = 1;
405             return -1;
406         }
407         /*
408          * If the directory doesn't exist, create the new
409          * one with the from file mode plus owner RWX bits,
410          * modified by the umask.  Trade-off between being
411          * able to write the directory (if from directory is
412          * 555) and not causing a permissions race.  If the
413          * umask blocks owner writes, we fail..
414          */
415         if (dne) {
416             if (mkdir(to.p_path, statp->st_mode | S_IRWXU) < 0)
417                 ERROR("%s", to.p_path);
418         } else if (!S_ISDIR(to_stat.st_mode)) {
419             errno = ENOTDIR;
420             ERROR("%s", to.p_path);
421         }
422
423         /* Create ad dir and copy ".Parent" */
424         if (svolume.volinfo.v_path && svolume.volinfo.v_adouble == AD_VERSION2 &&
425             dvolume.volinfo.v_path && dvolume.volinfo.v_adouble == AD_VERSION2) {
426             /* Create ".AppleDouble" dir */
427             mode_t omask = umask(0);
428             bstring addir = bfromcstr(to.p_path);
429             bcatcstr(addir, "/.AppleDouble");
430             mkdir(cfrombstr(addir), 02777);
431
432             /* copy ".Parent" file */
433             bcatcstr(addir, "/.Parent");
434             bstring sdir = bfromcstr(path);
435             bcatcstr(sdir, "/.AppleDouble/.Parent");
436             if (copy_file(-1, cfrombstr(sdir), cfrombstr(addir), 0666) != 0) {
437                 SLOG("Error copying %s -> %s", cfrombstr(sdir), cfrombstr(addir));
438                 badcp = rval = 1;
439                 break;
440             }
441
442             /* Get CNID of Parent and add new childir to CNID database */
443             pdid = did;
444             did = cnid_for_path(&dvolume.volinfo, &dvolume.volume, to.p_path);
445             SLOG("got CNID: %u for path: %s", ntohl(did), to.p_path);
446
447             struct adouble ad;
448             struct stat st;
449             if (stat(to.p_path, &st) != 0) {
450                 badcp = rval = 1;
451                 break;
452             }
453             ad_init(&ad, dvolume.volinfo.v_adouble, dvolume.volinfo.v_ad_options);
454             if (ad_open_metadata(to.p_path, ADFLAGS_DIR, O_RDWR, &ad) != 0) {
455                 ERROR("Error opening adouble for: %s", to.p_path);
456             }
457             ad_setid( &ad, st.st_dev, st.st_ino, did, pdid, dvolume.db_stamp);
458             ad_flush(&ad);
459             ad_close_metadata(&ad);
460
461             bdestroy(addir);
462             bdestroy(sdir);
463             umask(omask);
464         }
465
466         if (pflag) {
467             if (setfile(statp, -1))
468                 rval = 1;
469 #if 0
470             if (preserve_dir_acls(statp, curr->fts_accpath, to.p_path) != 0)
471                 rval = 1;
472 #endif
473         }
474         break;
475
476     case S_IFBLK:
477     case S_IFCHR:
478         SLOG("%s is a device file (not copied).", path);
479         break;
480     case S_IFSOCK:
481         SLOG("%s is a socket (not copied).", path);
482         break;
483     case S_IFIFO:
484         SLOG("%s is a FIFO (not copied).", path);
485         break;
486     default:
487         if (ftw_copy_file(ftw, path, statp, dne))
488             badcp = rval = 1;
489
490         SLOG("file: %s", to.p_path);
491
492         if (svolume.volinfo.v_path && svolume.volinfo.v_adouble == AD_VERSION2 &&
493             dvolume.volinfo.v_path && dvolume.volinfo.v_adouble == AD_VERSION2) {
494
495             SLOG("ad for file: %s", to.p_path);
496
497             if (dvolume.volume.vfs->vfs_copyfile(&dvolume.volume, -1, path, to.p_path))
498                 badcp = rval = 1;
499             /* Get CNID of Parent and add new childir to CNID database */
500             cnid_t cnid = cnid_for_path(&dvolume.volinfo, &dvolume.volume, to.p_path);
501             SLOG("got CNID: %u for path: %s", ntohl(cnid), to.p_path);
502
503             struct adouble ad;
504             ad_init(&ad, dvolume.volinfo.v_adouble, dvolume.volinfo.v_ad_options);
505             if (ad_open_metadata(to.p_path, 0, O_RDWR, &ad) != 0) {
506                 ERROR("Error opening adouble for: %s", to.p_path);
507             }
508             ad_setid( &ad, statp->st_dev, statp->st_ino, cnid, did, dvolume.db_stamp);
509             ad_flush(&ad);
510             ad_close_metadata(&ad);
511         }
512         break;
513     }
514     if (vflag && !badcp)
515         (void)printf("%s -> %s\n", path, to.p_path);
516
517     return 0;
518 }
519
520 static void siginfo(int sig _U_)
521 {
522     sigint = 1;
523 }
524
525 /* Memory strategy threshold, in pages: if physmem is larger then this, use a large buffer */
526 #define PHYSPAGES_THRESHOLD (32*1024)
527
528 /* Maximum buffer size in bytes - do not allow it to grow larger than this */
529 #define BUFSIZE_MAX (2*1024*1024)
530
531 /* Small (default) buffer size in bytes. It's inefficient for this to be smaller than MAXPHYS */
532 #define MAXPHYS (64 * 1024)
533 #define BUFSIZE_SMALL (MAXPHYS)
534
535 static int ftw_copy_file(const struct FTW *entp,
536                          const char *spath,
537                          const struct stat *sp,
538                          int dne)
539 {
540     static char *buf = NULL;
541     static size_t bufsize;
542     ssize_t wcount;
543     size_t wresid;
544     off_t wtotal;
545     int ch, checkch, from_fd = 0, rcount, rval, to_fd = 0;
546     char *bufp;
547     char *p;
548
549     if ((from_fd = open(spath, O_RDONLY, 0)) == -1) {
550         SLOG("%s: %s", spath, strerror(errno));
551         return (1);
552     }
553
554     /*
555      * If the file exists and we're interactive, verify with the user.
556      * If the file DNE, set the mode to be the from file, minus setuid
557      * bits, modified by the umask; arguably wrong, but it makes copying
558      * executables work right and it's been that way forever.  (The
559      * other choice is 666 or'ed with the execute bits on the from file
560      * modified by the umask.)
561      */
562     if (!dne) {
563 #define YESNO "(y/n [n]) "
564         if (nflag) {
565             if (vflag)
566                 printf("%s not overwritten\n", to.p_path);
567             (void)close(from_fd);
568             return (0);
569         } else if (iflag) {
570             (void)fprintf(stderr, "overwrite %s? %s", 
571                           to.p_path, YESNO);
572             checkch = ch = getchar();
573             while (ch != '\n' && ch != EOF)
574                 ch = getchar();
575             if (checkch != 'y' && checkch != 'Y') {
576                 (void)close(from_fd);
577                 (void)fprintf(stderr, "not overwritten\n");
578                 return (1);
579             }
580         }
581         
582         if (fflag) {
583             /* remove existing destination file name, 
584              * create a new file  */
585             (void)unlink(to.p_path);
586             (void)dvolume.volume.vfs->vfs_deletefile(&dvolume.volume, -1, to.p_path);
587             if (!lflag)
588                 to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
589                              sp->st_mode & ~(S_ISUID | S_ISGID));
590         } else {
591             if (!lflag)
592                 /* overwrite existing destination file name */
593                 to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
594         }
595     } else {
596         if (!lflag)
597             to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
598                          sp->st_mode & ~(S_ISUID | S_ISGID));
599     }
600     
601     if (to_fd == -1) {
602         SLOG("%s: %s", to.p_path, strerror(errno));
603         (void)close(from_fd);
604         return (1);
605     }
606
607     rval = 0;
608
609     if (!lflag) {
610         /*
611          * Mmap and write if less than 8M (the limit is so we don't totally
612          * trash memory on big files.  This is really a minor hack, but it
613          * wins some CPU back.
614          * Some filesystems, such as smbnetfs, don't support mmap,
615          * so this is a best-effort attempt.
616          */
617
618         if (S_ISREG(sp->st_mode) && sp->st_size > 0 &&
619             sp->st_size <= 8 * 1024 * 1024 &&
620             (p = mmap(NULL, (size_t)sp->st_size, PROT_READ,
621                       MAP_SHARED, from_fd, (off_t)0)) != MAP_FAILED) {
622             wtotal = 0;
623             for (bufp = p, wresid = sp->st_size; ;
624                  bufp += wcount, wresid -= (size_t)wcount) {
625                 wcount = write(to_fd, bufp, wresid);
626                 if (wcount <= 0)
627                     break;
628                 wtotal += wcount;
629                 if (wcount >= (ssize_t)wresid)
630                     break;
631             }
632             if (wcount != (ssize_t)wresid) {
633                 SLOG("%s: %s", to.p_path, strerror(errno));
634                 rval = 1;
635             }
636             /* Some systems don't unmap on close(2). */
637             if (munmap(p, sp->st_size) < 0) {
638                 SLOG("%s: %s", spath, strerror(errno));
639                 rval = 1;
640             }
641         } else {
642             if (buf == NULL) {
643                 /*
644                  * Note that buf and bufsize are static. If
645                  * malloc() fails, it will fail at the start
646                  * and not copy only some files. 
647                  */ 
648                 if (sysconf(_SC_PHYS_PAGES) > 
649                     PHYSPAGES_THRESHOLD)
650                     bufsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
651                 else
652                     bufsize = BUFSIZE_SMALL;
653                 buf = malloc(bufsize);
654                 if (buf == NULL)
655                     ERROR("Not enough memory");
656
657             }
658             wtotal = 0;
659             while ((rcount = read(from_fd, buf, bufsize)) > 0) {
660                 for (bufp = buf, wresid = rcount; ;
661                      bufp += wcount, wresid -= wcount) {
662                     wcount = write(to_fd, bufp, wresid);
663                     if (wcount <= 0)
664                         break;
665                     wtotal += wcount;
666                     if (wcount >= (ssize_t)wresid)
667                         break;
668                 }
669                 if (wcount != (ssize_t)wresid) {
670                     SLOG("%s: %s", to.p_path, strerror(errno));
671                     rval = 1;
672                     break;
673                 }
674             }
675             if (rcount < 0) {
676                 SLOG("%s: %s", spath, strerror(errno));
677                 rval = 1;
678             }
679         }
680     } else {
681         if (link(spath, to.p_path)) {
682             SLOG("%s", to.p_path);
683             rval = 1;
684         }
685     }
686     
687     /*
688      * Don't remove the target even after an error.  The target might
689      * not be a regular file, or its attributes might be important,
690      * or its contents might be irreplaceable.  It would only be safe
691      * to remove it if we created it and its length is 0.
692      */
693
694     if (!lflag) {
695         if (pflag && setfile(sp, to_fd))
696             rval = 1;
697         if (pflag && preserve_fd_acls(from_fd, to_fd) != 0)
698             rval = 1;
699         if (close(to_fd)) {
700             SLOG("%s: %s", to.p_path, strerror(errno));
701             rval = 1;
702         }
703     }
704
705     (void)close(from_fd);
706
707     return (rval);
708 }
709
710 static int ftw_copy_link(const struct FTW *p,
711                          const char *spath,
712                          const struct stat *sstp,
713                          int exists)
714 {
715     int len;
716     char llink[PATH_MAX];
717
718     if ((len = readlink(spath, llink, sizeof(llink) - 1)) == -1) {
719         SLOG("readlink: %s: %s", spath, strerror(errno));
720         return (1);
721     }
722     llink[len] = '\0';
723     if (exists && unlink(to.p_path)) {
724         SLOG("unlink: %s: %s", to.p_path, strerror(errno));
725         return (1);
726     }
727     if (symlink(llink, to.p_path)) {
728         SLOG("symlink: %s: %s", llink, strerror(errno));
729         return (1);
730     }
731     return (pflag ? setfile(sstp, -1) : 0);
732 }
733
734 static int setfile(const struct stat *fs, int fd)
735 {
736     static struct timeval tv[2];
737     struct stat ts;
738     int rval, gotstat, islink, fdval;
739     mode_t mode;
740
741     rval = 0;
742     fdval = fd != -1;
743     islink = !fdval && S_ISLNK(fs->st_mode);
744     mode = fs->st_mode & (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
745
746     TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atim);
747     TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtim);
748     if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
749         SLOG("%sutimes: %s", islink ? "l" : "", to.p_path);
750         rval = 1;
751     }
752     if (fdval ? fstat(fd, &ts) :
753         (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
754         gotstat = 0;
755     else {
756         gotstat = 1;
757         ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
758             S_IRWXU | S_IRWXG | S_IRWXO;
759     }
760     /*
761      * Changing the ownership probably won't succeed, unless we're root
762      * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
763      * the mode; current BSD behavior is to remove all setuid bits on
764      * chown.  If chown fails, lose setuid/setgid bits.
765      */
766     if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
767         if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
768             (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
769              chown(to.p_path, fs->st_uid, fs->st_gid))) {
770             if (errno != EPERM) {
771                 SLOG("chown: %s: %s", to.p_path, strerror(errno));
772                 rval = 1;
773             }
774             mode &= ~(S_ISUID | S_ISGID);
775         }
776
777     if (!gotstat || mode != ts.st_mode)
778         if (fdval ? fchmod(fd, mode) : chmod(to.p_path, mode)) {
779             SLOG("chmod: %s: %s", to.p_path, strerror(errno));
780             rval = 1;
781         }
782
783 #ifdef HAVE_ST_FLAGS
784     if (!gotstat || fs->st_flags != ts.st_flags)
785         if (fdval ?
786             fchflags(fd, fs->st_flags) :
787             (islink ? lchflags(to.p_path, fs->st_flags) :
788              chflags(to.p_path, fs->st_flags))) {
789             SLOG("chflags: %s: %s", to.p_path, strerror(errno));
790             rval = 1;
791         }
792 #endif
793
794     return (rval);
795 }
796
797 static int preserve_fd_acls(int source_fd, int dest_fd)
798 {
799 #if 0
800     acl_t acl;
801     acl_type_t acl_type;
802     int acl_supported = 0, ret, trivial;
803
804     ret = fpathconf(source_fd, _PC_ACL_NFS4);
805     if (ret > 0 ) {
806         acl_supported = 1;
807         acl_type = ACL_TYPE_NFS4;
808     } else if (ret < 0 && errno != EINVAL) {
809         warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", to.p_path);
810         return (1);
811     }
812     if (acl_supported == 0) {
813         ret = fpathconf(source_fd, _PC_ACL_EXTENDED);
814         if (ret > 0 ) {
815             acl_supported = 1;
816             acl_type = ACL_TYPE_ACCESS;
817         } else if (ret < 0 && errno != EINVAL) {
818             warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
819                  to.p_path);
820             return (1);
821         }
822     }
823     if (acl_supported == 0)
824         return (0);
825
826     acl = acl_get_fd_np(source_fd, acl_type);
827     if (acl == NULL) {
828         warn("failed to get acl entries while setting %s", to.p_path);
829         return (1);
830     }
831     if (acl_is_trivial_np(acl, &trivial)) {
832         warn("acl_is_trivial() failed for %s", to.p_path);
833         acl_free(acl);
834         return (1);
835     }
836     if (trivial) {
837         acl_free(acl);
838         return (0);
839     }
840     if (acl_set_fd_np(dest_fd, acl, acl_type) < 0) {
841         warn("failed to set acl entries for %s", to.p_path);
842         acl_free(acl);
843         return (1);
844     }
845     acl_free(acl);
846 #endif
847     return (0);
848 }
849
850 static int preserve_dir_acls(const struct stat *fs, char *source_dir, char *dest_dir)
851 {
852 #if 0
853     acl_t (*aclgetf)(const char *, acl_type_t);
854     int (*aclsetf)(const char *, acl_type_t, acl_t);
855     struct acl *aclp;
856     acl_t acl;
857     acl_type_t acl_type;
858     int acl_supported = 0, ret, trivial;
859
860     ret = pathconf(source_dir, _PC_ACL_NFS4);
861     if (ret > 0) {
862         acl_supported = 1;
863         acl_type = ACL_TYPE_NFS4;
864     } else if (ret < 0 && errno != EINVAL) {
865         warn("fpathconf(..., _PC_ACL_NFS4) failed for %s", source_dir);
866         return (1);
867     }
868     if (acl_supported == 0) {
869         ret = pathconf(source_dir, _PC_ACL_EXTENDED);
870         if (ret > 0) {
871             acl_supported = 1;
872             acl_type = ACL_TYPE_ACCESS;
873         } else if (ret < 0 && errno != EINVAL) {
874             warn("fpathconf(..., _PC_ACL_EXTENDED) failed for %s",
875                  source_dir);
876             return (1);
877         }
878     }
879     if (acl_supported == 0)
880         return (0);
881
882     /*
883      * If the file is a link we will not follow it
884      */
885     if (S_ISLNK(fs->st_mode)) {
886         aclgetf = acl_get_link_np;
887         aclsetf = acl_set_link_np;
888     } else {
889         aclgetf = acl_get_file;
890         aclsetf = acl_set_file;
891     }
892     if (acl_type == ACL_TYPE_ACCESS) {
893         /*
894          * Even if there is no ACL_TYPE_DEFAULT entry here, a zero
895          * size ACL will be returned. So it is not safe to simply
896          * check the pointer to see if the default ACL is present.
897          */
898         acl = aclgetf(source_dir, ACL_TYPE_DEFAULT);
899         if (acl == NULL) {
900             warn("failed to get default acl entries on %s",
901                  source_dir);
902             return (1);
903         }
904         aclp = &acl->ats_acl;
905         if (aclp->acl_cnt != 0 && aclsetf(dest_dir,
906                                           ACL_TYPE_DEFAULT, acl) < 0) {
907             warn("failed to set default acl entries on %s",
908                  dest_dir);
909             acl_free(acl);
910             return (1);
911         }
912         acl_free(acl);
913     }
914     acl = aclgetf(source_dir, acl_type);
915     if (acl == NULL) {
916         warn("failed to get acl entries on %s", source_dir);
917         return (1);
918     }
919     if (acl_is_trivial_np(acl, &trivial)) {
920         warn("acl_is_trivial() failed on %s", source_dir);
921         acl_free(acl);
922         return (1);
923     }
924     if (trivial) {
925         acl_free(acl);
926         return (0);
927     }
928     if (aclsetf(dest_dir, acl_type, acl) < 0) {
929         warn("failed to set acl entries on %s", dest_dir);
930         acl_free(acl);
931         return (1);
932     }
933     acl_free(acl);
934 #endif
935     return (0);
936 }