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