Merge branch 'vendor/DHCPCD'
[dragonfly.git] / bin / cpdup / cpdup.c
1 /*-
2  * CPDUP.C
3  *
4  * CPDUP <options> source destination
5  *
6  * (c) Copyright 1997-1999 by Matthew Dillon and Dima Ruban.  Permission to
7  *     use and distribute based on the FreeBSD copyright.  Supplied as-is,
8  *     USE WITH EXTREME CAUTION.
9  *
10  * This program attempts to duplicate the source onto the destination as
11  * exactly as possible, retaining modify times, flags, perms, uid, and gid.
12  * It can duplicate devices, files (including hardlinks), softlinks,
13  * directories, and so forth.  It is recursive by default!  The duplication
14  * is inclusive of removal of files/directories on the destination that do
15  * not exist on the source.  This program supports a per-directory exception
16  * file called .cpignore, or a user-specified exception file.
17  *
18  * Safety features:
19  *
20  *      - does not cross partition boundries on source
21  *      - asks for confirmation on deletions unless -i0 is specified
22  *      - refuses to replace a destination directory with a source file
23  *        unless -s0 is specified.
24  *      - terminates on error
25  *
26  * Copying features:
27  *
28  *      - does not copy file if mtime, flags, perms, and size match unless
29  *        forced
30  *
31  *      - copies to temporary and renames-over the original, allowing
32  *        you to update live systems
33  *
34  *      - copies uid, gid, mtime, perms, flags, softlinks, devices, hardlinks,
35  *        and recurses through directories.
36  *
37  *      - accesses a per-directory exclusion file, .cpignore, containing
38  *        standard wildcarded ( ? / * style, NOT regex) exclusions.
39  *
40  *      - tries to play permissions and flags smart in regards to overwriting
41  *        schg files and doing related stuff.
42  *
43  *      - Can do MD5 consistancy checks
44  *
45  *      - Is able to do incremental mirroring/backups via hardlinks from
46  *        the 'previous' version (supplied with -H path).
47  *
48  * $DragonFly: src/bin/cpdup/cpdup.c,v 1.32 2008/11/11 04:36:00 dillon Exp $
49  */
50
51 /*-
52  * Example: cc -O cpdup.c -o cpdup -lcrypto
53  *
54  * ".MD5.CHECKSUMS" contains md5 checksumms for the current directory.
55  * This file is stored on the source.
56  */
57
58 #include "cpdup.h"
59 #include "hclink.h"
60 #include "hcproto.h"
61
62 #define HSIZE   8192
63 #define HMASK   (HSIZE-1)
64 #define HLSIZE  8192
65 #define HLMASK  (HLSIZE - 1)
66
67 #define GETBUFSIZE      8192
68 #define GETPATHSIZE     2048
69 #define GETLINKSIZE     1024
70 #define GETIOSIZE       65536
71
72 #ifndef _ST_FLAGS_PRESENT_
73 #define st_flags        st_mode
74 #endif
75
76 typedef struct Node {
77     struct Node *no_Next;
78     struct Node *no_HNext;
79     struct stat *no_Stat;
80     int  no_Value;
81     char no_Name[4];
82 } Node;
83
84 typedef struct List {
85     Node        li_Node;
86     Node        *li_Hash[HSIZE];
87 } List;
88
89 struct hlink {
90     ino_t ino;
91     ino_t dino;
92     int refs;
93     struct hlink *next;
94     struct hlink *prev;
95     nlink_t nlinked;
96     char name[];
97 };
98
99 typedef struct copy_info {
100         char *spath;
101         char *dpath;
102         dev_t sdevNo;
103         dev_t ddevNo;
104 } *copy_info_t;
105
106 static struct hlink *hltable[HLSIZE];
107
108 static void RemoveRecur(const char *dpath, dev_t devNo, struct stat *dstat);
109 static void InitList(List *list);
110 static void ResetList(List *list);
111 static Node *IterateList(List *list, Node *node, int n);
112 static int AddList(List *list, const char *name, int n, struct stat *st);
113 static int CheckList(List *list, const char *path, const char *name);
114 static int getbool(const char *str);
115 static char *SplitRemote(char **pathp);
116 static int ChgrpAllowed(gid_t g);
117 static int OwnerMatch(struct stat *st1, struct stat *st2);
118 #ifdef _ST_FLAGS_PRESENT_
119 static int FlagsMatch(struct stat *st1, struct stat *st2);
120 #else
121 #define FlagsMatch(st1, st2)    1
122 #endif
123 static struct hlink *hltlookup(struct stat *);
124 static struct hlink *hltadd(struct stat *, const char *);
125 static char *checkHLPath(struct stat *st, const char *spath, const char *dpath);
126 static int validate_check(const char *spath, const char *dpath);
127 static int shash(const char *s);
128 static void hltdelete(struct hlink *);
129 static void hltsetdino(struct hlink *, ino_t);
130 static int YesNo(const char *path);
131 static int xrename(const char *src, const char *dst, u_long flags);
132 static int xlink(const char *src, const char *dst, u_long flags);
133 static int xremove(struct HostConf *host, const char *path);
134 static int xrmdir(struct HostConf *host, const char *path);
135 static int DoCopy(copy_info_t info, struct stat *stat1, int depth);
136 static int ScanDir(List *list, struct HostConf *host, const char *path,
137         int64_t *CountReadBytes, int n);
138
139 int AskConfirmation = 1;
140 int SafetyOpt = 1;
141 int ForceOpt;
142 int DeviceOpt = 1;
143 int VerboseOpt;
144 int DirShowOpt;
145 int NotForRealOpt;
146 int QuietOpt;
147 int NoRemoveOpt;
148 int UseMD5Opt;
149 int UseFSMIDOpt;
150 int SummaryOpt;
151 int CompressOpt;
152 int SlaveOpt;
153 int ReadOnlyOpt;
154 int ValidateOpt;
155 int ssh_argc;
156 const char *ssh_argv[16];
157 int DstRootPrivs;
158
159 const char *UseCpFile;
160 const char *MD5CacheFile;
161 const char *FSMIDCacheFile;
162 const char *UseHLPath;
163
164 static int DstBaseLen;
165 static int HardLinkCount;
166 static int GroupCount;
167 static gid_t *GroupList;
168
169 int64_t CountSourceBytes;
170 int64_t CountSourceItems;
171 int64_t CountCopiedItems;
172 int64_t CountSourceReadBytes;
173 int64_t CountTargetReadBytes;
174 int64_t CountWriteBytes;
175 int64_t CountRemovedItems;
176 int64_t CountLinkedItems;
177
178 static struct HostConf SrcHost;
179 static struct HostConf DstHost;
180
181 int
182 main(int ac, char **av)
183 {
184     int i;
185     int opt;
186     char *src = NULL;
187     char *dst = NULL;
188     char *ptr;
189     struct timeval start;
190     struct copy_info info;
191
192     signal(SIGPIPE, SIG_IGN);
193
194     gettimeofday(&start, NULL);
195     opterr = 0;
196     while ((opt = getopt(ac, av, ":CdF:fH:hIi:j:K:klM:mnoqRSs:uVvX:x")) != -1) {
197         switch (opt) {
198         case 'C':
199             CompressOpt = 1;
200             break;
201         case 'd':
202             DirShowOpt = 1;
203             break;
204         case 'F':
205             if (ssh_argc >= 16)
206                 fatal("too many -F options");
207             ssh_argv[ssh_argc++] = optarg;
208             break;
209         case 'f':
210             ForceOpt = 1;
211             break;
212         case 'H':
213             UseHLPath = optarg;
214             break;
215         case 'h':
216             fatal(NULL);
217             /* not reached */
218             break;
219         case 'I':
220             SummaryOpt = 1;
221             break;
222         case 'i':
223             AskConfirmation = getbool(optarg);
224             break;
225         case 'j':
226             DeviceOpt = getbool(optarg);
227             break;
228         case 'K':
229             UseFSMIDOpt = 1;
230             FSMIDCacheFile = optarg;
231             break;
232         case 'k':
233             UseFSMIDOpt = 1;
234             FSMIDCacheFile = ".FSMID.CHECK";
235             break;
236         case 'l':
237             setlinebuf(stdout);
238             setlinebuf(stderr);
239             break;
240         case 'M':
241             UseMD5Opt = 1;
242             MD5CacheFile = optarg;
243             break;
244         case 'm':
245             UseMD5Opt = 1;
246             MD5CacheFile = ".MD5.CHECKSUMS";
247             break;
248         case 'n':
249             NotForRealOpt = 1;
250             break;
251         case 'o':
252             NoRemoveOpt = 1;
253             break;
254         case 'q':
255             QuietOpt = 1;
256             break;
257         case 'R':
258             ReadOnlyOpt = 1;
259             break;
260         case 'S':
261             SlaveOpt = 1;
262             break;
263         case 's':
264             SafetyOpt = getbool(optarg);
265             break;
266         case 'u':
267             setvbuf(stdout, NULL, _IOLBF, 0);
268             break;
269         case 'V':
270             ++ValidateOpt;
271             break;
272         case 'v':
273             ++VerboseOpt;
274             break;
275         case 'X':
276             UseCpFile = optarg;
277             break;
278         case 'x':
279             UseCpFile = ".cpignore";
280             break;
281         case ':':
282             fatal("missing argument for option: -%c\n", optopt);
283             /* not reached */
284             break;
285         case '?':
286             fatal("illegal option: -%c\n", optopt);
287             /* not reached */
288             break;
289         default:
290             fatal(NULL);
291             /* not reached */
292             break;
293         }
294     }
295     ac -= optind;
296     av += optind;
297     if (ac > 0)
298         src = av[0];
299     if (ac > 1)
300         dst = av[1];
301     if (ac > 2)
302         fatal("too many arguments");
303
304     /*
305      * If we are told to go into slave mode, run the HC protocol
306      */
307     if (SlaveOpt) {
308         DstRootPrivs = (geteuid() == 0);
309         hc_slave(0, 1);
310         exit(0);
311     }
312
313     /*
314      * Extract the source and/or/neither target [user@]host and
315      * make any required connections.
316      */
317     if (src && (ptr = SplitRemote(&src)) != NULL) {
318         SrcHost.host = src;
319         src = ptr;
320         if (UseMD5Opt)
321             fatal("The MD5 options are not currently supported for remote sources");
322         if (hc_connect(&SrcHost, ReadOnlyOpt) < 0)
323             exit(1);
324     } else if (ReadOnlyOpt)
325         fatal("The -R option is only supported for remote sources");
326
327     if (dst && (ptr = SplitRemote(&dst)) != NULL) {
328         DstHost.host = dst;
329         dst = ptr;
330         if (UseFSMIDOpt)
331             fatal("The FSMID options are not currently supported for remote targets");
332         if (hc_connect(&DstHost, 0) < 0)
333             exit(1);
334     }
335
336     /*
337      * dst may be NULL only if -m option is specified,
338      * which forces an update of the MD5 checksums
339      */
340     if (dst == NULL && UseMD5Opt == 0) {
341         fatal(NULL);
342         /* not reached */
343     }
344
345     if (dst) {
346         DstRootPrivs = (hc_geteuid(&DstHost) == 0);
347         if (!DstRootPrivs)
348             GroupCount = hc_getgroups(&DstHost, &GroupList);
349     }
350 #if 0
351     /* XXXX DEBUG */
352     fprintf(stderr, "DstRootPrivs == %s\n", DstRootPrivs ? "true" : "false");
353     fprintf(stderr, "GroupCount == %d\n", GroupCount);
354     for (i = 0; i < GroupCount; i++)
355         fprintf(stderr, "Group[%d] == %d\n", i, GroupList[i]);
356 #endif
357
358     bzero(&info, sizeof(info));
359     if (dst) {
360         DstBaseLen = strlen(dst);
361         info.spath = src;
362         info.dpath = dst;
363         info.sdevNo = (dev_t)-1;
364         info.ddevNo = (dev_t)-1;
365         i = DoCopy(&info, NULL, -1);
366     } else {
367         info.spath = src;
368         info.dpath = NULL;
369         info.sdevNo = (dev_t)-1;
370         info.ddevNo = (dev_t)-1;
371         i = DoCopy(&info, NULL, -1);
372     }
373 #ifndef NOMD5
374     md5_flush();
375 #endif
376     fsmid_flush();
377
378     if (SummaryOpt && i == 0) {
379         double duration;
380         struct timeval end;
381
382         gettimeofday(&end, NULL);
383 #if 0
384         /* don't count stat's in our byte statistics */
385         CountSourceBytes += sizeof(struct stat) * CountSourceItems;
386         CountSourceReadBytes += sizeof(struct stat) * CountSourceItems;
387         CountWriteBytes +=  sizeof(struct stat) * CountCopiedItems;
388         CountWriteBytes +=  sizeof(struct stat) * CountRemovedItems;
389 #endif
390
391         duration = (end.tv_sec - start.tv_sec);
392         duration += (double)(end.tv_usec - start.tv_usec) / 1000000.0;
393         if (duration == 0.0)
394                 duration = 1.0;
395         logstd("cpdup completed successfully\n");
396         logstd("%lld bytes source, %lld src bytes read, %lld tgt bytes read\n"
397                "%lld bytes written (%.1fX speedup)\n",
398             (long long)CountSourceBytes,
399             (long long)CountSourceReadBytes,
400             (long long)CountTargetReadBytes,
401             (long long)CountWriteBytes,
402             ((double)CountSourceBytes * 2.0) / ((double)(CountSourceReadBytes + CountTargetReadBytes + CountWriteBytes)));
403         logstd("%lld source items, %lld items copied, %lld items linked, "
404                "%lld things deleted\n",
405             (long long)CountSourceItems,
406             (long long)CountCopiedItems,
407             (long long)CountLinkedItems,
408             (long long)CountRemovedItems);
409         logstd("%.1f seconds %5d Kbytes/sec synced %5d Kbytes/sec scanned\n",
410             duration,
411             (int)((CountSourceReadBytes + CountTargetReadBytes + CountWriteBytes) / duration  / 1024.0),
412             (int)(CountSourceBytes / duration / 1024.0));
413     }
414     exit((i == 0) ? 0 : 1);
415 }
416
417 static int
418 getbool(const char *str)
419 {
420     if (strcmp(str, "0") == 0)
421         return (0);
422     if (strcmp(str, "1") == 0)
423         return (1);
424     fatal("option requires boolean argument (0 or 1): -%c\n", optopt);
425     /* not reached */
426     return (0);
427 }
428
429 /*
430  * Check if path specifies a remote path, using the same syntax as scp(1),
431  * i.e. a path is considered remote if the first colon is not preceded by
432  * a slash, so e.g. "./foo:bar" is considered local.
433  * If a remote path is detected, the colon is replaced with a null byte,
434  * and the return value is a pointer to the next character.
435  * Otherwise NULL is returned.
436  *
437  * A path prefix of localhost is the same as a locally specified file or
438  * directory path, but prevents any further interpretation of the path
439  * as being a remote hostname (for paths that have colons in them).
440  */
441 static char *
442 SplitRemote(char **pathp)
443 {
444     int cindex;
445     char *path = *pathp;
446
447     if (path[(cindex = strcspn(path, ":/"))] == ':') {
448         path[cindex++] = 0;
449         if (strcmp(path, "localhost") != 0)
450                 return (path + cindex);
451         *pathp = path + cindex;
452     }
453     return (NULL);
454 }
455
456 /*
457  * Check if group g is in our GroupList.
458  *
459  * Typically the number of groups a user belongs to isn't large
460  * enough to warrant more effort than a simple linear search.
461  * However, we perform an optimization by moving a group to the
462  * top of the list when we have a hit.  This assumes that there
463  * isn't much variance in the gids of files that a non-root user
464  * copies.  So most of the time the search will terminate on the
465  * first element of the list.
466  */
467 static int
468 ChgrpAllowed(gid_t g)
469 {
470     int i;
471
472     for (i = 0; i < GroupCount; i++)
473         if (GroupList[i] == g) {
474             if (i > 0) {
475                 /* Optimize: Move g to the front of the list. */
476                 for (; i > 0; i--)
477                     GroupList[i] = GroupList[i - 1];
478                 GroupList[0] = g;
479             }
480             return (1);
481         }
482     return (0);
483 }
484
485 /*
486  * The following two functions return true if the ownership (UID + GID)
487  * or the flags of two files match, respectively.
488  *
489  * Only perform weak checking if we don't have sufficient privileges on
490  * the target machine, so we don't waste transfers with things that are
491  * bound to fail anyway.
492  */
493 static int
494 OwnerMatch(struct stat *st1, struct stat *st2)
495 {
496     if (DstRootPrivs)
497         /* Both UID and GID must match. */
498         return (st1->st_uid == st2->st_uid && st1->st_gid == st2->st_gid);
499     else
500         /* Ignore UID, and also ignore GID if we can't chgrp to that group. */
501         return (st1->st_gid == st2->st_gid || !ChgrpAllowed(st1->st_gid));
502 }
503
504 #ifdef _ST_FLAGS_PRESENT_
505 static int
506 FlagsMatch(struct stat *st1, struct stat *st2)
507 {
508 /*
509  * Ignore UF_ARCHIVE.  It gets set automatically by the filesystem, for
510  * filesystems that support it.  If the destination filesystem supports it, but
511  * it's cleared on the source file, then multiple invocations of cpdup would
512  * all try to copy the file because the flags wouldn't match.
513  *
514  * When unpriveleged, ignore flags we can't set
515  */
516     u_long ignored = DstRootPrivs ? 0 : SF_SETTABLE;
517
518 #ifdef UF_ARCHIVE
519     ignored |= UF_ARCHIVE;
520 #endif
521     return (((st1->st_flags ^ st2->st_flags) & ~ignored) == 0);
522 }
523 #endif
524
525
526 static struct hlink *
527 hltlookup(struct stat *stp)
528 {
529     struct hlink *hl;
530     int n;
531
532     n = stp->st_ino & HLMASK;
533
534     for (hl = hltable[n]; hl; hl = hl->next) {
535         if (hl->ino == stp->st_ino) {
536             ++hl->refs;
537             return hl;
538         }
539     }
540
541     return NULL;
542 }
543
544 static struct hlink *
545 hltadd(struct stat *stp, const char *path)
546 {
547     struct hlink *new;
548     int plen = strlen(path);
549     int n;
550
551     new = malloc(offsetof(struct hlink, name[plen + 1]));
552     if (new == NULL)
553         fatal("out of memory");
554     ++HardLinkCount;
555
556     /* initialize and link the new element into the table */
557     new->ino = stp->st_ino;
558     new->dino = (ino_t)-1;
559     new->refs = 1;
560     bcopy(path, new->name, plen + 1);
561     new->nlinked = 1;
562     new->prev = NULL;
563     n = stp->st_ino & HLMASK;
564     new->next = hltable[n];
565     if (hltable[n])
566         hltable[n]->prev = new;
567     hltable[n] = new;
568
569     return new;
570 }
571
572 static void
573 hltsetdino(struct hlink *hl, ino_t inum)
574 {
575     hl->dino = inum;
576 }
577
578 static void
579 hltdelete(struct hlink *hl)
580 {
581     assert(hl->refs == 1);
582     --hl->refs;
583     if (hl->prev) {
584         if (hl->next)
585             hl->next->prev = hl->prev;
586         hl->prev->next = hl->next;
587     } else {
588         if (hl->next)
589             hl->next->prev = NULL;
590
591         hltable[hl->ino & HLMASK] = hl->next;
592     }
593     --HardLinkCount;
594     free(hl);
595 }
596
597 static void
598 hltrels(struct hlink *hl)
599 {
600     assert(hl->refs == 1);
601     --hl->refs;
602 }
603
604 /*
605  * If UseHLPath is defined check to see if the file in question is
606  * the same as the source file, and if it is return a pointer to the
607  * -H path based file for hardlinking.  Else return NULL.
608  */
609 static char *
610 checkHLPath(struct stat *st1, const char *spath, const char *dpath)
611 {
612     struct stat sthl;
613     char *hpath;
614     int error;
615
616     if (asprintf(&hpath, "%s%s", UseHLPath, dpath + DstBaseLen) < 0)
617         fatal("out of memory");
618
619     /*
620      * stat info matches ?
621      */
622     if (hc_stat(&DstHost, hpath, &sthl) < 0 ||
623         st1->st_size != sthl.st_size ||
624         st1->st_mtime != sthl.st_mtime ||
625         !OwnerMatch(st1, &sthl) ||
626         !FlagsMatch(st1, &sthl)
627     ) {
628         free(hpath);
629         return(NULL);
630     }
631
632     /*
633      * If ForceOpt or ValidateOpt is set we have to compare the files
634      */
635     if (ForceOpt || ValidateOpt) {
636         error = validate_check(spath, hpath);
637         if (error) {
638             free(hpath);
639             hpath = NULL;
640         }
641     }
642     return(hpath);
643 }
644
645 /*
646  * Return 0 if the contents of the file <spath> matches the contents of
647  * the file <dpath>.
648  */
649 static int
650 validate_check(const char *spath, const char *dpath)
651 {
652     int error;
653     int fd1;
654     int fd2;
655
656     fd1 = hc_open(&SrcHost, spath, O_RDONLY, 0);
657     fd2 = hc_open(&DstHost, dpath, O_RDONLY, 0);
658     error = -1;
659
660     if (fd1 >= 0 && fd2 >= 0) {
661         int n;
662         int x;
663         char *iobuf1 = malloc(GETIOSIZE);
664         char *iobuf2 = malloc(GETIOSIZE);
665
666         while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
667             CountSourceReadBytes += n;
668             x = hc_read(&DstHost, fd2, iobuf2, GETIOSIZE);
669             if (x > 0)
670                     CountTargetReadBytes += x;
671             if (x != n)
672                 break;
673             if (bcmp(iobuf1, iobuf2, n) != 0)
674                 break;
675         }
676         free(iobuf1);
677         free(iobuf2);
678         if (n == 0)
679             error = 0;
680     }
681     if (fd1 >= 0)
682         hc_close(&SrcHost, fd1);
683     if (fd2 >= 0)
684         hc_close(&DstHost, fd2);
685     return (error);
686 }
687
688 int
689 DoCopy(copy_info_t info, struct stat *stat1, int depth)
690 {
691     const char *spath = info->spath;
692     const char *dpath = info->dpath;
693     dev_t sdevNo = info->sdevNo;
694     dev_t ddevNo = info->ddevNo;
695     struct stat st1;
696     struct stat st2;
697     unsigned long st2_flags;
698     int r, mres, fres, st2Valid;
699     struct hlink *hln;
700     uint64_t size;
701
702     r = mres = fres = st2Valid = 0;
703     st2_flags = 0;
704     size = 0;
705     hln = NULL;
706
707     if (stat1 == NULL) {
708         if (hc_lstat(&SrcHost, spath, &st1) != 0) {
709             r = 1;
710             goto done;
711         }
712         stat1 = &st1;
713     }
714 #ifdef SF_SNAPSHOT
715     /* skip snapshot files because they're sparse and _huge_ */
716     if (stat1->st_flags & SF_SNAPSHOT)
717        return(0);
718 #endif
719     st2.st_mode = 0;    /* in case lstat fails */
720     st2.st_flags = 0;   /* in case lstat fails */
721     if (dpath && hc_lstat(&DstHost, dpath, &st2) == 0) {
722         st2Valid = 1;
723 #ifdef _ST_FLAGS_PRESENT_
724         st2_flags = st2.st_flags;
725 #endif
726     }
727
728     if (S_ISREG(stat1->st_mode))
729         size = stat1->st_size;
730
731     /*
732      * Handle hardlinks
733      */
734
735     if (S_ISREG(stat1->st_mode) && stat1->st_nlink > 1 && dpath) {
736         if ((hln = hltlookup(stat1)) != NULL) {
737             hln->nlinked++;
738
739             if (st2Valid) {
740                 if (st2.st_ino == hln->dino) {
741                     /*
742                      * hard link is already correct, nothing to do
743                      */
744                     if (VerboseOpt >= 3)
745                         logstd("%-32s nochange\n", (dpath) ? dpath : spath);
746                     if (hln->nlinked == stat1->st_nlink) {
747                         hltdelete(hln);
748                         hln = NULL;
749                     }
750                     CountSourceItems++;
751                     r = 0;
752                     goto done;
753                 } else {
754                     /*
755                      * hard link is not correct, attempt to unlink it
756                      */
757                     if (xremove(&DstHost, dpath) < 0) {
758                         logerr("%-32s hardlink: unable to unlink: %s\n",
759                             ((dpath) ? dpath : spath), strerror(errno));
760                         hltdelete(hln);
761                         hln = NULL;
762                         ++r;
763                         goto done;
764                     }
765                 }
766             }
767
768             if (xlink(hln->name, dpath, stat1->st_flags) < 0) {
769                 int tryrelink = (errno == EMLINK);
770                 logerr("%-32s hardlink: unable to link to %s: %s\n",
771                     (dpath ? dpath : spath), hln->name, strerror(errno)
772                 );
773                 hltdelete(hln);
774                 hln = NULL;
775                 if (tryrelink) {
776                     logerr("%-20s hardlink: will attempt to copy normally\n",
777                         (dpath ? dpath : spath));
778                     goto relink;
779                 }
780                 ++r;
781             } else {
782                 if (hln->nlinked == stat1->st_nlink) {
783                     hltdelete(hln);
784                     hln = NULL;
785                 }
786                 if (r == 0) {
787                     if (VerboseOpt) {
788                         logstd("%-32s hardlink: %s\n",
789                             (dpath ? dpath : spath),
790                             (st2Valid ? "relinked" : "linked")
791                         );
792                     }
793                     CountSourceItems++;
794                     CountCopiedItems++;
795                     r = 0;
796                     goto done;
797                 }
798             }
799         } else {
800             /*
801              * first instance of hardlink must be copied normally
802              */
803 relink:
804             hln = hltadd(stat1, dpath);
805         }
806     }
807
808     /*
809      * Do we need to copy the file/dir/link/whatever?  Early termination
810      * if we do not.  Always redo links.  Directories are always traversed
811      * except when the FSMID options are used.
812      *
813      * NOTE: st2Valid is true only if dpath != NULL *and* dpath stats good.
814      */
815
816     if (
817         st2Valid
818         && stat1->st_mode == st2.st_mode
819         && FlagsMatch(stat1, &st2)
820     ) {
821         if (S_ISLNK(stat1->st_mode) || S_ISDIR(stat1->st_mode)) {
822             /*
823              * If FSMID tracking is turned on we can avoid recursing through
824              * an entire directory subtree if the FSMID matches.
825              */
826 #ifdef _ST_FSMID_PRESENT_
827             if (ForceOpt == 0 &&
828                 (UseFSMIDOpt && (fres = fsmid_check(stat1->st_fsmid, dpath)) == 0)
829             ) {
830                 if (VerboseOpt >= 3) {
831                     if (UseFSMIDOpt) /* always true!?! */
832                         logstd("%-32s fsmid-nochange\n", (dpath ? dpath : spath));
833                     else
834                         logstd("%-32s nochange\n", (dpath ? dpath : spath));
835                 }
836                 r = 0;
837                 goto done;
838             }
839 #endif
840         } else {
841             if (ForceOpt == 0 &&
842                 stat1->st_size == st2.st_size &&
843                 (ValidateOpt == 2 || stat1->st_mtime == st2.st_mtime) &&
844                 OwnerMatch(stat1, &st2)
845 #ifndef NOMD5
846                 && (UseMD5Opt == 0 || !S_ISREG(stat1->st_mode) ||
847                     (mres = md5_check(spath, dpath)) == 0)
848 #endif
849 #ifdef _ST_FSMID_PRESENT_
850                 && (UseFSMIDOpt == 0 ||
851                     (fres = fsmid_check(stat1->st_fsmid, dpath)) == 0)
852 #endif
853                 && (ValidateOpt == 0 || !S_ISREG(stat1->st_mode) ||
854                     validate_check(spath, dpath) == 0)
855             ) {
856                 /*
857                  * The files are identical, but if we are running as
858                  * root we might need to adjust ownership/group/flags.
859                  */
860                 int changedown = 0;
861                 int changedflags = 0;
862
863                 if (hln)
864                     hltsetdino(hln, st2.st_ino);
865
866                 if (!OwnerMatch(stat1, &st2)) {
867                     hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid);
868                     changedown = 1;
869                 }
870 #ifdef _ST_FLAGS_PRESENT_
871                 if (!FlagsMatch(stat1, &st2)) {
872                     hc_chflags(&DstHost, dpath, stat1->st_flags);
873                     changedflags = 1;
874                 }
875 #endif
876                 if (VerboseOpt >= 3) {
877 #ifndef NOMD5
878                     if (UseMD5Opt) {
879                         logstd("%-32s md5-nochange",
880                                 (dpath ? dpath : spath));
881                     } else
882 #endif
883                     if (UseFSMIDOpt) {
884                         logstd("%-32s fsmid-nochange",
885                                 (dpath ? dpath : spath));
886                     } else if (ValidateOpt) {
887                         logstd("%-32s nochange (contents validated)",
888                                 (dpath ? dpath : spath));
889                     } else {
890                         logstd("%-32s nochange", (dpath ? dpath : spath));
891                     }
892                     if (changedown)
893                         logstd(" (uid/gid differ)");
894                     if (changedflags)
895                         logstd(" (flags differ)");
896                     logstd("\n");
897                 }
898                 CountSourceBytes += size;
899                 CountSourceItems++;
900                 r = 0;
901                 goto done;
902             }
903         }
904     }
905     if (st2Valid && !S_ISDIR(stat1->st_mode) && S_ISDIR(st2.st_mode)) {
906         if (SafetyOpt) {
907             logerr("%-32s SAFETY - refusing to copy file over directory\n",
908                 (dpath ? dpath : spath)
909             );
910             ++r;                /* XXX */
911             r = 0;
912             goto done;          /* continue with the cpdup anyway */
913         }
914         if (QuietOpt == 0 || AskConfirmation) {
915             logstd("%-32s WARNING: non-directory source will blow away\n"
916                    "%-32s preexisting dest directory, continuing anyway!\n",
917                    ((dpath) ? dpath : spath), "");
918         }
919         if (dpath)
920             RemoveRecur(dpath, ddevNo, &st2);
921         st2Valid = 0;
922     }
923
924     /*
925      * The various comparisons failed, copy it.
926      */
927     if (S_ISDIR(stat1->st_mode)) {
928         int skipdir = 0;
929
930         if (fres < 0)
931             logerr("%-32s/ fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
932
933         if (dpath) {
934             if (!st2Valid || S_ISDIR(st2.st_mode) == 0) {
935                 if (st2Valid)
936                     xremove(&DstHost, dpath);
937                 if (hc_mkdir(&DstHost, dpath, stat1->st_mode | 0700) != 0) {
938                     logerr("%s: mkdir failed: %s\n",
939                         (dpath ? dpath : spath), strerror(errno));
940                     r = 1;
941                     skipdir = 1;
942                 }
943                 if (hc_lstat(&DstHost, dpath, &st2) != 0) {
944                     if (NotForRealOpt == 0)
945                             logerr("%s: lstat of newly made dir failed: %s\n",
946                                    (dpath ? dpath : spath), strerror(errno));
947                     st2Valid = 0;
948                     r = 1;
949                     skipdir = 1;
950                 }
951                 else {
952                     st2Valid = 1;
953                     if (!OwnerMatch(stat1, &st2) &&
954                         hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid) != 0
955                     ) {
956                         logerr("%s: chown of newly made dir failed: %s\n",
957                             (dpath ? dpath : spath), strerror(errno));
958                         r = 1;
959                         /* Note that we should not set skipdir = 1 here. */
960                     }
961                 }
962                 if (VerboseOpt)
963                     logstd("%-32s mkdir-ok\n", (dpath ? dpath : spath));
964                 CountCopiedItems++;
965             } else {
966                 /*
967                  * Directory must be scanable by root for cpdup to
968                  * work.  We'll fix it later if the directory isn't
969                  * supposed to be readable ( which is why we fixup
970                  * st2.st_mode to match what we did ).
971                  */
972                 if ((st2.st_mode & 0700) != 0700) {
973                     hc_chmod(&DstHost, dpath, st2.st_mode | 0700);
974                     st2.st_mode |= 0700;
975                 }
976                 if (VerboseOpt >= 2)
977                     logstd("%s\n", dpath ? dpath : spath);
978             }
979         }
980
981         /*
982          * When copying a directory, stop if the source crosses a mount
983          * point.
984          */
985         if (sdevNo != (dev_t)-1 && stat1->st_dev != sdevNo)
986             skipdir = 1;
987         else
988             sdevNo = stat1->st_dev;
989
990         /*
991          * When copying a directory, stop if the destination crosses
992          * a mount point.
993          *
994          * The target directory will have been created and stat'd
995          * for st2 if it did not previously exist.   st2Valid is left
996          * as a flag.  If the stat failed st2 will still only have its
997          * default initialization.
998          *
999          * So we simply assume here that the directory is within the
1000          * current target mount if we had to create it (aka st2Valid is 0)
1001          * and we leave ddevNo alone.
1002          */
1003         if (st2Valid) {
1004             if (ddevNo != (dev_t)-1 && st2.st_dev != ddevNo)
1005                 skipdir = 1;
1006             else
1007                 ddevNo = st2.st_dev;
1008         }
1009
1010         if (!skipdir) {
1011             List *list = malloc(sizeof(List));
1012             Node *node;
1013
1014             if (DirShowOpt)
1015                 logstd("Scanning %s ...\n", spath);
1016             InitList(list);
1017             if (ScanDir(list, &SrcHost, spath, &CountSourceReadBytes, 0) == 0) {
1018                 node = NULL;
1019                 while ((node = IterateList(list, node, 0)) != NULL) {
1020                     char *nspath;
1021                     char *ndpath = NULL;
1022
1023                     nspath = mprintf("%s/%s", spath, node->no_Name);
1024                     if (dpath)
1025                         ndpath = mprintf("%s/%s", dpath, node->no_Name);
1026
1027                     info->spath = nspath;
1028                     info->dpath = ndpath;
1029                     info->sdevNo = sdevNo;
1030                     info->ddevNo = ddevNo;
1031                     if (depth < 0)
1032                         r += DoCopy(info, node->no_Stat, depth);
1033                     else
1034                         r += DoCopy(info, node->no_Stat, depth + 1);
1035                     free(nspath);
1036                     if (ndpath)
1037                         free(ndpath);
1038                     info->spath = NULL;
1039                     info->dpath = NULL;
1040                 }
1041
1042                 /*
1043                  * Remove files/directories from destination that do not appear
1044                  * in the source.
1045                  */
1046                 if (dpath && ScanDir(list, &DstHost, dpath,
1047                                      &CountTargetReadBytes, 3) == 0) {
1048                     node = NULL;
1049                     while ((node = IterateList(list, node, 3)) != NULL) {
1050                         /*
1051                          * If object does not exist in source or .cpignore
1052                          * then recursively remove it.
1053                          */
1054                         char *ndpath;
1055
1056                         ndpath = mprintf("%s/%s", dpath, node->no_Name);
1057                         RemoveRecur(ndpath, ddevNo, node->no_Stat);
1058                         free(ndpath);
1059                     }
1060                 }
1061             }
1062             ResetList(list);
1063             free(list);
1064         }
1065
1066         if (dpath && st2Valid) {
1067             struct timeval tv[2];
1068
1069             if (ForceOpt || !OwnerMatch(stat1, &st2))
1070                 hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid);
1071             if (stat1->st_mode != st2.st_mode)
1072                 hc_chmod(&DstHost, dpath, stat1->st_mode);
1073 #ifdef _ST_FLAGS_PRESENT_
1074             if (!FlagsMatch(stat1, &st2))
1075                 hc_chflags(&DstHost, dpath, stat1->st_flags);
1076 #endif
1077             if (ForceOpt || stat1->st_mtime != st2.st_mtime) {
1078                 bzero(tv, sizeof(tv));
1079                 tv[0].tv_sec = stat1->st_mtime;
1080                 tv[1].tv_sec = stat1->st_mtime;
1081                 hc_utimes(&DstHost, dpath, tv);
1082             }
1083         }
1084     } else if (dpath == NULL) {
1085         /*
1086          * If dpath is NULL, we are just updating the MD5
1087          */
1088 #ifndef NOMD5
1089         if (UseMD5Opt && S_ISREG(stat1->st_mode)) {
1090             mres = md5_check(spath, NULL);
1091
1092             if (VerboseOpt > 1) {
1093                 if (mres < 0)
1094                     logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1095                 else
1096                     logstd("%-32s md5-ok\n", (dpath) ? dpath : spath);
1097             } else if (!QuietOpt && mres < 0) {
1098                 logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1099             }
1100         }
1101 #endif
1102     } else if (S_ISREG(stat1->st_mode)) {
1103         char *path;
1104         char *hpath;
1105         int fd1;
1106         int fd2;
1107
1108         if (st2Valid)
1109                 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1110         else
1111                 path = mprintf("%s", dpath);
1112
1113         /*
1114          * Handle check failure message.
1115          */
1116 #ifndef NOMD5
1117         if (mres < 0)
1118             logerr("%-32s md5-CHECK-FAILED\n", (dpath) ? dpath : spath);
1119         else
1120 #endif
1121         if (fres < 0)
1122             logerr("%-32s fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
1123
1124         /*
1125          * Not quite ready to do the copy yet.  If UseHLPath is defined,
1126          * see if we can hardlink instead.
1127          *
1128          * If we can hardlink, and the target exists, we have to remove it
1129          * first or the hardlink will fail.  This can occur in a number of
1130          * situations but most typically when the '-f -H' combination is
1131          * used.
1132          */
1133         if (UseHLPath && (hpath = checkHLPath(stat1, spath, dpath)) != NULL) {
1134                 if (st2Valid)
1135                         xremove(&DstHost, dpath);
1136                 if (hc_link(&DstHost, hpath, dpath) == 0) {
1137                         ++CountLinkedItems;
1138                         if (VerboseOpt) {
1139                             logstd("%-32s hardlinked(-H)\n",
1140                                    (dpath ? dpath : spath));
1141                         }
1142                         free(hpath);
1143                         goto skip_copy;
1144                 }
1145                 /*
1146                  * Shucks, we may have hit a filesystem hard linking limit,
1147                  * we have to copy instead.
1148                  */
1149                 free(hpath);
1150         }
1151
1152         if ((fd1 = hc_open(&SrcHost, spath, O_RDONLY, 0)) >= 0) {
1153             if ((fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL, 0600)) < 0) {
1154                 /*
1155                  * There could be a .tmp file from a previously interrupted
1156                  * run, delete and retry.  Fail if we still can't get at it.
1157                  */
1158 #ifdef _ST_FLAGS_PRESENT_
1159                 hc_chflags(&DstHost, path, 0);
1160 #endif
1161                 hc_remove(&DstHost, path);
1162                 fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600);
1163             }
1164             if (fd2 >= 0) {
1165                 const char *op;
1166                 char *iobuf1 = malloc(GETIOSIZE);
1167                 int n;
1168
1169                 /*
1170                  * Matt: What about holes?
1171                  */
1172                 op = "read";
1173                 while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
1174                     op = "write";
1175                     if (hc_write(&DstHost, fd2, iobuf1, n) != n)
1176                         break;
1177                     op = "read";
1178                 }
1179                 hc_close(&DstHost, fd2);
1180                 if (n == 0) {
1181                     struct timeval tv[2];
1182
1183                     bzero(tv, sizeof(tv));
1184                     tv[0].tv_sec = stat1->st_mtime;
1185                     tv[1].tv_sec = stat1->st_mtime;
1186
1187                     if (DstRootPrivs || ChgrpAllowed(stat1->st_gid))
1188                         hc_chown(&DstHost, path, stat1->st_uid, stat1->st_gid);
1189                     hc_chmod(&DstHost, path, stat1->st_mode);
1190 #ifdef _ST_FLAGS_PRESENT_
1191                     if (stat1->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
1192                         hc_utimes(&DstHost, path, tv);
1193 #else
1194                     hc_utimes(&DstHost, path, tv);
1195 #endif
1196                     if (st2Valid && xrename(path, dpath, st2_flags) != 0) {
1197                         logerr("%-32s rename-after-copy failed: %s\n",
1198                             (dpath ? dpath : spath), strerror(errno)
1199                         );
1200                         ++r;
1201                     } else {
1202                         if (VerboseOpt)
1203                             logstd("%-32s copy-ok\n", (dpath ? dpath : spath));
1204 #ifdef _ST_FLAGS_PRESENT_
1205                         if (DstRootPrivs ? stat1->st_flags : stat1->st_flags & UF_SETTABLE)
1206                             hc_chflags(&DstHost, dpath, stat1->st_flags);
1207 #endif
1208                     }
1209 #ifdef _ST_FLAGS_PRESENT_
1210                     if ((stat1->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE)) == 0)
1211                         hc_utimes(&DstHost, dpath, tv);
1212 #endif
1213                     CountSourceReadBytes += size;
1214                     CountWriteBytes += size;
1215                     CountSourceBytes += size;
1216                     CountSourceItems++;
1217                     CountCopiedItems++;
1218                 } else {
1219                     logerr("%-32s %s failed: %s\n",
1220                         (dpath ? dpath : spath), op, strerror(errno)
1221                     );
1222                     hc_remove(&DstHost, path);
1223                     ++r;
1224                 }
1225                 free(iobuf1);
1226             } else {
1227                 logerr("%-32s create (uid %d, euid %d) failed: %s\n",
1228                     (dpath ? dpath : spath), getuid(), geteuid(),
1229                     strerror(errno)
1230                 );
1231                 ++r;
1232             }
1233             hc_close(&SrcHost, fd1);
1234         } else {
1235             logerr("%-32s copy: open failed: %s\n",
1236                 (dpath ? dpath : spath),
1237                 strerror(errno)
1238             );
1239             ++r;
1240         }
1241 skip_copy:
1242         free(path);
1243
1244         if (hln) {
1245             if (!r && hc_stat(&DstHost, dpath, &st2) == 0) {
1246                 hltsetdino(hln, st2.st_ino);
1247             } else {
1248                 hltdelete(hln);
1249                 hln = NULL;
1250             }
1251         }
1252     } else if (S_ISLNK(stat1->st_mode)) {
1253         char *link1 = malloc(GETLINKSIZE);
1254         char *link2 = malloc(GETLINKSIZE);
1255         char *path;
1256         int n1;
1257         int n2;
1258
1259         n1 = hc_readlink(&SrcHost, spath, link1, GETLINKSIZE - 1);
1260         if (st2Valid) {
1261                 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1262                 n2 = hc_readlink(&DstHost, dpath, link2, GETLINKSIZE - 1);
1263         } else {
1264                 path = mprintf("%s", dpath);
1265                 n2 = -1;
1266         }
1267         if (n1 >= 0) {
1268             if (ForceOpt || n1 != n2 || bcmp(link1, link2, n1) != 0) {
1269                 hc_umask(&DstHost, ~stat1->st_mode);
1270                 xremove(&DstHost, path);
1271                 link1[n1] = 0;
1272                 if (hc_symlink(&DstHost, link1, path) < 0) {
1273                       logerr("%-32s symlink (%s->%s) failed: %s\n",
1274                           (dpath ? dpath : spath), link1, path,
1275                           strerror(errno)
1276                       );
1277                       ++r;
1278                 } else {
1279                     if (DstRootPrivs || ChgrpAllowed(stat1->st_gid))
1280                         hc_lchown(&DstHost, path, stat1->st_uid, stat1->st_gid);
1281                     /*
1282                      * there is no lchmod() or lchflags(), we
1283                      * cannot chmod or chflags a softlink.
1284                      */
1285                     if (st2Valid && xrename(path, dpath, st2_flags) != 0) {
1286                         logerr("%-32s rename softlink (%s->%s) failed: %s\n",
1287                             (dpath ? dpath : spath),
1288                             path, dpath, strerror(errno));
1289                     } else if (VerboseOpt) {
1290                         logstd("%-32s softlink-ok\n", (dpath ? dpath : spath));
1291                     }
1292                     hc_umask(&DstHost, 000);
1293                     CountWriteBytes += n1;
1294                     CountCopiedItems++;
1295                 }
1296             } else {
1297                 if (VerboseOpt >= 3)
1298                     logstd("%-32s nochange", (dpath ? dpath : spath));
1299                 if (!OwnerMatch(stat1, &st2)) {
1300                     hc_lchown(&DstHost, dpath, stat1->st_uid, stat1->st_gid);
1301                     if (VerboseOpt >= 3)
1302                         logstd(" (uid/gid differ)");
1303                 }
1304                 if (VerboseOpt >= 3)
1305                     logstd("\n");
1306             }
1307             CountSourceBytes += n1;
1308             CountSourceReadBytes += n1;
1309             if (n2 > 0)
1310                 CountTargetReadBytes += n2;
1311             CountSourceItems++;
1312         } else {
1313             r = 1;
1314             logerr("%-32s softlink-failed\n", (dpath ? dpath : spath));
1315         }
1316         free(link1);
1317         free(link2);
1318         free(path);
1319     } else if ((S_ISCHR(stat1->st_mode) || S_ISBLK(stat1->st_mode)) && DeviceOpt) {
1320         char *path = NULL;
1321
1322         if (ForceOpt ||
1323             st2Valid == 0 ||
1324             stat1->st_mode != st2.st_mode ||
1325             stat1->st_rdev != st2.st_rdev ||
1326             !OwnerMatch(stat1, &st2)
1327         ) {
1328             if (st2Valid) {
1329                 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1330                 xremove(&DstHost, path);
1331             } else {
1332                 path = mprintf("%s", dpath);
1333             }
1334
1335             if (hc_mknod(&DstHost, path, stat1->st_mode, stat1->st_rdev) == 0) {
1336                 hc_chmod(&DstHost, path, stat1->st_mode);
1337                 hc_chown(&DstHost, path, stat1->st_uid, stat1->st_gid);
1338                 if (st2Valid)
1339                         xremove(&DstHost, dpath);
1340                 if (st2Valid && xrename(path, dpath, st2_flags) != 0) {
1341                     logerr("%-32s dev-rename-after-create failed: %s\n",
1342                         (dpath ? dpath : spath),
1343                         strerror(errno)
1344                     );
1345                 } else if (VerboseOpt) {
1346                     logstd("%-32s dev-ok\n", (dpath ? dpath : spath));
1347                 }
1348                 CountCopiedItems++;
1349             } else {
1350                 r = 1;
1351                 logerr("%-32s dev failed: %s\n",
1352                     (dpath ? dpath : spath), strerror(errno)
1353                 );
1354             }
1355         } else {
1356             if (VerboseOpt >= 3)
1357                 logstd("%-32s nochange\n", (dpath ? dpath : spath));
1358         }
1359         if (path)
1360                 free(path);
1361         CountSourceItems++;
1362     }
1363 done:
1364     if (hln) {
1365         if (hln->dino == (ino_t)-1) {
1366             hltdelete(hln);
1367             /*hln = NULL; unneeded */
1368         } else {
1369             hltrels(hln);
1370         }
1371     }
1372     return (r);
1373 }
1374
1375 int
1376 ScanDir(List *list, struct HostConf *host, const char *path,
1377         int64_t *CountReadBytes, int n)
1378 {
1379     DIR *dir;
1380     struct HostConf *cphost;
1381     struct HCDirEntry *den;
1382     struct stat *statptr;
1383
1384     if (n == 0) {
1385         /*
1386          * scan .cpignore file for files/directories to ignore
1387          * (only in the source directory, i.e. if n == 0).
1388          */
1389         if (UseCpFile) {
1390             int fd;
1391             int nread;
1392             int bufused;
1393             char *buf = malloc(GETBUFSIZE);
1394             char *nl, *next;
1395             char *fpath;
1396
1397             if (UseCpFile[0] == '/') {
1398                 fpath = mprintf("%s", UseCpFile);
1399                 cphost = NULL;
1400             } else {
1401                 fpath = mprintf("%s/%s", path, UseCpFile);
1402                 AddList(list, strrchr(fpath, '/') + 1, 1, NULL);
1403                 cphost = host;
1404             }
1405             fd = hc_open(cphost, fpath, O_RDONLY, 0);
1406             if (fd >= 0) {
1407                 bufused = 0;
1408                 while ((nread = hc_read(cphost, fd, buf + bufused,
1409                         GETBUFSIZE - bufused - 1)) > 0) {
1410                     *CountReadBytes += nread;
1411                     bufused += nread;
1412                     buf[bufused] = 0;
1413                     for (next = buf; (nl = strchr(next, '\n')); next = nl+1) {
1414                         *nl = 0;
1415                         AddList(list, next, 1, NULL);
1416                     }
1417                     bufused = strlen(next);
1418                     if (bufused)
1419                         bcopy(next, buf, bufused);
1420                 }
1421                 if (bufused) {
1422                     /* last line has no trailing newline */
1423                     buf[bufused] = 0;
1424                     AddList(list, buf, 1, NULL);
1425                 }
1426                 hc_close(cphost, fd);
1427             }
1428             free(fpath);
1429             free(buf);
1430         }
1431
1432         /*
1433          * Automatically exclude MD5CacheFile that we create on the
1434          * source from the copy to the destination.
1435          *
1436          * Automatically exclude a FSMIDCacheFile on the source that
1437          * would otherwise overwrite the one we maintain on the target.
1438          */
1439         if (UseMD5Opt)
1440             AddList(list, MD5CacheFile, 1, NULL);
1441         if (UseFSMIDOpt)
1442             AddList(list, FSMIDCacheFile, 1, NULL);
1443     }
1444
1445     if ((dir = hc_opendir(host, path)) == NULL)
1446         return (1);
1447     while ((den = hc_readdir(host, dir, &statptr)) != NULL) {
1448         /*
1449          * ignore . and ..
1450          */
1451         if (strcmp(den->d_name, ".") != 0 && strcmp(den->d_name, "..") != 0) {
1452              if (UseCpFile && UseCpFile[0] == '/') {
1453                  if (CheckList(list, path, den->d_name) == 0)
1454                         continue;
1455              }
1456              AddList(list, den->d_name, n, statptr);
1457         }
1458     }
1459     hc_closedir(host, dir);
1460
1461     return (0);
1462 }
1463
1464 /*
1465  * RemoveRecur()
1466  */
1467
1468 static void
1469 RemoveRecur(const char *dpath, dev_t devNo, struct stat *dstat)
1470 {
1471     struct stat st;
1472
1473     if (dstat == NULL) {
1474         if (hc_lstat(&DstHost, dpath, &st) == 0)
1475             dstat = &st;
1476     }
1477     if (dstat != NULL) {
1478         if (devNo == (dev_t)-1)
1479             devNo = dstat->st_dev;
1480         if (dstat->st_dev == devNo) {
1481             if (S_ISDIR(dstat->st_mode)) {
1482                 DIR *dir;
1483
1484                 if ((dir = hc_opendir(&DstHost, dpath)) != NULL) {
1485                     List *list = malloc(sizeof(List));
1486                     Node *node = NULL;
1487                     struct HCDirEntry *den;
1488
1489                     InitList(list);
1490                     while ((den = hc_readdir(&DstHost, dir, &dstat)) != NULL) {
1491                         if (strcmp(den->d_name, ".") == 0)
1492                             continue;
1493                         if (strcmp(den->d_name, "..") == 0)
1494                             continue;
1495                         AddList(list, den->d_name, 3, dstat);
1496                     }
1497                     hc_closedir(&DstHost, dir);
1498                     while ((node = IterateList(list, node, 3)) != NULL) {
1499                         char *ndpath;
1500
1501                         ndpath = mprintf("%s/%s", dpath, node->no_Name);
1502                         RemoveRecur(ndpath, devNo, node->no_Stat);
1503                         free(ndpath);
1504                     }
1505                     ResetList(list);
1506                     free(list);
1507                 }
1508                 if (AskConfirmation && NoRemoveOpt == 0) {
1509                     if (YesNo(dpath)) {
1510                         if (xrmdir(&DstHost, dpath) < 0) {
1511                             logerr("%-32s rmdir failed: %s\n",
1512                                 dpath, strerror(errno)
1513                             );
1514                         }
1515                         CountRemovedItems++;
1516                     }
1517                 } else {
1518                     if (NoRemoveOpt) {
1519                         if (VerboseOpt)
1520                             logstd("%-32s not-removed\n", dpath);
1521                     } else if (xrmdir(&DstHost, dpath) == 0) {
1522                         if (VerboseOpt)
1523                             logstd("%-32s rmdir-ok\n", dpath);
1524                         CountRemovedItems++;
1525                     } else {
1526                         logerr("%-32s rmdir failed: %s\n",
1527                             dpath, strerror(errno)
1528                         );
1529                     }
1530                 }
1531             } else {
1532                 if (AskConfirmation && NoRemoveOpt == 0) {
1533                     if (YesNo(dpath)) {
1534                         if (xremove(&DstHost, dpath) < 0) {
1535                             logerr("%-32s remove failed: %s\n",
1536                                 dpath, strerror(errno)
1537                             );
1538                         }
1539                         CountRemovedItems++;
1540                     }
1541                 } else {
1542                     if (NoRemoveOpt) {
1543                         if (VerboseOpt)
1544                             logstd("%-32s not-removed\n", dpath);
1545                     } else if (xremove(&DstHost, dpath) == 0) {
1546                         if (VerboseOpt)
1547                             logstd("%-32s remove-ok\n", dpath);
1548                         CountRemovedItems++;
1549                     } else {
1550                         logerr("%-32s remove failed: %s\n",
1551                             dpath, strerror(errno)
1552                         );
1553                     }
1554                 }
1555             }
1556         }
1557     }
1558 }
1559
1560 static void
1561 InitList(List *list)
1562 {
1563     bzero(list, sizeof(List));
1564     list->li_Node.no_Next = &list->li_Node;
1565 }
1566
1567 static void
1568 ResetList(List *list)
1569 {
1570     Node *node;
1571
1572     while ((node = list->li_Node.no_Next) != &list->li_Node) {
1573         list->li_Node.no_Next = node->no_Next;
1574         if (node->no_Stat != NULL)
1575             free(node->no_Stat);
1576         free(node);
1577     }
1578     InitList(list);
1579 }
1580
1581 static Node *
1582 IterateList(List *list, Node *node, int n)
1583 {
1584     if (node == NULL)
1585         node = list->li_Node.no_Next;
1586     else
1587         node = node->no_Next;
1588     while (node->no_Value != n && node != &list->li_Node)
1589         node = node->no_Next;
1590     return (node == &list->li_Node ? NULL : node);
1591 }
1592
1593 static int
1594 AddList(List *list, const char *name, int n, struct stat *st)
1595 {
1596     Node *node;
1597     int hv;
1598
1599     /*
1600      * Scan against wildcards.  Only a node value of 1 can be a wildcard
1601      * ( usually scanned from .cpignore )
1602      */
1603     for (node = list->li_Hash[0]; node; node = node->no_HNext) {
1604         if (strcmp(name, node->no_Name) == 0 ||
1605             (n != 1 && node->no_Value == 1 &&
1606             fnmatch(node->no_Name, name, 0) == 0)
1607         ) {
1608             return(node->no_Value);
1609         }
1610     }
1611
1612     /*
1613      * Look for exact match
1614      */
1615
1616     hv = shash(name);
1617     for (node = list->li_Hash[hv]; node; node = node->no_HNext) {
1618         if (strcmp(name, node->no_Name) == 0) {
1619             return(node->no_Value);
1620         }
1621     }
1622     node = malloc(sizeof(Node) + strlen(name) + 1);
1623     if (node == NULL)
1624         fatal("out of memory");
1625
1626     node->no_Next = list->li_Node.no_Next;
1627     list->li_Node.no_Next = node;
1628
1629     node->no_HNext = list->li_Hash[hv];
1630     list->li_Hash[hv] = node;
1631
1632     strcpy(node->no_Name, name);
1633     node->no_Value = n;
1634     node->no_Stat = st;
1635
1636     return(n);
1637 }
1638
1639 /*
1640  * Match against n=1 (cpignore) entries
1641  *
1642  * Returns 0 on match, non-zero if no match
1643  */
1644 static int
1645 CheckList(List *list, const char *path, const char *name)
1646 {
1647     char *fpath = NULL;
1648     Node *node;
1649     int hv;
1650
1651     if (asprintf(&fpath, "%s/%s", path, name) < 0)
1652         fatal("out of memory");
1653
1654     /*
1655      * Scan against wildcards.  Only a node value of 1 can be a wildcard
1656      * ( usually scanned from .cpignore )
1657      */
1658     for (node = list->li_Hash[0]; node; node = node->no_HNext) {
1659         if (node->no_Value != 1)
1660                 continue;
1661         if (fnmatch(node->no_Name, fpath, 0) == 0) {
1662                 free(fpath);
1663                 return 0;
1664         }
1665     }
1666
1667     /*
1668      * Look for exact match
1669      */
1670     hv = shash(fpath);
1671     for (node = list->li_Hash[hv]; node; node = node->no_HNext) {
1672         if (node->no_Value != 1)
1673                 continue;
1674         if (strcmp(fpath, node->no_Name) == 0) {
1675                 free(fpath);
1676                 return 0;
1677         }
1678     }
1679
1680     free(fpath);
1681     return 1;
1682 }
1683
1684 static int
1685 shash(const char *s)
1686 {
1687     int hv;
1688
1689     hv = 0xA4FB3255;
1690
1691     while (*s) {
1692         if (*s == '*' || *s == '?' ||
1693             *s == '{' || *s == '}' ||
1694             *s == '[' || *s == ']' ||
1695             *s == '|'
1696         ) {
1697             return(0);
1698         }
1699         hv = (hv << 5) ^ *s ^ (hv >> 23);
1700         ++s;
1701     }
1702     return(((hv >> 16) ^ hv) & HMASK);
1703 }
1704
1705 static int
1706 YesNo(const char *path)
1707 {
1708     int ch, first;
1709
1710     fprintf(stderr, "remove %s (Yes/No) [No]? ", path);
1711     fflush(stderr);
1712
1713     first = ch = getchar();
1714     while (ch != '\n' && ch != EOF)
1715         ch = getchar();
1716     return ((first == 'y' || first == 'Y'));
1717 }
1718
1719 /*
1720  * xrename() - rename with override
1721  *
1722  *      If the rename fails, attempt to override st_flags on the
1723  *      destination and rename again.  If that fails too, try to
1724  *      set the flags back the way they were and give up.
1725  */
1726
1727 static int
1728 xrename(const char *src, const char *dst, u_long flags)
1729 {
1730     int r;
1731
1732     if ((r = hc_rename(&DstHost, src, dst)) < 0) {
1733 #ifdef _ST_FLAGS_PRESENT_
1734         hc_chflags(&DstHost, dst, 0);
1735         if ((r = hc_rename(&DstHost, src, dst)) < 0)
1736                 hc_chflags(&DstHost, dst, flags);
1737 #endif
1738     }
1739     return(r);
1740 }
1741
1742 static int
1743 xlink(const char *src, const char *dst, u_long flags)
1744 {
1745     int r;
1746 #ifdef _ST_FLAGS_PRESENT_
1747     int e;
1748 #endif
1749
1750     if ((r = hc_link(&DstHost, src, dst)) < 0) {
1751 #ifdef _ST_FLAGS_PRESENT_
1752         hc_chflags(&DstHost, src, 0);
1753         r = hc_link(&DstHost, src, dst);
1754         e = errno;
1755         hc_chflags(&DstHost, src, flags);
1756         errno = e;
1757 #endif
1758     }
1759     if (r == 0)
1760             ++CountLinkedItems;
1761     return(r);
1762 }
1763
1764 static int
1765 xremove(struct HostConf *host, const char *path)
1766 {
1767     int res;
1768
1769     res = hc_remove(host, path);
1770 #ifdef _ST_FLAGS_PRESENT_
1771     if (res == -EPERM) {
1772         hc_chflags(host, path, 0);
1773         res = hc_remove(host, path);
1774     }
1775 #endif
1776     return(res);
1777 }
1778
1779 static int
1780 xrmdir(struct HostConf *host, const char *path)
1781 {
1782     int res;
1783
1784     res = hc_rmdir(host, path);
1785 #ifdef _ST_FLAGS_PRESENT_
1786     if (res == -EPERM) {
1787         hc_chflags(host, path, 0);
1788         res = hc_rmdir(host, path);
1789     }
1790 #endif
1791     return(res);
1792 }