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