4 * CPDUP <options> source destination
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.
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.
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
28 * - does not copy file if mtime, flags, perms, and size match unless
31 * - copies to temporary and renames-over the original, allowing
32 * you to update live systems
34 * - copies uid, gid, mtime, perms, flags, softlinks, devices, hardlinks,
35 * and recurses through directories.
37 * - accesses a per-directory exclusion file, .cpignore, containing
38 * standard wildcarded ( ? / * style, NOT regex) exclusions.
40 * - tries to play permissions and flags smart in regards to overwriting
41 * schg files and doing related stuff.
43 * - Can do MD5 consistancy checks
45 * - Is able to do incremental mirroring/backups via hardlinks from
46 * the 'previous' version (supplied with -H path).
48 * $DragonFly: src/bin/cpdup/cpdup.c,v 1.32 2008/11/11 04:36:00 dillon Exp $
52 * Example: cc -O cpdup.c -o cpdup -lcrypto
54 * ".MD5.CHECKSUMS" contains md5 checksumms for the current directory.
55 * This file is stored on the source.
63 #define HMASK (HSIZE-1)
65 #define HLMASK (HLSIZE - 1)
67 #define GETBUFSIZE 8192
68 #define GETPATHSIZE 2048
69 #define GETLINKSIZE 1024
70 #define GETIOSIZE 65536
72 #ifndef _ST_FLAGS_PRESENT_
73 #define st_flags st_mode
78 struct Node *no_HNext;
99 typedef struct copy_info {
106 static struct hlink *hltable[HLSIZE];
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);
121 #define FlagsMatch(st1, st2) 1
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);
139 int AskConfirmation = 1;
156 const char *ssh_argv[16];
159 const char *UseCpFile;
160 const char *MD5CacheFile;
161 const char *FSMIDCacheFile;
162 const char *UseHLPath;
164 static int DstBaseLen;
165 static int HardLinkCount;
166 static int GroupCount;
167 static gid_t *GroupList;
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;
178 static struct HostConf SrcHost;
179 static struct HostConf DstHost;
182 main(int ac, char **av)
189 struct timeval start;
190 struct copy_info info;
192 signal(SIGPIPE, SIG_IGN);
194 gettimeofday(&start, NULL);
196 while ((opt = getopt(ac, av, ":CdF:fH:hIi:j:K:klM:mnoqRSs:uVvX:x")) != -1) {
206 fatal("too many -F options");
207 ssh_argv[ssh_argc++] = optarg;
223 AskConfirmation = getbool(optarg);
226 DeviceOpt = getbool(optarg);
230 FSMIDCacheFile = optarg;
234 FSMIDCacheFile = ".FSMID.CHECK";
242 MD5CacheFile = optarg;
246 MD5CacheFile = ".MD5.CHECKSUMS";
264 SafetyOpt = getbool(optarg);
267 setvbuf(stdout, NULL, _IOLBF, 0);
279 UseCpFile = ".cpignore";
282 fatal("missing argument for option: -%c\n", optopt);
286 fatal("illegal option: -%c\n", optopt);
302 fatal("too many arguments");
305 * If we are told to go into slave mode, run the HC protocol
308 DstRootPrivs = (geteuid() == 0);
314 * Extract the source and/or/neither target [user@]host and
315 * make any required connections.
317 if (src && (ptr = SplitRemote(&src)) != NULL) {
321 fatal("The MD5 options are not currently supported for remote sources");
322 if (hc_connect(&SrcHost, ReadOnlyOpt) < 0)
324 } else if (ReadOnlyOpt)
325 fatal("The -R option is only supported for remote sources");
327 if (dst && (ptr = SplitRemote(&dst)) != NULL) {
331 fatal("The FSMID options are not currently supported for remote targets");
332 if (hc_connect(&DstHost, 0) < 0)
337 * dst may be NULL only if -m option is specified,
338 * which forces an update of the MD5 checksums
340 if (dst == NULL && UseMD5Opt == 0) {
346 DstRootPrivs = (hc_geteuid(&DstHost) == 0);
348 GroupCount = hc_getgroups(&DstHost, &GroupList);
352 fprintf(stderr, "DstRootPrivs == %s\n", DstRootPrivs ? "true" : "false");
353 fprintf(stderr, "GroupCount == %d\n", GroupCount);
354 for (i = 0; i < GroupCount; i++)
355 fprintf(stderr, "Group[%d] == %d\n", i, GroupList[i]);
358 bzero(&info, sizeof(info));
360 DstBaseLen = strlen(dst);
363 info.sdevNo = (dev_t)-1;
364 info.ddevNo = (dev_t)-1;
365 i = DoCopy(&info, NULL, -1);
369 info.sdevNo = (dev_t)-1;
370 info.ddevNo = (dev_t)-1;
371 i = DoCopy(&info, NULL, -1);
378 if (SummaryOpt && i == 0) {
382 gettimeofday(&end, NULL);
384 /* don't count stat's in our byte statistics */
385 CountSourceBytes += sizeof(struct stat) * CountSourceItems;
386 CountSourceReadBytes += sizeof(struct stat) * CountSourceItems;
387 CountWriteBytes += sizeof(struct stat) * CountCopiedItems;
388 CountWriteBytes += sizeof(struct stat) * CountRemovedItems;
391 duration = (end.tv_sec - start.tv_sec);
392 duration += (double)(end.tv_usec - start.tv_usec) / 1000000.0;
395 logstd("cpdup completed successfully\n");
396 logstd("%lld bytes source, %lld src bytes read, %lld tgt bytes read\n"
397 "%lld bytes written (%.1fX speedup)\n",
398 (long long)CountSourceBytes,
399 (long long)CountSourceReadBytes,
400 (long long)CountTargetReadBytes,
401 (long long)CountWriteBytes,
402 ((double)CountSourceBytes * 2.0) / ((double)(CountSourceReadBytes + CountTargetReadBytes + CountWriteBytes)));
403 logstd("%lld source items, %lld items copied, %lld items linked, "
404 "%lld things deleted\n",
405 (long long)CountSourceItems,
406 (long long)CountCopiedItems,
407 (long long)CountLinkedItems,
408 (long long)CountRemovedItems);
409 logstd("%.1f seconds %5d Kbytes/sec synced %5d Kbytes/sec scanned\n",
411 (int)((CountSourceReadBytes + CountTargetReadBytes + CountWriteBytes) / duration / 1024.0),
412 (int)(CountSourceBytes / duration / 1024.0));
414 exit((i == 0) ? 0 : 1);
418 getbool(const char *str)
420 if (strcmp(str, "0") == 0)
422 if (strcmp(str, "1") == 0)
424 fatal("option requires boolean argument (0 or 1): -%c\n", optopt);
430 * Check if path specifies a remote path, using the same syntax as scp(1),
431 * i.e. a path is considered remote if the first colon is not preceded by
432 * a slash, so e.g. "./foo:bar" is considered local.
433 * If a remote path is detected, the colon is replaced with a null byte,
434 * and the return value is a pointer to the next character.
435 * Otherwise NULL is returned.
437 * A path prefix of localhost is the same as a locally specified file or
438 * directory path, but prevents any further interpretation of the path
439 * as being a remote hostname (for paths that have colons in them).
442 SplitRemote(char **pathp)
447 if (path[(cindex = strcspn(path, ":/"))] == ':') {
449 if (strcmp(path, "localhost") != 0)
450 return (path + cindex);
451 *pathp = path + cindex;
457 * Check if group g is in our GroupList.
459 * Typically the number of groups a user belongs to isn't large
460 * enough to warrant more effort than a simple linear search.
461 * However, we perform an optimization by moving a group to the
462 * top of the list when we have a hit. This assumes that there
463 * isn't much variance in the gids of files that a non-root user
464 * copies. So most of the time the search will terminate on the
465 * first element of the list.
468 ChgrpAllowed(gid_t g)
472 for (i = 0; i < GroupCount; i++)
473 if (GroupList[i] == g) {
475 /* Optimize: Move g to the front of the list. */
477 GroupList[i] = GroupList[i - 1];
486 * The following two functions return true if the ownership (UID + GID)
487 * or the flags of two files match, respectively.
489 * Only perform weak checking if we don't have sufficient privileges on
490 * the target machine, so we don't waste transfers with things that are
491 * bound to fail anyway.
494 OwnerMatch(struct stat *st1, struct stat *st2)
497 /* Both UID and GID must match. */
498 return (st1->st_uid == st2->st_uid && st1->st_gid == st2->st_gid);
500 /* Ignore UID, and also ignore GID if we can't chgrp to that group. */
501 return (st1->st_gid == st2->st_gid || !ChgrpAllowed(st1->st_gid));
504 #ifdef _ST_FLAGS_PRESENT_
506 FlagsMatch(struct stat *st1, struct stat *st2)
509 * Ignore UF_ARCHIVE. It gets set automatically by the filesystem, for
510 * filesystems that support it. If the destination filesystem supports it, but
511 * it's cleared on the source file, then multiple invocations of cpdup would
512 * all try to copy the file because the flags wouldn't match.
514 * When unpriveleged, ignore flags we can't set
516 u_long ignored = DstRootPrivs ? 0 : SF_SETTABLE;
519 ignored |= UF_ARCHIVE;
521 return (((st1->st_flags ^ st2->st_flags) & ~ignored) == 0);
526 static struct hlink *
527 hltlookup(struct stat *stp)
532 n = stp->st_ino & HLMASK;
534 for (hl = hltable[n]; hl; hl = hl->next) {
535 if (hl->ino == stp->st_ino) {
544 static struct hlink *
545 hltadd(struct stat *stp, const char *path)
548 int plen = strlen(path);
551 new = malloc(offsetof(struct hlink, name[plen + 1]));
553 fatal("out of memory");
556 /* initialize and link the new element into the table */
557 new->ino = stp->st_ino;
558 new->dino = (ino_t)-1;
560 bcopy(path, new->name, plen + 1);
563 n = stp->st_ino & HLMASK;
564 new->next = hltable[n];
566 hltable[n]->prev = new;
573 hltsetdino(struct hlink *hl, ino_t inum)
579 hltdelete(struct hlink *hl)
581 assert(hl->refs == 1);
585 hl->next->prev = hl->prev;
586 hl->prev->next = hl->next;
589 hl->next->prev = NULL;
591 hltable[hl->ino & HLMASK] = hl->next;
598 hltrels(struct hlink *hl)
600 assert(hl->refs == 1);
605 * If UseHLPath is defined check to see if the file in question is
606 * the same as the source file, and if it is return a pointer to the
607 * -H path based file for hardlinking. Else return NULL.
610 checkHLPath(struct stat *st1, const char *spath, const char *dpath)
616 if (asprintf(&hpath, "%s%s", UseHLPath, dpath + DstBaseLen) < 0)
617 fatal("out of memory");
620 * stat info matches ?
622 if (hc_stat(&DstHost, hpath, &sthl) < 0 ||
623 st1->st_size != sthl.st_size ||
624 st1->st_mtime != sthl.st_mtime ||
625 !OwnerMatch(st1, &sthl) ||
626 !FlagsMatch(st1, &sthl)
633 * If ForceOpt or ValidateOpt is set we have to compare the files
635 if (ForceOpt || ValidateOpt) {
636 error = validate_check(spath, hpath);
646 * Return 0 if the contents of the file <spath> matches the contents of
650 validate_check(const char *spath, const char *dpath)
656 fd1 = hc_open(&SrcHost, spath, O_RDONLY, 0);
657 fd2 = hc_open(&DstHost, dpath, O_RDONLY, 0);
660 if (fd1 >= 0 && fd2 >= 0) {
663 char *iobuf1 = malloc(GETIOSIZE);
664 char *iobuf2 = malloc(GETIOSIZE);
666 while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
667 CountSourceReadBytes += n;
668 x = hc_read(&DstHost, fd2, iobuf2, GETIOSIZE);
670 CountTargetReadBytes += x;
673 if (bcmp(iobuf1, iobuf2, n) != 0)
682 hc_close(&SrcHost, fd1);
684 hc_close(&DstHost, fd2);
689 DoCopy(copy_info_t info, struct stat *stat1, int depth)
691 const char *spath = info->spath;
692 const char *dpath = info->dpath;
693 dev_t sdevNo = info->sdevNo;
694 dev_t ddevNo = info->ddevNo;
697 unsigned long st2_flags;
698 int r, mres, fres, st2Valid;
702 r = mres = fres = st2Valid = 0;
708 if (hc_lstat(&SrcHost, spath, &st1) != 0) {
715 /* skip snapshot files because they're sparse and _huge_ */
716 if (stat1->st_flags & SF_SNAPSHOT)
719 st2.st_mode = 0; /* in case lstat fails */
720 st2.st_flags = 0; /* in case lstat fails */
721 if (dpath && hc_lstat(&DstHost, dpath, &st2) == 0) {
723 #ifdef _ST_FLAGS_PRESENT_
724 st2_flags = st2.st_flags;
728 if (S_ISREG(stat1->st_mode))
729 size = stat1->st_size;
735 if (S_ISREG(stat1->st_mode) && stat1->st_nlink > 1 && dpath) {
736 if ((hln = hltlookup(stat1)) != NULL) {
740 if (st2.st_ino == hln->dino) {
742 * hard link is already correct, nothing to do
745 logstd("%-32s nochange\n", (dpath) ? dpath : spath);
746 if (hln->nlinked == stat1->st_nlink) {
755 * hard link is not correct, attempt to unlink it
757 if (xremove(&DstHost, dpath) < 0) {
758 logerr("%-32s hardlink: unable to unlink: %s\n",
759 ((dpath) ? dpath : spath), strerror(errno));
768 if (xlink(hln->name, dpath, stat1->st_flags) < 0) {
769 int tryrelink = (errno == EMLINK);
770 logerr("%-32s hardlink: unable to link to %s: %s\n",
771 (dpath ? dpath : spath), hln->name, strerror(errno)
776 logerr("%-20s hardlink: will attempt to copy normally\n",
777 (dpath ? dpath : spath));
782 if (hln->nlinked == stat1->st_nlink) {
788 logstd("%-32s hardlink: %s\n",
789 (dpath ? dpath : spath),
790 (st2Valid ? "relinked" : "linked")
801 * first instance of hardlink must be copied normally
804 hln = hltadd(stat1, dpath);
809 * Do we need to copy the file/dir/link/whatever? Early termination
810 * if we do not. Always redo links. Directories are always traversed
811 * except when the FSMID options are used.
813 * NOTE: st2Valid is true only if dpath != NULL *and* dpath stats good.
818 && stat1->st_mode == st2.st_mode
819 && FlagsMatch(stat1, &st2)
821 if (S_ISLNK(stat1->st_mode) || S_ISDIR(stat1->st_mode)) {
823 * If FSMID tracking is turned on we can avoid recursing through
824 * an entire directory subtree if the FSMID matches.
826 #ifdef _ST_FSMID_PRESENT_
828 (UseFSMIDOpt && (fres = fsmid_check(stat1->st_fsmid, dpath)) == 0)
830 if (VerboseOpt >= 3) {
831 if (UseFSMIDOpt) /* always true!?! */
832 logstd("%-32s fsmid-nochange\n", (dpath ? dpath : spath));
834 logstd("%-32s nochange\n", (dpath ? dpath : spath));
842 stat1->st_size == st2.st_size &&
843 (ValidateOpt == 2 || stat1->st_mtime == st2.st_mtime) &&
844 OwnerMatch(stat1, &st2)
846 && (UseMD5Opt == 0 || !S_ISREG(stat1->st_mode) ||
847 (mres = md5_check(spath, dpath)) == 0)
849 #ifdef _ST_FSMID_PRESENT_
850 && (UseFSMIDOpt == 0 ||
851 (fres = fsmid_check(stat1->st_fsmid, dpath)) == 0)
853 && (ValidateOpt == 0 || !S_ISREG(stat1->st_mode) ||
854 validate_check(spath, dpath) == 0)
857 * The files are identical, but if we are running as
858 * root we might need to adjust ownership/group/flags.
861 int changedflags = 0;
864 hltsetdino(hln, st2.st_ino);
866 if (!OwnerMatch(stat1, &st2)) {
867 hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid);
870 #ifdef _ST_FLAGS_PRESENT_
871 if (!FlagsMatch(stat1, &st2)) {
872 hc_chflags(&DstHost, dpath, stat1->st_flags);
876 if (VerboseOpt >= 3) {
879 logstd("%-32s md5-nochange",
880 (dpath ? dpath : spath));
884 logstd("%-32s fsmid-nochange",
885 (dpath ? dpath : spath));
886 } else if (ValidateOpt) {
887 logstd("%-32s nochange (contents validated)",
888 (dpath ? dpath : spath));
890 logstd("%-32s nochange", (dpath ? dpath : spath));
893 logstd(" (uid/gid differ)");
895 logstd(" (flags differ)");
898 CountSourceBytes += size;
905 if (st2Valid && !S_ISDIR(stat1->st_mode) && S_ISDIR(st2.st_mode)) {
907 logerr("%-32s SAFETY - refusing to copy file over directory\n",
908 (dpath ? dpath : spath)
912 goto done; /* continue with the cpdup anyway */
914 if (QuietOpt == 0 || AskConfirmation) {
915 logstd("%-32s WARNING: non-directory source will blow away\n"
916 "%-32s preexisting dest directory, continuing anyway!\n",
917 ((dpath) ? dpath : spath), "");
920 RemoveRecur(dpath, ddevNo, &st2);
925 * The various comparisons failed, copy it.
927 if (S_ISDIR(stat1->st_mode)) {
931 logerr("%-32s/ fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
934 if (!st2Valid || S_ISDIR(st2.st_mode) == 0) {
936 xremove(&DstHost, dpath);
937 if (hc_mkdir(&DstHost, dpath, stat1->st_mode | 0700) != 0) {
938 logerr("%s: mkdir failed: %s\n",
939 (dpath ? dpath : spath), strerror(errno));
943 if (hc_lstat(&DstHost, dpath, &st2) != 0) {
944 if (NotForRealOpt == 0)
945 logerr("%s: lstat of newly made dir failed: %s\n",
946 (dpath ? dpath : spath), strerror(errno));
953 if (!OwnerMatch(stat1, &st2) &&
954 hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid) != 0
956 logerr("%s: chown of newly made dir failed: %s\n",
957 (dpath ? dpath : spath), strerror(errno));
959 /* Note that we should not set skipdir = 1 here. */
963 logstd("%-32s mkdir-ok\n", (dpath ? dpath : spath));
967 * Directory must be scanable by root for cpdup to
968 * work. We'll fix it later if the directory isn't
969 * supposed to be readable ( which is why we fixup
970 * st2.st_mode to match what we did ).
972 if ((st2.st_mode & 0700) != 0700) {
973 hc_chmod(&DstHost, dpath, st2.st_mode | 0700);
977 logstd("%s\n", dpath ? dpath : spath);
982 * When copying a directory, stop if the source crosses a mount
985 if (sdevNo != (dev_t)-1 && stat1->st_dev != sdevNo)
988 sdevNo = stat1->st_dev;
991 * When copying a directory, stop if the destination crosses
994 * The target directory will have been created and stat'd
995 * for st2 if it did not previously exist. st2Valid is left
996 * as a flag. If the stat failed st2 will still only have its
997 * default initialization.
999 * So we simply assume here that the directory is within the
1000 * current target mount if we had to create it (aka st2Valid is 0)
1001 * and we leave ddevNo alone.
1004 if (ddevNo != (dev_t)-1 && st2.st_dev != ddevNo)
1007 ddevNo = st2.st_dev;
1011 List *list = malloc(sizeof(List));
1015 logstd("Scanning %s ...\n", spath);
1017 if (ScanDir(list, &SrcHost, spath, &CountSourceReadBytes, 0) == 0) {
1019 while ((node = IterateList(list, node, 0)) != NULL) {
1021 char *ndpath = NULL;
1023 nspath = mprintf("%s/%s", spath, node->no_Name);
1025 ndpath = mprintf("%s/%s", dpath, node->no_Name);
1027 info->spath = nspath;
1028 info->dpath = ndpath;
1029 info->sdevNo = sdevNo;
1030 info->ddevNo = ddevNo;
1032 r += DoCopy(info, node->no_Stat, depth);
1034 r += DoCopy(info, node->no_Stat, depth + 1);
1043 * Remove files/directories from destination that do not appear
1046 if (dpath && ScanDir(list, &DstHost, dpath,
1047 &CountTargetReadBytes, 3) == 0) {
1049 while ((node = IterateList(list, node, 3)) != NULL) {
1051 * If object does not exist in source or .cpignore
1052 * then recursively remove it.
1056 ndpath = mprintf("%s/%s", dpath, node->no_Name);
1057 RemoveRecur(ndpath, ddevNo, node->no_Stat);
1066 if (dpath && st2Valid) {
1067 struct timeval tv[2];
1069 if (ForceOpt || !OwnerMatch(stat1, &st2))
1070 hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid);
1071 if (stat1->st_mode != st2.st_mode)
1072 hc_chmod(&DstHost, dpath, stat1->st_mode);
1073 #ifdef _ST_FLAGS_PRESENT_
1074 if (!FlagsMatch(stat1, &st2))
1075 hc_chflags(&DstHost, dpath, stat1->st_flags);
1077 if (ForceOpt || stat1->st_mtime != st2.st_mtime) {
1078 bzero(tv, sizeof(tv));
1079 tv[0].tv_sec = stat1->st_mtime;
1080 tv[1].tv_sec = stat1->st_mtime;
1081 hc_utimes(&DstHost, dpath, tv);
1084 } else if (dpath == NULL) {
1086 * If dpath is NULL, we are just updating the MD5
1089 if (UseMD5Opt && S_ISREG(stat1->st_mode)) {
1090 mres = md5_check(spath, NULL);
1092 if (VerboseOpt > 1) {
1094 logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1096 logstd("%-32s md5-ok\n", (dpath) ? dpath : spath);
1097 } else if (!QuietOpt && mres < 0) {
1098 logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1102 } else if (S_ISREG(stat1->st_mode)) {
1109 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1111 path = mprintf("%s", dpath);
1114 * Handle check failure message.
1118 logerr("%-32s md5-CHECK-FAILED\n", (dpath) ? dpath : spath);
1122 logerr("%-32s fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
1125 * Not quite ready to do the copy yet. If UseHLPath is defined,
1126 * see if we can hardlink instead.
1128 * If we can hardlink, and the target exists, we have to remove it
1129 * first or the hardlink will fail. This can occur in a number of
1130 * situations but most typically when the '-f -H' combination is
1133 if (UseHLPath && (hpath = checkHLPath(stat1, spath, dpath)) != NULL) {
1135 xremove(&DstHost, dpath);
1136 if (hc_link(&DstHost, hpath, dpath) == 0) {
1139 logstd("%-32s hardlinked(-H)\n",
1140 (dpath ? dpath : spath));
1146 * Shucks, we may have hit a filesystem hard linking limit,
1147 * we have to copy instead.
1152 if ((fd1 = hc_open(&SrcHost, spath, O_RDONLY, 0)) >= 0) {
1153 if ((fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL, 0600)) < 0) {
1155 * There could be a .tmp file from a previously interrupted
1156 * run, delete and retry. Fail if we still can't get at it.
1158 #ifdef _ST_FLAGS_PRESENT_
1159 hc_chflags(&DstHost, path, 0);
1161 hc_remove(&DstHost, path);
1162 fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600);
1166 char *iobuf1 = malloc(GETIOSIZE);
1170 * Matt: What about holes?
1173 while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
1175 if (hc_write(&DstHost, fd2, iobuf1, n) != n)
1179 hc_close(&DstHost, fd2);
1181 struct timeval tv[2];
1183 bzero(tv, sizeof(tv));
1184 tv[0].tv_sec = stat1->st_mtime;
1185 tv[1].tv_sec = stat1->st_mtime;
1187 if (DstRootPrivs || ChgrpAllowed(stat1->st_gid))
1188 hc_chown(&DstHost, path, stat1->st_uid, stat1->st_gid);
1189 hc_chmod(&DstHost, path, stat1->st_mode);
1190 #ifdef _ST_FLAGS_PRESENT_
1191 if (stat1->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
1192 hc_utimes(&DstHost, path, tv);
1194 hc_utimes(&DstHost, path, tv);
1196 if (st2Valid && xrename(path, dpath, st2_flags) != 0) {
1197 logerr("%-32s rename-after-copy failed: %s\n",
1198 (dpath ? dpath : spath), strerror(errno)
1203 logstd("%-32s copy-ok\n", (dpath ? dpath : spath));
1204 #ifdef _ST_FLAGS_PRESENT_
1205 if (DstRootPrivs ? stat1->st_flags : stat1->st_flags & UF_SETTABLE)
1206 hc_chflags(&DstHost, dpath, stat1->st_flags);
1209 #ifdef _ST_FLAGS_PRESENT_
1210 if ((stat1->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE)) == 0)
1211 hc_utimes(&DstHost, dpath, tv);
1213 CountSourceReadBytes += size;
1214 CountWriteBytes += size;
1215 CountSourceBytes += size;
1219 logerr("%-32s %s failed: %s\n",
1220 (dpath ? dpath : spath), op, strerror(errno)
1222 hc_remove(&DstHost, path);
1227 logerr("%-32s create (uid %d, euid %d) failed: %s\n",
1228 (dpath ? dpath : spath), getuid(), geteuid(),
1233 hc_close(&SrcHost, fd1);
1235 logerr("%-32s copy: open failed: %s\n",
1236 (dpath ? dpath : spath),
1245 if (!r && hc_stat(&DstHost, dpath, &st2) == 0) {
1246 hltsetdino(hln, st2.st_ino);
1252 } else if (S_ISLNK(stat1->st_mode)) {
1253 char *link1 = malloc(GETLINKSIZE);
1254 char *link2 = malloc(GETLINKSIZE);
1259 n1 = hc_readlink(&SrcHost, spath, link1, GETLINKSIZE - 1);
1261 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1262 n2 = hc_readlink(&DstHost, dpath, link2, GETLINKSIZE - 1);
1264 path = mprintf("%s", dpath);
1268 if (ForceOpt || n1 != n2 || bcmp(link1, link2, n1) != 0) {
1269 hc_umask(&DstHost, ~stat1->st_mode);
1270 xremove(&DstHost, path);
1272 if (hc_symlink(&DstHost, link1, path) < 0) {
1273 logerr("%-32s symlink (%s->%s) failed: %s\n",
1274 (dpath ? dpath : spath), link1, path,
1279 if (DstRootPrivs || ChgrpAllowed(stat1->st_gid))
1280 hc_lchown(&DstHost, path, stat1->st_uid, stat1->st_gid);
1282 * there is no lchmod() or lchflags(), we
1283 * cannot chmod or chflags a softlink.
1285 if (st2Valid && xrename(path, dpath, st2_flags) != 0) {
1286 logerr("%-32s rename softlink (%s->%s) failed: %s\n",
1287 (dpath ? dpath : spath),
1288 path, dpath, strerror(errno));
1289 } else if (VerboseOpt) {
1290 logstd("%-32s softlink-ok\n", (dpath ? dpath : spath));
1292 hc_umask(&DstHost, 000);
1293 CountWriteBytes += n1;
1297 if (VerboseOpt >= 3)
1298 logstd("%-32s nochange", (dpath ? dpath : spath));
1299 if (!OwnerMatch(stat1, &st2)) {
1300 hc_lchown(&DstHost, dpath, stat1->st_uid, stat1->st_gid);
1301 if (VerboseOpt >= 3)
1302 logstd(" (uid/gid differ)");
1304 if (VerboseOpt >= 3)
1307 CountSourceBytes += n1;
1308 CountSourceReadBytes += n1;
1310 CountTargetReadBytes += n2;
1314 logerr("%-32s softlink-failed\n", (dpath ? dpath : spath));
1319 } else if ((S_ISCHR(stat1->st_mode) || S_ISBLK(stat1->st_mode)) && DeviceOpt) {
1324 stat1->st_mode != st2.st_mode ||
1325 stat1->st_rdev != st2.st_rdev ||
1326 !OwnerMatch(stat1, &st2)
1329 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1330 xremove(&DstHost, path);
1332 path = mprintf("%s", dpath);
1335 if (hc_mknod(&DstHost, path, stat1->st_mode, stat1->st_rdev) == 0) {
1336 hc_chmod(&DstHost, path, stat1->st_mode);
1337 hc_chown(&DstHost, path, stat1->st_uid, stat1->st_gid);
1339 xremove(&DstHost, dpath);
1340 if (st2Valid && xrename(path, dpath, st2_flags) != 0) {
1341 logerr("%-32s dev-rename-after-create failed: %s\n",
1342 (dpath ? dpath : spath),
1345 } else if (VerboseOpt) {
1346 logstd("%-32s dev-ok\n", (dpath ? dpath : spath));
1351 logerr("%-32s dev failed: %s\n",
1352 (dpath ? dpath : spath), strerror(errno)
1356 if (VerboseOpt >= 3)
1357 logstd("%-32s nochange\n", (dpath ? dpath : spath));
1365 if (hln->dino == (ino_t)-1) {
1367 /*hln = NULL; unneeded */
1376 ScanDir(List *list, struct HostConf *host, const char *path,
1377 int64_t *CountReadBytes, int n)
1380 struct HostConf *cphost;
1381 struct HCDirEntry *den;
1382 struct stat *statptr;
1386 * scan .cpignore file for files/directories to ignore
1387 * (only in the source directory, i.e. if n == 0).
1393 char *buf = malloc(GETBUFSIZE);
1397 if (UseCpFile[0] == '/') {
1398 fpath = mprintf("%s", UseCpFile);
1401 fpath = mprintf("%s/%s", path, UseCpFile);
1402 AddList(list, strrchr(fpath, '/') + 1, 1, NULL);
1405 fd = hc_open(cphost, fpath, O_RDONLY, 0);
1408 while ((nread = hc_read(cphost, fd, buf + bufused,
1409 GETBUFSIZE - bufused - 1)) > 0) {
1410 *CountReadBytes += nread;
1413 for (next = buf; (nl = strchr(next, '\n')); next = nl+1) {
1415 AddList(list, next, 1, NULL);
1417 bufused = strlen(next);
1419 bcopy(next, buf, bufused);
1422 /* last line has no trailing newline */
1424 AddList(list, buf, 1, NULL);
1426 hc_close(cphost, fd);
1433 * Automatically exclude MD5CacheFile that we create on the
1434 * source from the copy to the destination.
1436 * Automatically exclude a FSMIDCacheFile on the source that
1437 * would otherwise overwrite the one we maintain on the target.
1440 AddList(list, MD5CacheFile, 1, NULL);
1442 AddList(list, FSMIDCacheFile, 1, NULL);
1445 if ((dir = hc_opendir(host, path)) == NULL)
1447 while ((den = hc_readdir(host, dir, &statptr)) != NULL) {
1451 if (strcmp(den->d_name, ".") != 0 && strcmp(den->d_name, "..") != 0) {
1452 if (UseCpFile && UseCpFile[0] == '/') {
1453 if (CheckList(list, path, den->d_name) == 0)
1456 AddList(list, den->d_name, n, statptr);
1459 hc_closedir(host, dir);
1469 RemoveRecur(const char *dpath, dev_t devNo, struct stat *dstat)
1473 if (dstat == NULL) {
1474 if (hc_lstat(&DstHost, dpath, &st) == 0)
1477 if (dstat != NULL) {
1478 if (devNo == (dev_t)-1)
1479 devNo = dstat->st_dev;
1480 if (dstat->st_dev == devNo) {
1481 if (S_ISDIR(dstat->st_mode)) {
1484 if ((dir = hc_opendir(&DstHost, dpath)) != NULL) {
1485 List *list = malloc(sizeof(List));
1487 struct HCDirEntry *den;
1490 while ((den = hc_readdir(&DstHost, dir, &dstat)) != NULL) {
1491 if (strcmp(den->d_name, ".") == 0)
1493 if (strcmp(den->d_name, "..") == 0)
1495 AddList(list, den->d_name, 3, dstat);
1497 hc_closedir(&DstHost, dir);
1498 while ((node = IterateList(list, node, 3)) != NULL) {
1501 ndpath = mprintf("%s/%s", dpath, node->no_Name);
1502 RemoveRecur(ndpath, devNo, node->no_Stat);
1508 if (AskConfirmation && NoRemoveOpt == 0) {
1510 if (xrmdir(&DstHost, dpath) < 0) {
1511 logerr("%-32s rmdir failed: %s\n",
1512 dpath, strerror(errno)
1515 CountRemovedItems++;
1520 logstd("%-32s not-removed\n", dpath);
1521 } else if (xrmdir(&DstHost, dpath) == 0) {
1523 logstd("%-32s rmdir-ok\n", dpath);
1524 CountRemovedItems++;
1526 logerr("%-32s rmdir failed: %s\n",
1527 dpath, strerror(errno)
1532 if (AskConfirmation && NoRemoveOpt == 0) {
1534 if (xremove(&DstHost, dpath) < 0) {
1535 logerr("%-32s remove failed: %s\n",
1536 dpath, strerror(errno)
1539 CountRemovedItems++;
1544 logstd("%-32s not-removed\n", dpath);
1545 } else if (xremove(&DstHost, dpath) == 0) {
1547 logstd("%-32s remove-ok\n", dpath);
1548 CountRemovedItems++;
1550 logerr("%-32s remove failed: %s\n",
1551 dpath, strerror(errno)
1561 InitList(List *list)
1563 bzero(list, sizeof(List));
1564 list->li_Node.no_Next = &list->li_Node;
1568 ResetList(List *list)
1572 while ((node = list->li_Node.no_Next) != &list->li_Node) {
1573 list->li_Node.no_Next = node->no_Next;
1574 if (node->no_Stat != NULL)
1575 free(node->no_Stat);
1582 IterateList(List *list, Node *node, int n)
1585 node = list->li_Node.no_Next;
1587 node = node->no_Next;
1588 while (node->no_Value != n && node != &list->li_Node)
1589 node = node->no_Next;
1590 return (node == &list->li_Node ? NULL : node);
1594 AddList(List *list, const char *name, int n, struct stat *st)
1600 * Scan against wildcards. Only a node value of 1 can be a wildcard
1601 * ( usually scanned from .cpignore )
1603 for (node = list->li_Hash[0]; node; node = node->no_HNext) {
1604 if (strcmp(name, node->no_Name) == 0 ||
1605 (n != 1 && node->no_Value == 1 &&
1606 fnmatch(node->no_Name, name, 0) == 0)
1608 return(node->no_Value);
1613 * Look for exact match
1617 for (node = list->li_Hash[hv]; node; node = node->no_HNext) {
1618 if (strcmp(name, node->no_Name) == 0) {
1619 return(node->no_Value);
1622 node = malloc(sizeof(Node) + strlen(name) + 1);
1624 fatal("out of memory");
1626 node->no_Next = list->li_Node.no_Next;
1627 list->li_Node.no_Next = node;
1629 node->no_HNext = list->li_Hash[hv];
1630 list->li_Hash[hv] = node;
1632 strcpy(node->no_Name, name);
1640 * Match against n=1 (cpignore) entries
1642 * Returns 0 on match, non-zero if no match
1645 CheckList(List *list, const char *path, const char *name)
1651 if (asprintf(&fpath, "%s/%s", path, name) < 0)
1652 fatal("out of memory");
1655 * Scan against wildcards. Only a node value of 1 can be a wildcard
1656 * ( usually scanned from .cpignore )
1658 for (node = list->li_Hash[0]; node; node = node->no_HNext) {
1659 if (node->no_Value != 1)
1661 if (fnmatch(node->no_Name, fpath, 0) == 0) {
1668 * Look for exact match
1671 for (node = list->li_Hash[hv]; node; node = node->no_HNext) {
1672 if (node->no_Value != 1)
1674 if (strcmp(fpath, node->no_Name) == 0) {
1685 shash(const char *s)
1692 if (*s == '*' || *s == '?' ||
1693 *s == '{' || *s == '}' ||
1694 *s == '[' || *s == ']' ||
1699 hv = (hv << 5) ^ *s ^ (hv >> 23);
1702 return(((hv >> 16) ^ hv) & HMASK);
1706 YesNo(const char *path)
1710 fprintf(stderr, "remove %s (Yes/No) [No]? ", path);
1713 first = ch = getchar();
1714 while (ch != '\n' && ch != EOF)
1716 return ((first == 'y' || first == 'Y'));
1720 * xrename() - rename with override
1722 * If the rename fails, attempt to override st_flags on the
1723 * destination and rename again. If that fails too, try to
1724 * set the flags back the way they were and give up.
1728 xrename(const char *src, const char *dst, u_long flags)
1732 if ((r = hc_rename(&DstHost, src, dst)) < 0) {
1733 #ifdef _ST_FLAGS_PRESENT_
1734 hc_chflags(&DstHost, dst, 0);
1735 if ((r = hc_rename(&DstHost, src, dst)) < 0)
1736 hc_chflags(&DstHost, dst, flags);
1743 xlink(const char *src, const char *dst, u_long flags)
1746 #ifdef _ST_FLAGS_PRESENT_
1750 if ((r = hc_link(&DstHost, src, dst)) < 0) {
1751 #ifdef _ST_FLAGS_PRESENT_
1752 hc_chflags(&DstHost, src, 0);
1753 r = hc_link(&DstHost, src, dst);
1755 hc_chflags(&DstHost, src, flags);
1765 xremove(struct HostConf *host, const char *path)
1769 res = hc_remove(host, path);
1770 #ifdef _ST_FLAGS_PRESENT_
1771 if (res == -EPERM) {
1772 hc_chflags(host, path, 0);
1773 res = hc_remove(host, path);
1780 xrmdir(struct HostConf *host, const char *path)
1784 res = hc_rmdir(host, path);
1785 #ifdef _ST_FLAGS_PRESENT_
1786 if (res == -EPERM) {
1787 hc_chflags(host, path, 0);
1788 res = hc_rmdir(host, path);