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