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