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