xref: /dragonfly/bin/cpdup/cpdup.c (revision 15b85273)
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 		     * Matt: why don't you check error codes here?
842 		     */
843 		    hc_lstat(&DstHost, dpath, &st2);
844 		    hc_chown(&DstHost, dpath, st1.st_uid, st1.st_gid);
845 		    CountCopiedItems++;
846 		} else {
847 		    /*
848 		     * Directory must be scanable by root for cpdup to
849 		     * work.  We'll fix it later if the directory isn't
850 		     * supposed to be readable ( which is why we fixup
851 		     * st2.st_mode to match what we did ).
852 		     */
853 		    if ((st2.st_mode & 0700) != 0700) {
854 			hc_chmod(&DstHost, dpath, st2.st_mode | 0700);
855 			st2.st_mode |= 0700;
856 		    }
857 		    if (VerboseOpt >= 2)
858 			logstd("%s\n", dpath ? dpath : spath);
859 		}
860 	    }
861 
862 	    if ((int)sdevNo >= 0 && st1.st_dev != sdevNo) {
863 		noLoop = 1;
864 	    } else {
865 		sdevNo = st1.st_dev;
866 	    }
867 
868 	    if ((int)ddevNo >= 0 && st2.st_dev != ddevNo) {
869 		noLoop = 1;
870 	    } else {
871 		ddevNo = st2.st_dev;
872 	    }
873 
874 	    /*
875 	     * scan .cpignore file for files/directories
876 	     * to ignore.
877 	     */
878 
879 	    if (UseCpFile) {
880 		FILE *fi;
881 		char *buf = malloc(GETBUFSIZE);
882 		char *fpath;
883 
884 		if (UseCpFile[0] == '/') {
885 		    fpath = mprintf("%s", UseCpFile);
886 		} else {
887 		    fpath = mprintf("%s/%s", spath, UseCpFile);
888 		}
889 		AddList(list, strrchr(fpath, '/') + 1, 1);
890 		if ((fi = fopen(fpath, "r")) != NULL) {
891 		    while (fgets(buf, GETBUFSIZE, fi) != NULL) {
892 			int l = strlen(buf);
893 			CountSourceReadBytes += l;
894 			if (l && buf[l-1] == '\n')
895 			    buf[--l] = 0;
896 			if (buf[0] && buf[0] != '#')
897 			    AddList(list, buf, 1);
898 		    }
899 		    fclose(fi);
900 		}
901 		free(fpath);
902 		free(buf);
903 	    }
904 
905 	    /*
906 	     * Automatically exclude MD5CacheFile that we create on the
907 	     * source from the copy to the destination.
908 	     *
909 	     * Automatically exclude a FSMIDCacheFile on the source that
910 	     * would otherwise overwrite the one we maintain on the target.
911 	     */
912 	    if (UseMD5Opt)
913 		AddList(list, MD5CacheFile, 1);
914 	    if (UseFSMIDOpt)
915 		AddList(list, FSMIDCacheFile, 1);
916 
917 	    while (noLoop == 0 && (den = hc_readdir(&SrcHost, dir)) != NULL) {
918 		/*
919 		 * ignore . and ..
920 		 */
921 		char *nspath;
922 		char *ndpath = NULL;
923 
924 		if (strcmp(den->d_name, ".") == 0 ||
925 		    strcmp(den->d_name, "..") == 0
926 		) {
927 		    continue;
928 		}
929 		/*
930 		 * ignore if on .cpignore list
931 		 */
932 		if (AddList(list, den->d_name, 0) == 1) {
933 		    continue;
934 		}
935 		nspath = mprintf("%s/%s", spath, den->d_name);
936 		if (dpath)
937 		    ndpath = mprintf("%s/%s", dpath, den->d_name);
938 
939 #if USE_PTHREADS
940 		if (CurParallel < MaxParallel || depth > MAXDEPTH) {
941 		    copy_info_t cinfo = malloc(sizeof(*cinfo));
942 		    pthread_t dummy_thr;
943 
944 		    bzero(cinfo, sizeof(*cinfo));
945 		    cinfo->spath = nspath;
946 		    cinfo->dpath = ndpath;
947 		    cinfo->sdevNo = sdevNo;
948 		    cinfo->ddevNo = ddevNo;
949 		    cinfo->parent = info;
950 		    ++CurParallel;
951 		    ++info->children;
952 		    pthread_create(&dummy_thr, NULL, DoCopyThread, cinfo);
953 		} else
954 #endif
955 		{
956 		    info->spath = nspath;
957 		    info->dpath = ndpath;
958 		    info->sdevNo = sdevNo;
959 		    info->ddevNo = ddevNo;
960 		    if (depth < 0)
961 			r += DoCopy(info, depth);
962 		    else
963 			r += DoCopy(info, depth + 1);
964 		    free(nspath);
965 		    if (ndpath)
966 			free(ndpath);
967 		    info->spath = NULL;
968 		    info->dpath = NULL;
969 		}
970 	    }
971 
972 	    hc_closedir(&SrcHost, dir);
973 
974 #if USE_PTHREADS
975 	    /*
976 	     * Wait for our children to finish
977 	     */
978 	    while (info->children) {
979 		pthread_cond_wait(&info->cond, &MasterMutex);
980 	    }
981 	    r += info->r;
982 	    info->r = 0;
983 #endif
984 
985 	    /*
986 	     * Remove files/directories from destination that do not appear
987 	     * in the source.
988 	     */
989 	    if (dpath && (dir = hc_opendir(&DstHost, dpath)) != NULL) {
990 		while (noLoop == 0 && (den = hc_readdir(&DstHost, dir)) != NULL) {
991 		    /*
992 		     * ignore . or ..
993 		     */
994 		    if (strcmp(den->d_name, ".") == 0 ||
995 			strcmp(den->d_name, "..") == 0
996 		    ) {
997 			continue;
998 		    }
999 		    /*
1000 		     * If object does not exist in source or .cpignore
1001 		     * then recursively remove it.
1002 		     */
1003 		    if (AddList(list, den->d_name, 3) == 3) {
1004 			char *ndpath;
1005 
1006 			ndpath = mprintf("%s/%s", dpath, den->d_name);
1007 			RemoveRecur(ndpath, ddevNo);
1008 			free(ndpath);
1009 		    }
1010 		}
1011 		hc_closedir(&DstHost, dir);
1012 	    }
1013 
1014 	    if (dpath) {
1015 		struct timeval tv[2];
1016 
1017 		if (ForceOpt ||
1018 		    st2Valid == 0 ||
1019 		    st1.st_uid != st2.st_uid ||
1020 		    st1.st_gid != st2.st_gid
1021 		) {
1022 		    hc_chown(&DstHost, dpath, st1.st_uid, st1.st_gid);
1023 		}
1024 		if (st2Valid == 0 || st1.st_mode != st2.st_mode) {
1025 		    hc_chmod(&DstHost, dpath, st1.st_mode);
1026 		}
1027 #ifdef _ST_FLAGS_PRESENT_
1028 		if (st2Valid == 0 || st1.st_flags != st2.st_flags) {
1029 		    hc_chflags(&DstHost, dpath, st1.st_flags);
1030 		}
1031 #endif
1032 		if (ForceOpt ||
1033 		    st2Valid == 0 ||
1034 		    st1.st_mtime != st2.st_mtime
1035 		) {
1036 		    bzero(tv, sizeof(tv));
1037 		    tv[0].tv_sec = st1.st_mtime;
1038 		    tv[1].tv_sec = st1.st_mtime;
1039 		    hc_utimes(&DstHost, dpath, tv);
1040 		}
1041 	    }
1042 	}
1043     } else if (dpath == NULL) {
1044 	/*
1045 	 * If dpath is NULL, we are just updating the MD5
1046 	 */
1047 #ifndef NOMD5
1048 	if (UseMD5Opt && S_ISREG(st1.st_mode)) {
1049 	    mres = md5_check(spath, NULL);
1050 
1051 	    if (VerboseOpt > 1) {
1052 		if (mres < 0)
1053 		    logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1054 		else
1055 		    logstd("%-32s md5-ok\n", (dpath) ? dpath : spath);
1056 	    } else if (!QuietOpt && mres < 0) {
1057 		logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1058 	    }
1059 	}
1060 #endif
1061     } else if (S_ISREG(st1.st_mode)) {
1062 	char *path;
1063 	char *hpath;
1064 	int fd1;
1065 	int fd2;
1066 
1067 	path = mprintf("%s.tmp%d", dpath, (int)getpid());
1068 
1069 	/*
1070 	 * Handle check failure message.
1071 	 */
1072 #ifndef NOMD5
1073 	if (mres < 0)
1074 	    logerr("%-32s md5-CHECK-FAILED\n", (dpath) ? dpath : spath);
1075 	else
1076 #endif
1077 	if (fres < 0)
1078 	    logerr("%-32s fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
1079 
1080 	/*
1081 	 * Not quite ready to do the copy yet.  If UseHLPath is defined,
1082 	 * see if we can hardlink instead.
1083 	 *
1084 	 * If we can hardlink, and the target exists, we have to remove it
1085 	 * first or the hardlink will fail.  This can occur in a number of
1086 	 * situations but must typically when the '-f -H' combination is
1087 	 * used.
1088 	 */
1089 	if (UseHLPath && (hpath = checkHLPath(&st1, spath, dpath)) != NULL) {
1090 		if (st2Valid)
1091 			xremove(&DstHost, dpath);
1092 		if (hc_link(&DstHost, hpath, dpath) == 0) {
1093 			++CountLinkedItems;
1094 			if (VerboseOpt) {
1095 			    logstd("%-32s hardlinked(-H)\n",
1096 				   (dpath ? dpath : spath));
1097 			}
1098 			free(hpath);
1099 			goto skip_copy;
1100 		}
1101 		/*
1102 		 * Shucks, we may have hit a filesystem hard linking limit,
1103 		 * we have to copy instead.
1104 		 */
1105 		free(hpath);
1106 	}
1107 
1108 	if ((fd1 = hc_open(&SrcHost, spath, O_RDONLY, 0)) >= 0) {
1109 	    if ((fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL, 0600)) < 0) {
1110 		/*
1111 		 * There could be a .tmp file from a previously interrupted
1112 		 * run, delete and retry.  Fail if we still can't get at it.
1113 		 */
1114 #ifdef _ST_FLAGS_PRESENT_
1115 		hc_chflags(&DstHost, path, 0);
1116 #endif
1117 		hc_remove(&DstHost, path);
1118 		fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600);
1119 	    }
1120 	    if (fd2 >= 0) {
1121 		const char *op;
1122 		char *iobuf1 = malloc(GETIOSIZE);
1123 		int n;
1124 
1125 		/*
1126 		 * Matt: What about holes?
1127 		 */
1128 		op = "read";
1129 		while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
1130 		    op = "write";
1131 		    if (hc_write(&DstHost, fd2, iobuf1, n) != n)
1132 			break;
1133 		    op = "read";
1134 		}
1135 		hc_close(&DstHost, fd2);
1136 		if (n == 0) {
1137 		    struct timeval tv[2];
1138 
1139 		    bzero(tv, sizeof(tv));
1140 		    tv[0].tv_sec = st1.st_mtime;
1141 		    tv[1].tv_sec = st1.st_mtime;
1142 
1143 		    hc_utimes(&DstHost, path, tv);
1144 		    hc_chown(&DstHost, path, st1.st_uid, st1.st_gid);
1145 		    hc_chmod(&DstHost, path, st1.st_mode);
1146 		    if (xrename(path, dpath, st2.st_flags) != 0) {
1147 			logerr("%-32s rename-after-copy failed: %s\n",
1148 			    (dpath ? dpath : spath), strerror(errno)
1149 			);
1150 			++r;
1151 		    } else {
1152 			if (VerboseOpt)
1153 			    logstd("%-32s copy-ok\n", (dpath ? dpath : spath));
1154 #ifdef _ST_FLAGS_PRESENT_
1155 			if (st1.st_flags)
1156 			    hc_chflags(&DstHost, dpath, st1.st_flags);
1157 #endif
1158 		    }
1159 		    CountSourceReadBytes += size;
1160 		    CountWriteBytes += size;
1161 		    CountSourceBytes += size;
1162 		    CountSourceItems++;
1163 		    CountCopiedItems++;
1164 		} else {
1165 		    logerr("%-32s %s failed: %s\n",
1166 			(dpath ? dpath : spath), op, strerror(errno)
1167 		    );
1168 		    hc_remove(&DstHost, path);
1169 		    ++r;
1170 		}
1171 		free(iobuf1);
1172 	    } else {
1173 		logerr("%-32s create (uid %d, euid %d) failed: %s\n",
1174 		    (dpath ? dpath : spath), getuid(), geteuid(),
1175 		    strerror(errno)
1176 		);
1177 		++r;
1178 	    }
1179 	    hc_close(&SrcHost, fd1);
1180 	} else {
1181 	    logerr("%-32s copy: open failed: %s\n",
1182 		(dpath ? dpath : spath),
1183 		strerror(errno)
1184 	    );
1185 	    ++r;
1186 	}
1187 skip_copy:
1188 	free(path);
1189 
1190         if (hln) {
1191             if (!r && hc_stat(&DstHost, dpath, &st2) == 0) {
1192 		hltsetdino(hln, st2.st_ino);
1193 	    } else {
1194                 hltdelete(hln);
1195 		hln = NULL;
1196 	    }
1197         }
1198     } else if (S_ISLNK(st1.st_mode)) {
1199 	char *link1 = malloc(GETLINKSIZE);
1200 	char *link2 = malloc(GETLINKSIZE);
1201 	char *path = malloc(GETPATHSIZE);
1202 	int n1;
1203 	int n2;
1204 
1205 	snprintf(path, GETPATHSIZE, "%s.tmp%d", dpath, (int)getpid());
1206 	n1 = hc_readlink(&SrcHost, spath, link1, GETLINKSIZE - 1);
1207 	n2 = hc_readlink(&DstHost, dpath, link2, GETLINKSIZE - 1);
1208 	if (n1 >= 0) {
1209 	    if (ForceOpt || n1 != n2 || bcmp(link1, link2, n1) != 0) {
1210 		hc_umask(&DstHost, ~st1.st_mode);
1211 		xremove(&DstHost, path);
1212 		link1[n1] = 0;
1213 		if (hc_symlink(&DstHost, link1, path) < 0) {
1214                       logerr("%-32s symlink (%s->%s) failed: %s\n",
1215 			  (dpath ? dpath : spath), link1, path,
1216 			  strerror(errno)
1217 		      );
1218 		      ++r;
1219 		} else {
1220 		    hc_lchown(&DstHost, path, st1.st_uid, st1.st_gid);
1221 		    /*
1222 		     * there is no lchmod() or lchflags(), we
1223 		     * cannot chmod or chflags a softlink.
1224 		     */
1225 		    if (xrename(path, dpath, st2.st_flags) != 0) {
1226 			logerr("%-32s rename softlink (%s->%s) failed: %s\n",
1227 			    (dpath ? dpath : spath),
1228 			    path, dpath, strerror(errno));
1229 		    } else if (VerboseOpt) {
1230 			logstd("%-32s softlink-ok\n", (dpath ? dpath : spath));
1231 		    }
1232 		    hc_umask(&DstHost, 000);
1233 		    CountWriteBytes += n1;
1234 		    CountCopiedItems++;
1235 	  	}
1236 	    } else {
1237 		if (VerboseOpt >= 3)
1238 		    logstd("%-32s nochange\n", (dpath ? dpath : spath));
1239 	    }
1240 	    CountSourceBytes += n1;
1241 	    CountSourceReadBytes += n1;
1242 	    if (n2 > 0)
1243 		CountTargetReadBytes += n2;
1244 	    CountSourceItems++;
1245 	} else {
1246 	    r = 1;
1247 	    logerr("%-32s softlink-failed\n", (dpath ? dpath : spath));
1248 	}
1249 	free(link1);
1250 	free(link2);
1251 	free(path);
1252     } else if ((S_ISCHR(st1.st_mode) || S_ISBLK(st1.st_mode)) && DeviceOpt) {
1253 	char *path = malloc(GETPATHSIZE);
1254 
1255 	if (ForceOpt ||
1256 	    st2Valid == 0 ||
1257 	    st1.st_mode != st2.st_mode ||
1258 	    st1.st_rdev != st2.st_rdev ||
1259 	    st1.st_uid != st2.st_uid ||
1260 	    st1.st_gid != st2.st_gid
1261 	) {
1262 	    snprintf(path, GETPATHSIZE, "%s.tmp%d", dpath, (int)getpid());
1263 
1264 	    xremove(&DstHost, path);
1265 	    if (hc_mknod(&DstHost, path, st1.st_mode, st1.st_rdev) == 0) {
1266 		hc_chmod(&DstHost, path, st1.st_mode);
1267 		hc_chown(&DstHost, path, st1.st_uid, st1.st_gid);
1268 		xremove(&DstHost, dpath);
1269 		if (xrename(path, dpath, st2.st_flags) != 0) {
1270 		    logerr("%-32s dev-rename-after-create failed: %s\n",
1271 			(dpath ? dpath : spath),
1272 			strerror(errno)
1273 		    );
1274 		} else if (VerboseOpt) {
1275 		    logstd("%-32s dev-ok\n", (dpath ? dpath : spath));
1276 		}
1277 		CountCopiedItems++;
1278 	    } else {
1279 		r = 1;
1280 		logerr("%-32s dev failed: %s\n",
1281 		    (dpath ? dpath : spath), strerror(errno)
1282 		);
1283 	    }
1284 	} else {
1285 	    if (VerboseOpt >= 3)
1286 		logstd("%-32s nochange\n", (dpath ? dpath : spath));
1287 	}
1288 	free(path);
1289 	CountSourceItems++;
1290     }
1291 done:
1292     if (hln) {
1293 	if (hln->dino == (ino_t)-1) {
1294 	    hltdelete(hln);
1295 	    /*hln = NULL; unneeded */
1296 	} else {
1297 	    hltrels(hln);
1298 	}
1299     }
1300     ResetList(list);
1301     free(list);
1302     return (r);
1303 }
1304 
1305 /*
1306  * RemoveRecur()
1307  */
1308 
1309 void
1310 RemoveRecur(const char *dpath, dev_t devNo)
1311 {
1312     struct stat st;
1313 
1314     if (hc_lstat(&DstHost, dpath, &st) == 0) {
1315 	if ((int)devNo < 0)
1316 	    devNo = st.st_dev;
1317 	if (st.st_dev == devNo) {
1318 	    if (S_ISDIR(st.st_mode)) {
1319 		DIR *dir;
1320 
1321 		if ((dir = hc_opendir(&DstHost, dpath)) != NULL) {
1322 		    struct dirent *den;
1323 		    while ((den = hc_readdir(&DstHost, dir)) != NULL) {
1324 			char *ndpath;
1325 
1326 			if (strcmp(den->d_name, ".") == 0)
1327 			    continue;
1328 			if (strcmp(den->d_name, "..") == 0)
1329 			    continue;
1330 			ndpath = mprintf("%s/%s", dpath, den->d_name);
1331 			RemoveRecur(ndpath, devNo);
1332 			free(ndpath);
1333 		    }
1334 		    hc_closedir(&DstHost, dir);
1335 		}
1336 		if (AskConfirmation && NoRemoveOpt == 0) {
1337 		    if (YesNo(dpath)) {
1338 			if (hc_rmdir(&DstHost, dpath) < 0) {
1339 			    logerr("%-32s rmdir failed: %s\n",
1340 				dpath, strerror(errno)
1341 			    );
1342 			}
1343 			CountRemovedItems++;
1344 		    }
1345 		} else {
1346 		    if (NoRemoveOpt) {
1347 			if (VerboseOpt)
1348 			    logstd("%-32s not-removed\n", dpath);
1349 		    } else if (hc_rmdir(&DstHost, dpath) == 0) {
1350 			if (VerboseOpt)
1351 			    logstd("%-32s rmdir-ok\n", dpath);
1352 			CountRemovedItems++;
1353 		    } else {
1354 			logerr("%-32s rmdir failed: %s\n",
1355 			    dpath, strerror(errno)
1356 			);
1357 		    }
1358 		}
1359 	    } else {
1360 		if (AskConfirmation && NoRemoveOpt == 0) {
1361 		    if (YesNo(dpath)) {
1362 			if (xremove(&DstHost, dpath) < 0) {
1363 			    logerr("%-32s remove failed: %s\n",
1364 				dpath, strerror(errno)
1365 			    );
1366 			}
1367 			CountRemovedItems++;
1368 		    }
1369 		} else {
1370 		    if (NoRemoveOpt) {
1371 			if (VerboseOpt)
1372 			    logstd("%-32s not-removed\n", dpath);
1373 		    } else if (xremove(&DstHost, dpath) == 0) {
1374 			if (VerboseOpt)
1375 			    logstd("%-32s remove-ok\n", dpath);
1376 			CountRemovedItems++;
1377 		    } else {
1378 			logerr("%-32s remove failed: %s\n",
1379 			    dpath, strerror(errno)
1380 			);
1381 		    }
1382 		}
1383 	    }
1384 	}
1385     }
1386 }
1387 
1388 void
1389 InitList(List *list)
1390 {
1391     bzero(list, sizeof(List));
1392     list->li_Node.no_Next = &list->li_Node;
1393 }
1394 
1395 void
1396 ResetList(List *list)
1397 {
1398     Node *node;
1399 
1400     while ((node = list->li_Node.no_Next) != &list->li_Node) {
1401 	list->li_Node.no_Next = node->no_Next;
1402 	free(node);
1403     }
1404     InitList(list);
1405 }
1406 
1407 int
1408 AddList(List *list, const char *name, int n)
1409 {
1410     Node *node;
1411     int hv;
1412 
1413     hv = shash(name);
1414 
1415     /*
1416      * Scan against wildcards.  Only a node value of 1 can be a wildcard
1417      * ( usually scanned from .cpignore )
1418      */
1419 
1420     for (node = list->li_Hash[0]; node; node = node->no_HNext) {
1421 	if (strcmp(name, node->no_Name) == 0 ||
1422 	    (n != 1 && node->no_Value == 1 && WildCmp(node->no_Name, name) == 0)
1423 	) {
1424 	    return(node->no_Value);
1425 	}
1426     }
1427 
1428     /*
1429      * Look for exact match
1430      */
1431 
1432     for (node = list->li_Hash[hv]; node; node = node->no_HNext) {
1433 	if (strcmp(name, node->no_Name) == 0) {
1434 	    return(node->no_Value);
1435 	}
1436     }
1437     node = malloc(sizeof(Node) + strlen(name) + 1);
1438     if (node == NULL) {
1439         fprintf(stderr, "out of memory\n");
1440         exit(EXIT_FAILURE);
1441     }
1442 
1443     node->no_Next = list->li_Node.no_Next;
1444     list->li_Node.no_Next = node;
1445 
1446     node->no_HNext = list->li_Hash[hv];
1447     list->li_Hash[hv] = node;
1448 
1449     strcpy(node->no_Name, name);
1450     node->no_Value = n;
1451 
1452     return(n);
1453 }
1454 
1455 static int
1456 shash(const char *s)
1457 {
1458     int hv;
1459 
1460     hv = 0xA4FB3255;
1461 
1462     while (*s) {
1463 	if (*s == '*' || *s == '?' ||
1464 	    *s == '{' || *s == '}' ||
1465 	    *s == '[' || *s == ']' ||
1466 	    *s == '|'
1467 	) {
1468 	    return(0);
1469 	}
1470 	hv = (hv << 5) ^ *s ^ (hv >> 23);
1471 	++s;
1472     }
1473     return(((hv >> 16) ^ hv) & HMASK);
1474 }
1475 
1476 /*
1477  * WildCmp() - compare wild string to sane string
1478  *
1479  *	Return 0 on success, -1 on failure.
1480  */
1481 
1482 int
1483 WildCmp(const char *w, const char *s)
1484 {
1485     /*
1486      * skip fixed portion
1487      */
1488 
1489     for (;;) {
1490 	switch(*w) {
1491 	case '*':
1492 	    if (w[1] == 0)	/* optimize wild* case */
1493 		return(0);
1494 	    {
1495 		int i;
1496 		int l = strlen(s);
1497 
1498 		for (i = 0; i <= l; ++i) {
1499 		    if (WildCmp(w + 1, s + i) == 0)
1500 			return(0);
1501 		}
1502 	    }
1503 	    return(-1);
1504 	case '?':
1505 	    if (*s == 0)
1506 		return(-1);
1507 	    ++w;
1508 	    ++s;
1509 	    break;
1510 	default:
1511 	    if (*w != *s)
1512 		return(-1);
1513 	    if (*w == 0)	/* terminator */
1514 		return(0);
1515 	    ++w;
1516 	    ++s;
1517 	    break;
1518 	}
1519     }
1520     /* not reached */
1521     return(-1);
1522 }
1523 
1524 int
1525 YesNo(const char *path)
1526 {
1527     int ch, first;
1528 
1529     fprintf(stderr, "remove %s (Yes/No) [No]? ", path);
1530     fflush(stderr);
1531 
1532     first = ch = getchar();
1533     while (ch != '\n' && ch != EOF)
1534 	ch = getchar();
1535     return ((first == 'y' || first == 'Y'));
1536 }
1537 
1538 /*
1539  * xrename() - rename with override
1540  *
1541  *	If the rename fails, attempt to override st_flags on the
1542  *	destination and rename again.  If that fails too, try to
1543  *	set the flags back the way they were and give up.
1544  */
1545 
1546 static int
1547 xrename(const char *src, const char *dst, u_long flags)
1548 {
1549     int r;
1550 
1551     r = 0;
1552 
1553     if ((r = hc_rename(&DstHost, src, dst)) < 0) {
1554 #ifdef _ST_FLAGS_PRESENT_
1555 	hc_chflags(&DstHost, dst, 0);
1556 	if ((r = hc_rename(&DstHost, src, dst)) < 0)
1557 		hc_chflags(&DstHost, dst, flags);
1558 #endif
1559     }
1560     return(r);
1561 }
1562 
1563 static int
1564 xlink(const char *src, const char *dst, u_long flags)
1565 {
1566     int r;
1567 #ifdef _ST_FLAGS_PRESENT_
1568     int e;
1569 #endif
1570 
1571     r = 0;
1572 
1573     if ((r = hc_link(&DstHost, src, dst)) < 0) {
1574 #ifdef _ST_FLAGS_PRESENT_
1575 	hc_chflags(&DstHost, src, 0);
1576 	r = hc_link(&DstHost, src, dst);
1577 	e = errno;
1578 	hc_chflags(&DstHost, src, flags);
1579 	errno = e;
1580 #endif
1581     }
1582     if (r == 0)
1583 	    ++CountLinkedItems;
1584     return(r);
1585 }
1586 
1587 static int
1588 xremove(struct HostConf *host, const char *path)
1589 {
1590     int res;
1591 
1592     res = hc_remove(host, path);
1593 #ifdef _ST_FLAGS_PRESENT_
1594     if (res == -EPERM) {
1595 	hc_chflags(host, path, 0);
1596 	res = hc_remove(host, path);
1597     }
1598 #endif
1599     return(res);
1600 }
1601 
1602