Finish up cpdup. Bump the protocol version to 2 and refuse to talk to
[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.25 2008/04/16 17:38:19 dillon Exp $
49  */
50
51 /*-
52  * Example: cc -O cpdup.c -o cpdup -lmd
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 MAXDEPTH        32      /* max copy depth for thread */
68 #define GETBUFSIZE      8192
69 #define GETPATHSIZE     2048
70 #define GETLINKSIZE     1024
71 #define GETIOSIZE       65536
72
73 #ifndef _ST_FLAGS_PRESENT_
74 #define st_flags        st_mode
75 #endif
76
77 typedef struct Node {
78     struct Node *no_Next;
79     struct Node *no_HNext;
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[0];
97 };
98
99 typedef struct copy_info {
100         char *spath;
101         char *dpath;
102         dev_t sdevNo;
103         dev_t ddevNo;
104 #ifdef USE_PTHREADS
105         struct copy_info *parent;
106         pthread_cond_t cond;
107         int children;
108         int r;
109 #endif
110 } *copy_info_t;
111
112 struct hlink *hltable[HLSIZE];
113
114 void RemoveRecur(const char *dpath, dev_t devNo);
115 void InitList(List *list);
116 void ResetList(List *list);
117 int AddList(List *list, const char *name, int n);
118 static struct hlink *hltlookup(struct stat *);
119 static struct hlink *hltadd(struct stat *, const char *);
120 static char *checkHLPath(struct stat *st, const char *spath, const char *dpath);
121 static int validate_check(const char *spath, const char *dpath);
122 static int shash(const char *s);
123 static void hltdelete(struct hlink *);
124 static void hltsetdino(struct hlink *, ino_t);
125 int YesNo(const char *path);
126 static int xrename(const char *src, const char *dst, u_long flags);
127 static int xlink(const char *src, const char *dst, u_long flags);
128 int WildCmp(const char *s1, const char *s2);
129 static int DoCopy(copy_info_t info, int depth);
130
131 int AskConfirmation = 1;
132 int SafetyOpt = 1;
133 int ForceOpt;
134 int DeviceOpt = 1;
135 int VerboseOpt;
136 int QuietOpt;
137 int NoRemoveOpt;
138 int UseMD5Opt;
139 int UseFSMIDOpt;
140 int SummaryOpt;
141 int CompressOpt;
142 int SlaveOpt;
143 int EnableDirectoryRetries;
144 int DstBaseLen;
145 int ValidateOpt;
146 int CurParallel;
147 int MaxParallel = -1;
148 int HardLinkCount;
149 const char *UseCpFile;
150 const char *UseHLPath;
151 const char *MD5CacheFile;
152 const char *FSMIDCacheFile;
153
154 int64_t CountSourceBytes;
155 int64_t CountSourceItems;
156 int64_t CountCopiedItems;
157 int64_t CountSourceReadBytes;
158 int64_t CountTargetReadBytes;
159 int64_t CountWriteBytes;
160 int64_t CountRemovedItems;
161 int64_t CountLinkedItems;
162
163 struct HostConf SrcHost;
164 struct HostConf DstHost;
165
166 #if USE_PTHREADS
167 pthread_mutex_t MasterMutex;
168 #endif
169
170 int
171 main(int ac, char **av)
172 {
173     int i;
174     char *src = NULL;
175     char *dst = NULL;
176     char *ptr;
177     struct timeval start;
178     struct copy_info info;
179
180     signal(SIGPIPE, SIG_IGN);
181
182 #if USE_PTHREADS
183     pthread_mutex_init(&SrcHost.read_mutex, NULL);
184     pthread_mutex_init(&DstHost.read_mutex, NULL);
185     pthread_mutex_init(&MasterMutex, NULL);
186     pthread_mutex_lock(&MasterMutex);
187 #endif
188
189     gettimeofday(&start, NULL);
190     for (i = 1; i < ac; ++i) {
191         int v = 1;
192
193         ptr = av[i];
194         if (*ptr != '-') { 
195             if (src == NULL) {
196                 src = ptr;
197             } else if (dst == NULL) {
198                 dst = ptr;
199             } else {
200                 fatal("too many arguments");
201                 /* not reached */
202             }
203             continue;
204         }
205         ptr += 2;
206
207         if (*ptr)
208             v = strtol(ptr, NULL, 0);
209
210         switch(ptr[-1]) {
211         case 'C':
212             CompressOpt = 1;
213             break;
214         case 'v':
215             VerboseOpt = 1;
216             while (*ptr == 'v') {
217                 ++VerboseOpt;
218                 ++ptr;
219             }
220             if (*ptr >= '0' && *ptr <= '9')
221                 VerboseOpt = strtol(ptr, NULL, 0);
222             break;
223         case 'l':
224             setlinebuf(stdout);
225             setlinebuf(stderr);
226             break;
227         case 'V':
228             ValidateOpt = v;
229             break;
230         case 'I':
231             SummaryOpt = v;
232             break;
233         case 'o':
234             NoRemoveOpt = v;
235             break;
236         case 'x':
237             UseCpFile = ".cpignore";
238             break;
239         case 'X':
240             UseCpFile = (*ptr) ? ptr : av[++i];
241             break;
242         case 'H':
243             UseHLPath = (*ptr) ? ptr : av[++i];
244             break;
245         case 'S':
246             SlaveOpt = v;
247             break;
248         case 'f':
249             ForceOpt = v;
250             break;
251         case 'i':
252             AskConfirmation = v;
253             break;
254         case 'j':
255             DeviceOpt = v;
256             break;
257         case 'p':
258             MaxParallel = v;
259             break;
260         case 's':
261             SafetyOpt = v;
262             break;
263         case 'q':
264             QuietOpt = v;
265             break;
266         case 'k':
267             UseFSMIDOpt = v;
268             FSMIDCacheFile = ".FSMID.CHECK";
269             break;
270         case 'K':
271             UseFSMIDOpt = v;
272             FSMIDCacheFile = av[++i];
273             break;
274         case 'M':
275             UseMD5Opt = v;
276             MD5CacheFile = av[++i];
277             break;
278         case 'm':
279             UseMD5Opt = v;
280             MD5CacheFile = ".MD5.CHECKSUMS";
281             break;
282         case 'u':
283             setvbuf(stdout, NULL, _IOLBF, 0);
284             break;
285         default:
286             fatal("illegal option: %s\n", ptr - 2);
287             /* not reached */
288             break;
289         }
290     }
291
292     /*
293      * If we are told to go into slave mode, run the HC protocol
294      */
295     if (SlaveOpt) {
296         hc_slave(0, 1);
297         exit(0);
298     }
299
300     /*
301      * Extract the source and/or/neither target [user@]host and
302      * make any required connections.
303      */
304     if (src && (ptr = strchr(src, ':')) != NULL) {
305         asprintf(&SrcHost.host, "%*.*s", ptr - src, ptr - src, src);
306         src = ptr + 1;
307         if (UseCpFile) {
308             fprintf(stderr, "The cpignore options are not currently supported for remote sources\n");
309             exit(1);
310         }
311         if (UseMD5Opt) {
312             fprintf(stderr, "The MD5 options are not currently supported for remote sources\n");
313             exit(1);
314         }
315         if (hc_connect(&SrcHost) < 0)
316             exit(1);
317     }
318     if (dst && (ptr = strchr(dst, ':')) != NULL) {
319         asprintf(&DstHost.host, "%*.*s", ptr - dst, ptr - dst, dst);
320         dst = ptr + 1;
321         if (UseFSMIDOpt) {
322             fprintf(stderr, "The FSMID options are not currently supported for remote targets\n");
323             exit(1);
324         }
325         if (hc_connect(&DstHost) < 0)
326             exit(1);
327     }
328
329     /*
330      * dst may be NULL only if -m option is specified,
331      * which forces an update of the MD5 checksums
332      */
333     if (dst == NULL && UseMD5Opt == 0) {
334         fatal(NULL);
335         /* not reached */
336     }
337 #if USE_PTHREADS
338     info.r = 0;
339     info.children = 0;
340     pthread_cond_init(&info.cond, NULL);
341 #endif
342     if (dst) {
343         DstBaseLen = strlen(dst);
344         info.spath = src;
345         info.dpath = dst;
346         info.sdevNo = (dev_t)-1;
347         info.ddevNo = (dev_t)-1;
348         i = DoCopy(&info, -1);
349     } else {
350         info.spath = src;
351         info.dpath = NULL;
352         info.sdevNo = (dev_t)-1;
353         info.ddevNo = (dev_t)-1;
354         i = DoCopy(&info, -1);
355     }
356 #if USE_PTHREADS
357     pthread_cond_destroy(&info.cond);
358 #endif
359 #ifndef NOMD5
360     md5_flush();
361 #endif
362     fsmid_flush();
363
364     if (SummaryOpt && i == 0) {
365         long duration;
366         struct timeval end;
367
368         gettimeofday(&end, NULL);
369 #if 0
370         /* don't count stat's in our byte statistics */
371         CountSourceBytes += sizeof(struct stat) * CountSourceItems;
372         CountSourceReadBytes += sizeof(struct stat) * CountSourceItems;
373         CountWriteBytes +=  sizeof(struct stat) * CountCopiedItems;
374         CountWriteBytes +=  sizeof(struct stat) * CountRemovedItems;
375 #endif
376
377         duration = end.tv_sec - start.tv_sec;
378         duration *= 1000000;
379         duration += end.tv_usec - start.tv_usec;
380         if (duration == 0) duration = 1;
381         logstd("cpdup completed successfully\n");
382         logstd("%lld bytes source, %lld src bytes read, %lld tgt bytes read\n"
383                "%lld bytes written (%.1fX speedup)\n",
384             (long long)CountSourceBytes,
385             (long long)CountSourceReadBytes,
386             (long long)CountTargetReadBytes,
387             (long long)CountWriteBytes,
388             ((double)CountSourceBytes * 2.0) / ((double)(CountSourceReadBytes + CountTargetReadBytes + CountWriteBytes)));
389         logstd("%lld source items, %lld items copied, %lld items linked, "
390                "%lld things deleted\n",
391             (long long)CountSourceItems,
392             (long long)CountCopiedItems,
393             (long long)CountLinkedItems,
394             (long long)CountRemovedItems);
395         logstd("%.1f seconds %5d Kbytes/sec synced %5d Kbytes/sec scanned\n",
396             (float)duration / (float)1000000,
397             (long)((long)1000000 * (CountSourceReadBytes + CountTargetReadBytes + CountWriteBytes) / duration  / 1024.0),
398             (long)((long)1000000 * CountSourceBytes / duration / 1024.0));
399     }
400     exit((i == 0) ? 0 : 1);
401 }
402
403 static struct hlink *
404 hltlookup(struct stat *stp)
405 {
406     struct timespec ts = { 0, 100000 };
407     struct hlink *hl;
408     int n;
409
410     n = stp->st_ino & HLMASK;
411
412 #if USE_PTHREADS
413 again:
414 #endif
415     for (hl = hltable[n]; hl; hl = hl->next) {
416         if (hl->ino == stp->st_ino) {
417 #if USE_PTHREADS
418             /*
419              * If the hl entry is still in the process of being created
420              * by another thread we have to wait until it has either been
421              * deleted or completed.
422              */
423             if (hl->refs) {
424                 pthread_mutex_unlock(&MasterMutex);
425                 nanosleep(&ts, NULL);
426                 pthread_mutex_lock(&MasterMutex);
427                 goto again;
428             }
429 #endif
430             ++hl->refs;
431             return hl;
432         }
433     }
434
435     return NULL;
436 }
437
438 static struct hlink *
439 hltadd(struct stat *stp, const char *path)
440 {
441     struct hlink *new;
442     int plen = strlen(path);
443     int n;
444
445     new = malloc(offsetof(struct hlink, name[plen + 1]));
446     if (new == NULL) {
447         fprintf(stderr, "out of memory\n");
448         exit(EXIT_FAILURE);
449     }
450     ++HardLinkCount;
451
452     /* initialize and link the new element into the table */
453     new->ino = stp->st_ino;
454     new->dino = (ino_t)-1;
455     new->refs = 1;
456     bcopy(path, new->name, plen + 1);
457     new->nlinked = 1;
458     new->prev = NULL;
459     n = stp->st_ino & HLMASK;
460     new->next = hltable[n];
461     if (hltable[n])
462         hltable[n]->prev = new;
463     hltable[n] = new;
464
465     return new;
466 }
467
468 static void
469 hltsetdino(struct hlink *hl, ino_t inum)
470 {
471     hl->dino = inum;
472 }
473
474 static void
475 hltdelete(struct hlink *hl)
476 {
477     assert(hl->refs == 1);
478     --hl->refs;
479     if (hl->prev) {
480         if (hl->next)
481             hl->next->prev = hl->prev;
482         hl->prev->next = hl->next;
483     } else {
484         if (hl->next)
485             hl->next->prev = NULL;
486
487         hltable[hl->ino & HLMASK] = hl->next;
488     }
489     --HardLinkCount;
490     free(hl);
491 }
492
493 static void
494 hltrels(struct hlink *hl)
495 {
496     assert(hl->refs == 1);
497     --hl->refs;
498 }
499
500 /*
501  * If UseHLPath is defined check to see if the file in question is
502  * the same as the source file, and if it is return a pointer to the
503  * -H path based file for hardlinking.  Else return NULL.
504  */
505 static char *
506 checkHLPath(struct stat *st1, const char *spath, const char *dpath)
507 {
508     struct stat sthl;
509     char *hpath;
510     int error;
511
512     asprintf(&hpath, "%s%s", UseHLPath, dpath + DstBaseLen);
513
514     /*
515      * stat info matches ?
516      */
517     if (hc_stat(&DstHost, hpath, &sthl) < 0 ||
518         st1->st_size != sthl.st_size ||
519         st1->st_uid != sthl.st_uid ||
520         st1->st_gid != sthl.st_gid ||
521         st1->st_mtime != sthl.st_mtime
522     ) {
523         free(hpath);
524         return(NULL);
525     }
526
527     /*
528      * If ForceOpt or ValidateOpt is set we have to compare the files
529      */
530     if (ForceOpt || ValidateOpt) {
531         error = validate_check(spath, hpath);
532         if (error) {
533             free(hpath);
534             hpath = NULL;
535         }
536     }
537     return(hpath);
538 }
539
540 /*
541  * Return 0 if the contents of the file <spath> matches the contents of
542  * the file <dpath>.
543  */
544 static int
545 validate_check(const char *spath, const char *dpath)
546 {
547     int error;
548     int fd1;
549     int fd2;
550
551     fd1 = hc_open(&SrcHost, spath, O_RDONLY, 0);
552     fd2 = hc_open(&DstHost, dpath, O_RDONLY, 0);
553     error = -1;
554
555     if (fd1 >= 0 && fd2 >= 0) {
556         int n;
557         int x;
558         char *iobuf1 = malloc(GETIOSIZE);
559         char *iobuf2 = malloc(GETIOSIZE);
560
561         while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
562             CountSourceReadBytes += n;
563             x = hc_read(&DstHost, fd2, iobuf2, GETIOSIZE);
564             if (x > 0)
565                     CountTargetReadBytes += x;
566             if (x != n)
567                 break;
568             if (bcmp(iobuf1, iobuf2, n) != 0)
569                 break;
570         }
571         free(iobuf1);
572         free(iobuf2);
573         if (n == 0)
574             error = 0;
575     }
576     if (fd1 >= 0)
577         hc_close(&SrcHost, fd1);
578     if (fd2 >= 0)
579         hc_close(&DstHost, fd2);
580     return (error);
581 }
582 #if USE_PTHREADS
583
584 static void *
585 DoCopyThread(void *arg)
586 {
587     copy_info_t cinfo = arg;
588     char *spath = cinfo->spath;
589     char *dpath = cinfo->dpath;
590     int r;
591  
592     r = pthread_detach(pthread_self());
593     assert(r == 0);
594     pthread_cond_init(&cinfo->cond, NULL);
595     pthread_mutex_lock(&MasterMutex);
596     cinfo->r += DoCopy(cinfo, 0);
597     /* cinfo arguments invalid on return */
598     --cinfo->parent->children;
599     --CurParallel;
600     pthread_cond_signal(&cinfo->parent->cond);
601     pthread_mutex_unlock(&MasterMutex);
602     free(spath);
603     if (dpath)
604         free(dpath);
605     pthread_cond_destroy(&cinfo->cond);
606     free(cinfo);
607     hcc_free_trans(&SrcHost);
608     hcc_free_trans(&DstHost);
609     return(NULL);
610 }
611
612 #endif
613
614 int
615 DoCopy(copy_info_t info, int depth)
616 {
617     const char *spath = info->spath;
618     const char *dpath = info->dpath;
619     dev_t sdevNo = info->sdevNo;
620     dev_t ddevNo = info->ddevNo;
621     struct stat st1;
622     struct stat st2;
623     int r, mres, fres, st2Valid;
624     struct hlink *hln;
625     List *list = malloc(sizeof(List));
626     u_int64_t size;
627
628     InitList(list);
629     r = mres = fres = st2Valid = 0;
630     size = 0;
631     hln = NULL;
632
633     if (hc_lstat(&SrcHost, spath, &st1) != 0) {
634         r = 0;
635         goto done;
636     }
637     st2.st_mode = 0;    /* in case lstat fails */
638     st2.st_flags = 0;   /* in case lstat fails */
639     if (dpath && hc_lstat(&DstHost, dpath, &st2) == 0)
640         st2Valid = 1;
641
642     if (S_ISREG(st1.st_mode)) {
643         size = st1.st_size;
644     }
645
646     /*
647      * Handle hardlinks
648      */
649
650     if (S_ISREG(st1.st_mode) && st1.st_nlink > 1 && dpath) {
651         if ((hln = hltlookup(&st1)) != NULL) {
652             hln->nlinked++;
653
654             if (st2Valid) {
655                 if (st2.st_ino == hln->dino) {
656                     /*
657                      * hard link is already correct, nothing to do
658                      */
659                     if (VerboseOpt >= 3)
660                         logstd("%-32s nochange\n", (dpath) ? dpath : spath);
661                     if (hln->nlinked == st1.st_nlink) {
662                         hltdelete(hln);
663                         hln = NULL;
664                     }
665                     CountSourceItems++;
666                     r = 0;
667                     goto done;
668                 } else {
669                     /*
670                      * hard link is not correct, attempt to unlink it
671                      */
672                     if (hc_remove(&DstHost, dpath) < 0) {
673                         logerr("%-32s hardlink: unable to unlink: %s\n", 
674                             ((dpath) ? dpath : spath), strerror(errno));
675                         hltdelete(hln);
676                         hln = NULL;
677                         ++r;
678                         goto done;
679                     }
680                 }
681             }
682
683             if (xlink(hln->name, dpath, st1.st_flags) < 0) {
684                 int tryrelink = (errno == EMLINK);
685                 logerr("%-32s hardlink: unable to link to %s: %s\n",
686                     (dpath ? dpath : spath), hln->name, strerror(errno)
687                 );
688                 hltdelete(hln);
689                 hln = NULL;
690                 if (tryrelink) {
691                     logerr("%-20s hardlink: will attempt to copy normally\n");
692                     goto relink;
693                 }
694                 ++r;
695             } else {
696                 if (hln->nlinked == st1.st_nlink) {
697                     hltdelete(hln);
698                     hln = NULL;
699                 }
700                 if (r == 0) {
701                     if (VerboseOpt) {
702                         logstd("%-32s hardlink: %s\n", 
703                             (dpath ? dpath : spath),
704                             (st2Valid ? "relinked" : "linked")
705                         );
706                     }
707                     CountSourceItems++;
708                     CountCopiedItems++;
709                     r = 0;
710                     goto done;
711                 }
712             }
713         } else {
714             /*
715              * first instance of hardlink must be copied normally
716              */
717 relink:
718             hln = hltadd(&st1, dpath);
719         }
720     }
721
722     /*
723      * Do we need to copy the file/dir/link/whatever?  Early termination
724      * if we do not.  Always redo links.  Directories are always traversed
725      * except when the FSMID options are used.
726      *
727      * NOTE: st2Valid is true only if dpath != NULL *and* dpath stats good.
728      */
729
730     if (
731         st2Valid
732         && st1.st_mode == st2.st_mode
733 #ifdef _ST_FLAGS_PRESENT_
734         && st1.st_flags == st2.st_flags
735 #endif
736     ) {
737         if (S_ISLNK(st1.st_mode) || S_ISDIR(st1.st_mode)) {
738             /*
739              * If FSMID tracking is turned on we can avoid recursing through
740              * an entire directory subtree if the FSMID matches.
741              */
742 #ifdef _ST_FSMID_PRESENT_
743             if (ForceOpt == 0 &&
744                 (UseFSMIDOpt && (fres = fsmid_check(st1.st_fsmid, dpath)) == 0)
745             ) {
746                 if (VerboseOpt >= 3) {
747                     if (UseFSMIDOpt)
748                         logstd("%-32s fsmid-nochange\n", (dpath ? dpath : spath));
749                     else
750                         logstd("%-32s nochange\n", (dpath ? dpath : spath));
751                 }
752                 r = 0;
753                 goto done;
754             }
755 #endif
756         } else {
757             if (ForceOpt == 0 &&
758                 st1.st_size == st2.st_size &&
759                 st1.st_uid == st2.st_uid &&
760                 st1.st_gid == st2.st_gid &&
761                 st1.st_mtime == st2.st_mtime
762 #ifndef NOMD5
763                 && (UseMD5Opt == 0 || !S_ISREG(st1.st_mode) ||
764                     (mres = md5_check(spath, dpath)) == 0)
765 #endif
766 #ifdef _ST_FSMID_PRESENT_
767                 && (UseFSMIDOpt == 0 ||
768                     (fres = fsmid_check(st1.st_fsmid, dpath)) == 0)
769 #endif
770                 && (ValidateOpt == 0 || !S_ISREG(st1.st_mode) ||
771                     validate_check(spath, dpath) == 0)
772             ) {
773                 if (hln)
774                     hltsetdino(hln, st2.st_ino);
775                 if (VerboseOpt >= 3) {
776 #ifndef NOMD5
777                     if (UseMD5Opt)
778                         logstd("%-32s md5-nochange\n", (dpath ? dpath : spath));
779                     else
780 #endif
781                     if (UseFSMIDOpt)
782                         logstd("%-32s fsmid-nochange\n", (dpath ? dpath : spath));
783                     else if (ValidateOpt)
784                         logstd("%-32s nochange (contents validated)\n", (dpath ? dpath : spath));
785                     else
786                         logstd("%-32s nochange\n", (dpath ? dpath : spath));
787                 }
788                 CountSourceBytes += size;
789                 CountSourceItems++;
790                 r = 0;
791                 goto done;
792             }
793         }
794     }
795     if (st2Valid && !S_ISDIR(st1.st_mode) && S_ISDIR(st2.st_mode)) {
796         if (SafetyOpt) {
797             logerr("%-32s SAFETY - refusing to copy file over directory\n",
798                 (dpath ? dpath : spath)
799             );
800             ++r;                /* XXX */
801             r = 0;
802             goto done;          /* continue with the cpdup anyway */
803         }
804         if (QuietOpt == 0 || AskConfirmation) {
805             logstd("%-32s WARNING: non-directory source will blow away\n"
806                    "%-32s preexisting dest directory, continuing anyway!\n",
807                    ((dpath) ? dpath : spath), "");
808         }
809         if (dpath)
810             RemoveRecur(dpath, ddevNo);
811     }
812
813     /*
814      * The various comparisons failed, copy it.
815      */
816     if (S_ISDIR(st1.st_mode)) {
817         DIR *dir;
818
819         if (fres < 0)
820             logerr("%-32s/ fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
821         if ((dir = hc_opendir(&SrcHost, spath)) != NULL) {
822             struct dirent *den;
823             int noLoop = 0;
824
825             if (dpath) {
826                 if (S_ISDIR(st2.st_mode) == 0) {
827                     hc_remove(&DstHost, dpath);
828                     if (hc_mkdir(&DstHost, dpath, st1.st_mode | 0700) != 0) {
829                         logerr("%s: mkdir failed: %s\n", 
830                             (dpath ? dpath : spath), strerror(errno));
831                         r = 1;
832                         noLoop = 1;
833                     }
834                     /*
835                      * Matt: why don't you check error codes here?
836                      */
837                     hc_lstat(&DstHost, dpath, &st2);
838                     hc_chown(&DstHost, dpath, st1.st_uid, st1.st_gid);
839                     CountCopiedItems++;
840                 } else {
841                     /*
842                      * Directory must be scanable by root for cpdup to
843                      * work.  We'll fix it later if the directory isn't
844                      * supposed to be readable ( which is why we fixup
845                      * st2.st_mode to match what we did ).
846                      */
847                     if ((st2.st_mode & 0700) != 0700) {
848                         hc_chmod(&DstHost, dpath, st2.st_mode | 0700);
849                         st2.st_mode |= 0700;
850                     }
851                     if (VerboseOpt >= 2)
852                         logstd("%s\n", dpath ? dpath : spath);
853                 }
854             }
855
856             if ((int)sdevNo >= 0 && st1.st_dev != sdevNo) {
857                 noLoop = 1;
858             } else {
859                 sdevNo = st1.st_dev;
860             }
861
862             if ((int)ddevNo >= 0 && st2.st_dev != ddevNo) {
863                 noLoop = 1;
864             } else {
865                 ddevNo = st2.st_dev;
866             }
867
868             /*
869              * scan .cpignore file for files/directories 
870              * to ignore.
871              */
872
873             if (UseCpFile) {
874                 FILE *fi;
875                 char *buf = malloc(GETBUFSIZE);
876                 char *fpath;
877
878                 if (UseCpFile[0] == '/') {
879                     fpath = mprintf("%s", UseCpFile);
880                 } else {
881                     fpath = mprintf("%s/%s", spath, UseCpFile);
882                 }
883                 AddList(list, strrchr(fpath, '/') + 1, 1);
884                 if ((fi = fopen(fpath, "r")) != NULL) {
885                     while (fgets(buf, GETBUFSIZE, fi) != NULL) {
886                         int l = strlen(buf);
887                         CountSourceReadBytes += l;
888                         if (l && buf[l-1] == '\n')
889                             buf[--l] = 0;
890                         if (buf[0] && buf[0] != '#')
891                             AddList(list, buf, 1);
892                     }
893                     fclose(fi);
894                 }
895                 free(fpath);
896                 free(buf);
897             }
898
899             /*
900              * Automatically exclude MD5CacheFile that we create on the
901              * source from the copy to the destination.
902              *
903              * Automatically exclude a FSMIDCacheFile on the source that
904              * would otherwise overwrite the one we maintain on the target.
905              */
906             if (UseMD5Opt)
907                 AddList(list, MD5CacheFile, 1);
908             if (UseFSMIDOpt)
909                 AddList(list, FSMIDCacheFile, 1);
910
911             while (noLoop == 0 && (den = hc_readdir(&SrcHost, dir)) != NULL) {
912                 /*
913                  * ignore . and ..
914                  */
915                 char *nspath;
916                 char *ndpath = NULL;
917
918                 if (strcmp(den->d_name, ".") == 0 ||
919                     strcmp(den->d_name, "..") == 0
920                 ) {
921                     continue;
922                 }
923                 /*
924                  * ignore if on .cpignore list
925                  */
926                 if (AddList(list, den->d_name, 0) == 1) {
927                     continue;
928                 }
929                 nspath = mprintf("%s/%s", spath, den->d_name);
930                 if (dpath)
931                     ndpath = mprintf("%s/%s", dpath, den->d_name);
932
933 #if USE_PTHREADS
934                 if (CurParallel < MaxParallel || depth > MAXDEPTH) {
935                     copy_info_t cinfo = malloc(sizeof(*cinfo));
936                     pthread_t dummy_thr = NULL;
937
938                     bzero(cinfo, sizeof(*cinfo));
939                     cinfo->spath = nspath;
940                     cinfo->dpath = ndpath;
941                     cinfo->sdevNo = sdevNo;
942                     cinfo->ddevNo = ddevNo;
943                     cinfo->parent = info;
944                     ++CurParallel;
945                     ++info->children;
946                     pthread_create(&dummy_thr, NULL, DoCopyThread, cinfo);
947                 } else
948 #endif
949                 {
950                     info->spath = nspath;
951                     info->dpath = ndpath;
952                     info->sdevNo = sdevNo;
953                     info->ddevNo = ddevNo;
954                     if (depth < 0)
955                         r += DoCopy(info, depth);
956                     else
957                         r += DoCopy(info, depth + 1);
958                     free(nspath);
959                     if (ndpath)
960                         free(ndpath);
961                     info->spath = NULL;
962                     info->dpath = NULL;
963                 }
964             }
965
966             hc_closedir(&SrcHost, dir);
967
968 #if USE_PTHREADS
969             /*
970              * Wait for our children to finish
971              */
972             while (info->children) {
973                 pthread_cond_wait(&info->cond, &MasterMutex);
974             }
975             r += info->r;
976             info->r = 0;
977 #endif
978
979             /*
980              * Remove files/directories from destination that do not appear
981              * in the source.
982              */
983             if (dpath && (dir = hc_opendir(&DstHost, dpath)) != NULL) {
984                 while (noLoop == 0 && (den = hc_readdir(&DstHost, dir)) != NULL) {
985                     /*
986                      * ignore . or ..
987                      */
988                     if (strcmp(den->d_name, ".") == 0 ||
989                         strcmp(den->d_name, "..") == 0
990                     ) {
991                         continue;
992                     }
993                     /*
994                      * If object does not exist in source or .cpignore
995                      * then recursively remove it.
996                      */
997                     if (AddList(list, den->d_name, 3) == 3) {
998                         char *ndpath;
999
1000                         ndpath = mprintf("%s/%s", dpath, den->d_name);
1001                         RemoveRecur(ndpath, ddevNo);
1002                         free(ndpath);
1003                     }
1004                 }
1005                 hc_closedir(&DstHost, dir);
1006             }
1007
1008             if (dpath) {
1009                 struct timeval tv[2];
1010
1011                 if (ForceOpt ||
1012                     st2Valid == 0 || 
1013                     st1.st_uid != st2.st_uid ||
1014                     st1.st_gid != st2.st_gid
1015                 ) {
1016                     hc_chown(&DstHost, dpath, st1.st_uid, st1.st_gid);
1017                 }
1018                 if (st2Valid == 0 || st1.st_mode != st2.st_mode) {
1019                     hc_chmod(&DstHost, dpath, st1.st_mode);
1020                 }
1021 #ifdef _ST_FLAGS_PRESENT_
1022                 if (st2Valid == 0 || st1.st_flags != st2.st_flags) {
1023                     hc_chflags(&DstHost, dpath, st1.st_flags);
1024                 }
1025 #endif
1026                 if (ForceOpt ||
1027                     st2Valid == 0 ||
1028                     st1.st_mtime != st2.st_mtime
1029                 ) {
1030                     bzero(tv, sizeof(tv));
1031                     tv[0].tv_sec = st1.st_mtime;
1032                     tv[1].tv_sec = st1.st_mtime;
1033                     hc_utimes(&DstHost, dpath, tv);
1034                 }
1035             }
1036         }
1037     } else if (dpath == NULL) {
1038         /*
1039          * If dpath is NULL, we are just updating the MD5
1040          */
1041 #ifndef NOMD5
1042         if (UseMD5Opt && S_ISREG(st1.st_mode)) {
1043             mres = md5_check(spath, NULL);
1044
1045             if (VerboseOpt > 1) {
1046                 if (mres < 0)
1047                     logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1048                 else
1049                     logstd("%-32s md5-ok\n", (dpath) ? dpath : spath);
1050             } else if (!QuietOpt && mres < 0) {
1051                 logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1052             }
1053         }
1054 #endif
1055     } else if (S_ISREG(st1.st_mode)) {
1056         char *path;
1057         char *hpath;
1058         int fd1;
1059         int fd2;
1060
1061         path = mprintf("%s.tmp%d", dpath, (int)getpid());
1062
1063         /*
1064          * Handle check failure message.
1065          */
1066 #ifndef NOMD5
1067         if (mres < 0)
1068             logerr("%-32s md5-CHECK-FAILED\n", (dpath) ? dpath : spath);
1069         else 
1070 #endif
1071         if (fres < 0)
1072             logerr("%-32s fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
1073
1074         /*
1075          * Not quite ready to do the copy yet.  If UseHLPath is defined,
1076          * see if we can hardlink instead.
1077          *
1078          * If we can hardlink, and the target exists, we have to remove it
1079          * first or the hardlink will fail.  This can occur in a number of
1080          * situations but must typically when the '-f -H' combination is 
1081          * used.
1082          */
1083         if (UseHLPath && (hpath = checkHLPath(&st1, spath, dpath)) != NULL) {
1084                 if (st2Valid)
1085                         hc_remove(&DstHost, dpath);
1086                 if (hc_link(&DstHost, hpath, dpath) == 0) {
1087                         ++CountLinkedItems;
1088                         if (VerboseOpt) {
1089                             logstd("%-32s hardlinked(-H)\n",
1090                                    (dpath ? dpath : spath));
1091                         }
1092                         free(hpath);
1093                         goto skip_copy;
1094                 }
1095                 /*
1096                  * Shucks, we may have hit a filesystem hard linking limit,
1097                  * we have to copy instead.
1098                  */
1099                 free(hpath);
1100         }
1101
1102         if ((fd1 = hc_open(&SrcHost, spath, O_RDONLY, 0)) >= 0) {
1103             if ((fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL, 0600)) < 0) {
1104                 /*
1105                  * There could be a .tmp file from a previously interrupted
1106                  * run, delete and retry.  Fail if we still can't get at it.
1107                  */
1108 #ifdef _ST_FLAGS_PRESENT_
1109                 hc_chflags(&DstHost, path, 0);
1110 #endif
1111                 hc_remove(&DstHost, path);
1112                 fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600);
1113             }
1114             if (fd2 >= 0) {
1115                 const char *op;
1116                 char *iobuf1 = malloc(GETIOSIZE);
1117                 int n;
1118
1119                 /*
1120                  * Matt: What about holes?
1121                  */
1122                 op = "read";
1123                 while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
1124                     op = "write";
1125                     if (hc_write(&DstHost, fd2, iobuf1, n) != n)
1126                         break;
1127                     op = "read";
1128                 }
1129                 hc_close(&DstHost, fd2);
1130                 if (n == 0) {
1131                     struct timeval tv[2];
1132
1133                     bzero(tv, sizeof(tv));
1134                     tv[0].tv_sec = st1.st_mtime;
1135                     tv[1].tv_sec = st1.st_mtime;
1136
1137                     hc_utimes(&DstHost, path, tv);
1138                     hc_chown(&DstHost, path, st1.st_uid, st1.st_gid);
1139                     hc_chmod(&DstHost, path, st1.st_mode);
1140                     if (xrename(path, dpath, st2.st_flags) != 0) {
1141                         logerr("%-32s rename-after-copy failed: %s\n",
1142                             (dpath ? dpath : spath), strerror(errno)
1143                         );
1144                         ++r;
1145                     } else {
1146                         if (VerboseOpt)
1147                             logstd("%-32s copy-ok\n", (dpath ? dpath : spath));
1148 #ifdef _ST_FLAGS_PRESENT_
1149                         if (st1.st_flags)
1150                             hc_chflags(&DstHost, dpath, st1.st_flags);
1151 #endif
1152                     }
1153                     CountSourceReadBytes += size;
1154                     CountWriteBytes += size;
1155                     CountSourceBytes += size;
1156                     CountSourceItems++;
1157                     CountCopiedItems++;
1158                 } else {
1159                     logerr("%-32s %s failed: %s\n",
1160                         (dpath ? dpath : spath), op, strerror(errno)
1161                     );
1162                     hc_remove(&DstHost, path);
1163                     ++r;
1164                 }
1165                 free(iobuf1);
1166             } else {
1167                 logerr("%-32s create (uid %d, euid %d) failed: %s\n",
1168                     (dpath ? dpath : spath), getuid(), geteuid(),
1169                     strerror(errno)
1170                 );
1171                 ++r;
1172             }
1173             hc_close(&SrcHost, fd1);
1174         } else {
1175             logerr("%-32s copy: open failed: %s\n",
1176                 (dpath ? dpath : spath),
1177                 strerror(errno)
1178             );
1179             ++r;
1180         }
1181 skip_copy:
1182         free(path);
1183
1184         if (hln) {
1185             if (!r && hc_stat(&DstHost, dpath, &st2) == 0) {
1186                 hltsetdino(hln, st2.st_ino);
1187             } else {
1188                 hltdelete(hln);
1189                 hln = NULL;
1190             }
1191         }
1192     } else if (S_ISLNK(st1.st_mode)) {
1193         char *link1 = malloc(GETLINKSIZE);
1194         char *link2 = malloc(GETLINKSIZE);
1195         char *path = malloc(GETPATHSIZE);
1196         int n1;
1197         int n2;
1198
1199         snprintf(path, GETPATHSIZE, "%s.tmp%d", dpath, (int)getpid());
1200         n1 = hc_readlink(&SrcHost, spath, link1, GETLINKSIZE - 1);
1201         n2 = hc_readlink(&DstHost, dpath, link2, GETLINKSIZE - 1);
1202         if (n1 >= 0) {
1203             if (ForceOpt || n1 != n2 || bcmp(link1, link2, n1) != 0) {
1204                 hc_umask(&DstHost, ~st1.st_mode);
1205                 hc_remove(&DstHost, path);
1206                 link1[n1] = 0;
1207                 if (hc_symlink(&DstHost, link1, path) < 0) {
1208                       logerr("%-32s symlink (%s->%s) failed: %s\n",
1209                           (dpath ? dpath : spath), link1, path,
1210                           strerror(errno)
1211                       );
1212                       ++r;
1213                 } else {
1214                     hc_lchown(&DstHost, path, st1.st_uid, st1.st_gid);
1215                     /*
1216                      * there is no lchmod() or lchflags(), we 
1217                      * cannot chmod or chflags a softlink.
1218                      */
1219                     if (xrename(path, dpath, st2.st_flags) != 0) {
1220                         logerr("%-32s rename softlink (%s->%s) failed: %s\n",
1221                             (dpath ? dpath : spath),
1222                             path, dpath, strerror(errno));
1223                     } else if (VerboseOpt) {
1224                         logstd("%-32s softlink-ok\n", (dpath ? dpath : spath));
1225                     }
1226                     hc_umask(&DstHost, 000);
1227                     CountWriteBytes += n1;
1228                     CountCopiedItems++;
1229                 }
1230             } else {
1231                 if (VerboseOpt >= 3)
1232                     logstd("%-32s nochange\n", (dpath ? dpath : spath));
1233             }
1234             CountSourceBytes += n1;
1235             CountSourceReadBytes += n1;
1236             if (n2 > 0) 
1237                 CountTargetReadBytes += n2;
1238             CountSourceItems++;
1239         } else {
1240             r = 1;
1241             logerr("%-32s softlink-failed\n", (dpath ? dpath : spath));
1242         }
1243         free(link1);
1244         free(link2);
1245         free(path);
1246     } else if ((S_ISCHR(st1.st_mode) || S_ISBLK(st1.st_mode)) && DeviceOpt) {
1247         char *path = malloc(GETPATHSIZE);
1248
1249         if (ForceOpt ||
1250             st2Valid == 0 || 
1251             st1.st_mode != st2.st_mode || 
1252             st1.st_rdev != st2.st_rdev ||
1253             st1.st_uid != st2.st_uid ||
1254             st1.st_gid != st2.st_gid
1255         ) {
1256             snprintf(path, GETPATHSIZE, "%s.tmp%d", dpath, (int)getpid());
1257
1258             hc_remove(&DstHost, path);
1259             if (hc_mknod(&DstHost, path, st1.st_mode, st1.st_rdev) == 0) {
1260                 hc_chmod(&DstHost, path, st1.st_mode);
1261                 hc_chown(&DstHost, path, st1.st_uid, st1.st_gid);
1262                 hc_remove(&DstHost, dpath);
1263                 if (xrename(path, dpath, st2.st_flags) != 0) {
1264                     logerr("%-32s dev-rename-after-create failed: %s\n",
1265                         (dpath ? dpath : spath),
1266                         strerror(errno)
1267                     );
1268                 } else if (VerboseOpt) {
1269                     logstd("%-32s dev-ok\n", (dpath ? dpath : spath));
1270                 }
1271                 CountCopiedItems++;
1272             } else {
1273                 r = 1;
1274                 logerr("%-32s dev failed: %s\n", 
1275                     (dpath ? dpath : spath), strerror(errno)
1276                 );
1277             }
1278         } else {
1279             if (VerboseOpt >= 3)
1280                 logstd("%-32s nochange\n", (dpath ? dpath : spath));
1281         }
1282         free(path);
1283         CountSourceItems++;
1284     }
1285 done:
1286     if (hln) {
1287         if (hln->dino == (ino_t)-1) {
1288             hltdelete(hln);
1289             /*hln = NULL; unneeded */
1290         } else {
1291             hltrels(hln);
1292         }
1293     }
1294     ResetList(list);
1295     free(list);
1296     return (r);
1297 }
1298
1299 /*
1300  * RemoveRecur()
1301  */
1302
1303 void
1304 RemoveRecur(const char *dpath, dev_t devNo)
1305 {
1306     struct stat st;
1307
1308     if (hc_lstat(&DstHost, dpath, &st) == 0) {
1309         if ((int)devNo < 0)
1310             devNo = st.st_dev;
1311         if (st.st_dev == devNo) {
1312             if (S_ISDIR(st.st_mode)) {
1313                 DIR *dir;
1314
1315                 if ((dir = hc_opendir(&DstHost, dpath)) != NULL) {
1316                     struct dirent *den;
1317                     while ((den = hc_readdir(&DstHost, dir)) != NULL) {
1318                         char *ndpath;
1319
1320                         if (strcmp(den->d_name, ".") == 0)
1321                             continue;
1322                         if (strcmp(den->d_name, "..") == 0)
1323                             continue;
1324                         ndpath = mprintf("%s/%s", dpath, den->d_name);
1325                         RemoveRecur(ndpath, devNo);
1326                         free(ndpath);
1327                     }
1328                     hc_closedir(&DstHost, dir);
1329                 }
1330                 if (AskConfirmation && NoRemoveOpt == 0) {
1331                     if (YesNo(dpath)) {
1332                         if (hc_rmdir(&DstHost, dpath) < 0) {
1333                             logerr("%-32s rmdir failed: %s\n",
1334                                 dpath, strerror(errno)
1335                             );
1336                         }
1337                         CountRemovedItems++;
1338                     }
1339                 } else {
1340                     if (NoRemoveOpt) {
1341                         if (VerboseOpt)
1342                             logstd("%-32s not-removed\n", dpath);
1343                     } else if (hc_rmdir(&DstHost, dpath) == 0) {
1344                         if (VerboseOpt)
1345                             logstd("%-32s rmdir-ok\n", dpath);
1346                         CountRemovedItems++;
1347                     } else {
1348                         logerr("%-32s rmdir failed: %s\n",
1349                             dpath, strerror(errno)
1350                         );
1351                     }
1352                 }
1353             } else {
1354                 if (AskConfirmation && NoRemoveOpt == 0) {
1355                     if (YesNo(dpath)) {
1356                         if (hc_remove(&DstHost, dpath) < 0) {
1357                             logerr("%-32s remove failed: %s\n",
1358                                 dpath, strerror(errno)
1359                             );
1360                         }
1361                         CountRemovedItems++;
1362                     }
1363                 } else {
1364                     if (NoRemoveOpt) {
1365                         if (VerboseOpt)
1366                             logstd("%-32s not-removed\n", dpath);
1367                     } else if (hc_remove(&DstHost, dpath) == 0) {
1368                         if (VerboseOpt)
1369                             logstd("%-32s remove-ok\n", dpath);
1370                         CountRemovedItems++;
1371                     } else {
1372                         logerr("%-32s remove failed: %s\n",
1373                             dpath, strerror(errno)
1374                         );
1375                     }
1376                 }
1377             }
1378         }
1379     }
1380 }
1381
1382 void
1383 InitList(List *list)
1384 {
1385     bzero(list, sizeof(List));
1386     list->li_Node.no_Next = &list->li_Node;
1387 }
1388
1389 void 
1390 ResetList(List *list)
1391 {
1392     Node *node;
1393
1394     while ((node = list->li_Node.no_Next) != &list->li_Node) {
1395         list->li_Node.no_Next = node->no_Next;
1396         free(node);
1397     }
1398     InitList(list);
1399 }
1400
1401 int
1402 AddList(List *list, const char *name, int n)
1403 {
1404     Node *node;
1405     int hv;
1406
1407     hv = shash(name);
1408
1409     /*
1410      * Scan against wildcards.  Only a node value of 1 can be a wildcard
1411      * ( usually scanned from .cpignore )
1412      */
1413
1414     for (node = list->li_Hash[0]; node; node = node->no_HNext) {
1415         if (strcmp(name, node->no_Name) == 0 ||
1416             (n != 1 && node->no_Value == 1 && WildCmp(node->no_Name, name) == 0)
1417         ) {
1418             return(node->no_Value);
1419         }
1420     }
1421
1422     /*
1423      * Look for exact match
1424      */
1425
1426     for (node = list->li_Hash[hv]; node; node = node->no_HNext) {
1427         if (strcmp(name, node->no_Name) == 0) {
1428             return(node->no_Value);
1429         }
1430     }
1431     node = malloc(sizeof(Node) + strlen(name) + 1);
1432     if (node == NULL) {
1433         fprintf(stderr, "out of memory\n");
1434         exit(EXIT_FAILURE);
1435     }
1436
1437     node->no_Next = list->li_Node.no_Next;
1438     list->li_Node.no_Next = node;
1439
1440     node->no_HNext = list->li_Hash[hv];
1441     list->li_Hash[hv] = node;
1442
1443     strcpy(node->no_Name, name);
1444     node->no_Value = n;
1445
1446     return(n);
1447 }
1448
1449 static int
1450 shash(const char *s)
1451 {
1452     int hv;
1453
1454     hv = 0xA4FB3255;
1455
1456     while (*s) {
1457         if (*s == '*' || *s == '?' || 
1458             *s == '{' || *s == '}' || 
1459             *s == '[' || *s == ']' ||
1460             *s == '|'
1461         ) {
1462             return(0);
1463         }
1464         hv = (hv << 5) ^ *s ^ (hv >> 23);
1465         ++s;
1466     }
1467     return(((hv >> 16) ^ hv) & HMASK);
1468 }
1469
1470 /*
1471  * WildCmp() - compare wild string to sane string
1472  *
1473  *      Return 0 on success, -1 on failure.
1474  */
1475
1476 int
1477 WildCmp(const char *w, const char *s)
1478 {
1479     /*
1480      * skip fixed portion
1481      */
1482   
1483     for (;;) {
1484         switch(*w) {
1485         case '*':
1486             if (w[1] == 0)      /* optimize wild* case */
1487                 return(0);
1488             {
1489                 int i;
1490                 int l = strlen(s);
1491
1492                 for (i = 0; i <= l; ++i) {
1493                     if (WildCmp(w + 1, s + i) == 0)
1494                         return(0);
1495                 }
1496             }
1497             return(-1);
1498         case '?':
1499             if (*s == 0)
1500                 return(-1);
1501             ++w;
1502             ++s;
1503             break;
1504         default:
1505             if (*w != *s)
1506                 return(-1);
1507             if (*w == 0)        /* terminator */
1508                 return(0);
1509             ++w;
1510             ++s;
1511             break;
1512         }
1513     }
1514     /* not reached */
1515     return(-1);
1516 }
1517
1518 int
1519 YesNo(const char *path)
1520 {
1521     int ch, first;
1522
1523     fprintf(stderr, "remove %s (Yes/No) [No]? ", path);
1524     fflush(stderr);
1525
1526     first = ch = getchar();
1527     while (ch != '\n' && ch != EOF)
1528         ch = getchar();
1529     return ((first == 'y' || first == 'Y'));
1530 }
1531
1532 /*
1533  * xrename() - rename with override
1534  *
1535  *      If the rename fails, attempt to override st_flags on the 
1536  *      destination and rename again.  If that fails too, try to
1537  *      set the flags back the way they were and give up.
1538  */
1539
1540 static int
1541 xrename(const char *src, const char *dst, u_long flags)
1542 {
1543     int r;
1544
1545     r = 0;
1546
1547     if ((r = hc_rename(&DstHost, src, dst)) < 0) {
1548 #ifdef _ST_FLAGS_PRESENT_
1549         hc_chflags(&DstHost, dst, 0);
1550         if ((r = hc_rename(&DstHost, src, dst)) < 0)
1551                 hc_chflags(&DstHost, dst, flags);
1552 #endif
1553     }
1554     return(r);
1555 }
1556
1557 static int
1558 xlink(const char *src, const char *dst, u_long flags)
1559 {
1560     int r;
1561 #ifdef _ST_FLAGS_PRESENT_
1562     int e;
1563 #endif
1564
1565     r = 0;
1566
1567     if ((r = hc_link(&DstHost, src, dst)) < 0) {
1568 #ifdef _ST_FLAGS_PRESENT_
1569         hc_chflags(&DstHost, src, 0);
1570         r = hc_link(&DstHost, src, dst);
1571         e = errno;
1572         hc_chflags(&DstHost, src, flags);
1573         errno = e;
1574 #endif
1575     }
1576     if (r == 0)
1577             ++CountLinkedItems;
1578     return(r);
1579 }
1580