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