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 -lmd
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 struct hlink *hltable[HLSIZE];
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);
120 #define FlagsMatch(st1, st2) 1
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);
137 int AskConfirmation = 1;
151 int EnableDirectoryRetries;
156 const char *ssh_argv[16];
160 const char *UseCpFile;
161 const char *UseHLPath;
162 const char *MD5CacheFile;
163 const char *FSMIDCacheFile;
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;
174 struct HostConf SrcHost;
175 struct HostConf DstHost;
178 main(int ac, char **av)
185 struct timeval start;
186 struct copy_info info;
188 signal(SIGPIPE, SIG_IGN);
190 gettimeofday(&start, NULL);
192 while ((opt = getopt(ac, av, ":CdF:fH:Ii:j:K:klM:mopqRSs:uVvX:x")) != -1) {
194 /* TODO: sort the branches */
218 UseCpFile = ".cpignore";
228 fatal("too many -F options");
229 ssh_argv[ssh_argc++] = optarg;
241 AskConfirmation = getbool(optarg);
244 DeviceOpt = getbool(optarg);
247 SafetyOpt = getbool(optarg);
254 FSMIDCacheFile = ".FSMID.CHECK";
258 FSMIDCacheFile = optarg;
262 MD5CacheFile = optarg;
266 MD5CacheFile = ".MD5.CHECKSUMS";
269 setvbuf(stdout, NULL, _IOLBF, 0);
272 fatal("missing argument for option: -%c\n", optopt);
276 fatal("illegal option: -%c\n", optopt);
292 fatal("too many arguments");
295 * If we are told to go into slave mode, run the HC protocol
298 DstRootPrivs = (geteuid() == 0);
304 * Extract the source and/or/neither target [user@]host and
305 * make any required connections.
307 if (src && (ptr = SplitRemote(src)) != NULL) {
311 fatal("The MD5 options are not currently supported for remote sources");
312 if (hc_connect(&SrcHost, ReadOnlyOpt) < 0)
314 } else if (ReadOnlyOpt)
315 fatal("The -R option is only supported for remote sources");
317 if (dst && (ptr = SplitRemote(dst)) != NULL) {
321 fatal("The FSMID options are not currently supported for remote targets");
322 if (hc_connect(&DstHost, 0) < 0)
327 * dst may be NULL only if -m option is specified,
328 * which forces an update of the MD5 checksums
330 if (dst == NULL && UseMD5Opt == 0) {
336 DstRootPrivs = (hc_geteuid(&DstHost) == 0);
338 GroupCount = hc_getgroups(&DstHost, &GroupList);
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]);
348 bzero(&info, sizeof(info));
350 DstBaseLen = strlen(dst);
353 info.sdevNo = (dev_t)-1;
354 info.ddevNo = (dev_t)-1;
355 i = DoCopy(&info, NULL, -1);
359 info.sdevNo = (dev_t)-1;
360 info.ddevNo = (dev_t)-1;
361 i = DoCopy(&info, NULL, -1);
368 if (SummaryOpt && i == 0) {
372 gettimeofday(&end, NULL);
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;
381 duration = (end.tv_sec - start.tv_sec);
382 duration += (double)(end.tv_usec - start.tv_usec) / 1000000.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",
401 (int)((CountSourceReadBytes + CountTargetReadBytes + CountWriteBytes) / duration / 1024.0),
402 (int)(CountSourceBytes / duration / 1024.0));
404 exit((i == 0) ? 0 : 1);
408 getbool(const char *str)
410 if (strcmp(str, "0") == 0)
412 if (strcmp(str, "1") == 0)
414 fatal("option requires boolean argument (0 or 1): -%c\n", optopt);
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.
428 SplitRemote(char *path)
432 if (path[(cindex = strcspn(path, ":/"))] == ':') {
434 return (path + cindex);
440 * Check if group g is in our GroupList.
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.
451 ChgrpAllowed(gid_t g)
455 for (i = 0; i < GroupCount; i++)
456 if (GroupList[i] == g) {
458 /* Optimize: Move g to the front of the list. */
460 GroupList[i] = GroupList[i - 1];
469 * The following two functions return true if the ownership (UID + GID)
470 * or the flags of two files match, respectively.
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.
477 OwnerMatch(struct stat *st1, struct stat *st2)
480 /* Both UID and GID must match. */
481 return (st1->st_uid == st2->st_uid && st1->st_gid == st2->st_gid);
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));
487 #ifdef _ST_FLAGS_PRESENT_
489 FlagsMatch(struct stat *st1, struct stat *st2)
492 return (st1->st_flags == st2->st_flags);
494 /* Only consider the user-settable flags. */
495 return (((st1->st_flags ^ st2->st_flags) & UF_SETTABLE) == 0);
500 static struct hlink *
501 hltlookup(struct stat *stp)
506 n = stp->st_ino & HLMASK;
508 for (hl = hltable[n]; hl; hl = hl->next) {
509 if (hl->ino == stp->st_ino) {
518 static struct hlink *
519 hltadd(struct stat *stp, const char *path)
522 int plen = strlen(path);
525 new = malloc(offsetof(struct hlink, name[plen + 1]));
527 fatal("out of memory");
530 /* initialize and link the new element into the table */
531 new->ino = stp->st_ino;
532 new->dino = (ino_t)-1;
534 bcopy(path, new->name, plen + 1);
537 n = stp->st_ino & HLMASK;
538 new->next = hltable[n];
540 hltable[n]->prev = new;
547 hltsetdino(struct hlink *hl, ino_t inum)
553 hltdelete(struct hlink *hl)
555 assert(hl->refs == 1);
559 hl->next->prev = hl->prev;
560 hl->prev->next = hl->next;
563 hl->next->prev = NULL;
565 hltable[hl->ino & HLMASK] = hl->next;
572 hltrels(struct hlink *hl)
574 assert(hl->refs == 1);
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.
584 checkHLPath(struct stat *st1, const char *spath, const char *dpath)
590 asprintf(&hpath, "%s%s", UseHLPath, dpath + DstBaseLen);
593 * stat info matches ?
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)
606 * If ForceOpt or ValidateOpt is set we have to compare the files
608 if (ForceOpt || ValidateOpt) {
609 error = validate_check(spath, hpath);
619 * Return 0 if the contents of the file <spath> matches the contents of
623 validate_check(const char *spath, const char *dpath)
629 fd1 = hc_open(&SrcHost, spath, O_RDONLY, 0);
630 fd2 = hc_open(&DstHost, dpath, O_RDONLY, 0);
633 if (fd1 >= 0 && fd2 >= 0) {
636 char *iobuf1 = malloc(GETIOSIZE);
637 char *iobuf2 = malloc(GETIOSIZE);
639 while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
640 CountSourceReadBytes += n;
641 x = hc_read(&DstHost, fd2, iobuf2, GETIOSIZE);
643 CountTargetReadBytes += x;
646 if (bcmp(iobuf1, iobuf2, n) != 0)
655 hc_close(&SrcHost, fd1);
657 hc_close(&DstHost, fd2);
662 DoCopy(copy_info_t info, struct stat *stat1, int depth)
664 const char *spath = info->spath;
665 const char *dpath = info->dpath;
666 dev_t sdevNo = info->sdevNo;
667 dev_t ddevNo = info->ddevNo;
670 unsigned long st2_flags;
671 int r, mres, fres, st2Valid;
675 r = mres = fres = st2Valid = 0;
681 if (hc_lstat(&SrcHost, spath, &st1) != 0) {
688 /* skip snapshot files because they're sparse and _huge_ */
689 if (stat1->st_flags & SF_SNAPSHOT)
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) {
696 #ifdef _ST_FLAGS_PRESENT_
697 st2_flags = st2.st_flags;
701 if (S_ISREG(stat1->st_mode))
702 size = stat1->st_size;
708 if (S_ISREG(stat1->st_mode) && stat1->st_nlink > 1 && dpath) {
709 if ((hln = hltlookup(stat1)) != NULL) {
713 if (st2.st_ino == hln->dino) {
715 * hard link is already correct, nothing to do
718 logstd("%-32s nochange\n", (dpath) ? dpath : spath);
719 if (hln->nlinked == stat1->st_nlink) {
728 * hard link is not correct, attempt to unlink it
730 if (xremove(&DstHost, dpath) < 0) {
731 logerr("%-32s hardlink: unable to unlink: %s\n",
732 ((dpath) ? dpath : spath), strerror(errno));
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)
749 logerr("%-20s hardlink: will attempt to copy normally\n",
750 (dpath ? dpath : spath));
755 if (hln->nlinked == stat1->st_nlink) {
761 logstd("%-32s hardlink: %s\n",
762 (dpath ? dpath : spath),
763 (st2Valid ? "relinked" : "linked")
774 * first instance of hardlink must be copied normally
777 hln = hltadd(stat1, dpath);
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.
786 * NOTE: st2Valid is true only if dpath != NULL *and* dpath stats good.
791 && stat1->st_mode == st2.st_mode
792 && FlagsMatch(stat1, &st2)
794 if (S_ISLNK(stat1->st_mode) || S_ISDIR(stat1->st_mode)) {
796 * If FSMID tracking is turned on we can avoid recursing through
797 * an entire directory subtree if the FSMID matches.
799 #ifdef _ST_FSMID_PRESENT_
801 (UseFSMIDOpt && (fres = fsmid_check(stat1->st_fsmid, dpath)) == 0)
803 if (VerboseOpt >= 3) {
804 if (UseFSMIDOpt) /* always true!?! */
805 logstd("%-32s fsmid-nochange\n", (dpath ? dpath : spath));
807 logstd("%-32s nochange\n", (dpath ? dpath : spath));
815 stat1->st_size == st2.st_size &&
816 (ValidateOpt == 2 || stat1->st_mtime == st2.st_mtime) &&
817 OwnerMatch(stat1, &st2)
819 && (UseMD5Opt == 0 || !S_ISREG(stat1->st_mode) ||
820 (mres = md5_check(spath, dpath)) == 0)
822 #ifdef _ST_FSMID_PRESENT_
823 && (UseFSMIDOpt == 0 ||
824 (fres = fsmid_check(stat1->st_fsmid, dpath)) == 0)
826 && (ValidateOpt == 0 || !S_ISREG(stat1->st_mode) ||
827 validate_check(spath, dpath) == 0)
830 * The files are identical, but if we are running as
831 * root we might need to adjust ownership/group/flags.
834 int changedflags = 0;
837 hltsetdino(hln, st2.st_ino);
839 if (!OwnerMatch(stat1, &st2)) {
840 hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid);
843 #ifdef _ST_FLAGS_PRESENT_
844 if (!FlagsMatch(stat1, &st2)) {
845 hc_chflags(&DstHost, dpath, stat1->st_flags);
849 if (VerboseOpt >= 3) {
852 logstd("%-32s md5-nochange",
853 (dpath ? dpath : spath));
857 logstd("%-32s fsmid-nochange",
858 (dpath ? dpath : spath));
859 } else if (ValidateOpt) {
860 logstd("%-32s nochange (contents validated)",
861 (dpath ? dpath : spath));
863 logstd("%-32s nochange", (dpath ? dpath : spath));
866 logstd(" (uid/gid differ)");
868 logstd(" (flags differ)");
871 CountSourceBytes += size;
878 if (st2Valid && !S_ISDIR(stat1->st_mode) && S_ISDIR(st2.st_mode)) {
880 logerr("%-32s SAFETY - refusing to copy file over directory\n",
881 (dpath ? dpath : spath)
885 goto done; /* continue with the cpdup anyway */
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), "");
893 RemoveRecur(dpath, ddevNo, &st2);
898 * The various comparisons failed, copy it.
900 if (S_ISDIR(stat1->st_mode)) {
904 logerr("%-32s/ fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
907 if (!st2Valid || S_ISDIR(st2.st_mode) == 0) {
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));
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));
925 if (!OwnerMatch(stat1, &st2) &&
926 hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid) != 0
928 logerr("%s: chown of newly made dir failed: %s\n",
929 (dpath ? dpath : spath), strerror(errno));
931 /* Note that we should not set skipdir = 1 here. */
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 ).
942 if ((st2.st_mode & 0700) != 0700) {
943 hc_chmod(&DstHost, dpath, st2.st_mode | 0700);
947 logstd("%s\n", dpath ? dpath : spath);
952 * When copying a directory, stop if the source crosses a mount
955 if (sdevNo != (dev_t)-1 && stat1->st_dev != sdevNo)
958 sdevNo = stat1->st_dev;
961 * When copying a directory, stop if the destination crosses
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.
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.
974 if (ddevNo != (dev_t)-1 && st2.st_dev != ddevNo)
981 List *list = malloc(sizeof(List));
985 logstd("Scanning %s ...\n", spath);
987 if (ScanDir(list, &SrcHost, spath, &CountSourceReadBytes, 0) == 0) {
989 while ((node = IterateList(list, node, 0)) != NULL) {
993 nspath = mprintf("%s/%s", spath, node->no_Name);
995 ndpath = mprintf("%s/%s", dpath, node->no_Name);
997 info->spath = nspath;
998 info->dpath = ndpath;
999 info->sdevNo = sdevNo;
1000 info->ddevNo = ddevNo;
1002 r += DoCopy(info, node->no_Stat, depth);
1004 r += DoCopy(info, node->no_Stat, depth + 1);
1013 * Remove files/directories from destination that do not appear
1016 if (dpath && ScanDir(list, &DstHost, dpath,
1017 &CountTargetReadBytes, 3) == 0) {
1019 while ((node = IterateList(list, node, 3)) != NULL) {
1021 * If object does not exist in source or .cpignore
1022 * then recursively remove it.
1026 ndpath = mprintf("%s/%s", dpath, node->no_Name);
1027 RemoveRecur(ndpath, ddevNo, node->no_Stat);
1036 if (dpath && st2Valid) {
1037 struct timeval tv[2];
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);
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);
1054 } else if (dpath == NULL) {
1056 * If dpath is NULL, we are just updating the MD5
1059 if (UseMD5Opt && S_ISREG(stat1->st_mode)) {
1060 mres = md5_check(spath, NULL);
1062 if (VerboseOpt > 1) {
1064 logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1066 logstd("%-32s md5-ok\n", (dpath) ? dpath : spath);
1067 } else if (!QuietOpt && mres < 0) {
1068 logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1072 } else if (S_ISREG(stat1->st_mode)) {
1079 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1081 path = mprintf("%s", dpath);
1084 * Handle check failure message.
1088 logerr("%-32s md5-CHECK-FAILED\n", (dpath) ? dpath : spath);
1092 logerr("%-32s fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
1095 * Not quite ready to do the copy yet. If UseHLPath is defined,
1096 * see if we can hardlink instead.
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
1103 if (UseHLPath && (hpath = checkHLPath(stat1, spath, dpath)) != NULL) {
1105 xremove(&DstHost, dpath);
1106 if (hc_link(&DstHost, hpath, dpath) == 0) {
1109 logstd("%-32s hardlinked(-H)\n",
1110 (dpath ? dpath : spath));
1116 * Shucks, we may have hit a filesystem hard linking limit,
1117 * we have to copy instead.
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) {
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.
1128 #ifdef _ST_FLAGS_PRESENT_
1129 hc_chflags(&DstHost, path, 0);
1131 hc_remove(&DstHost, path);
1132 fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600);
1136 char *iobuf1 = malloc(GETIOSIZE);
1140 * Matt: What about holes?
1143 while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
1145 if (hc_write(&DstHost, fd2, iobuf1, n) != n)
1149 hc_close(&DstHost, fd2);
1151 struct timeval tv[2];
1153 bzero(tv, sizeof(tv));
1154 tv[0].tv_sec = stat1->st_mtime;
1155 tv[1].tv_sec = stat1->st_mtime;
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);
1164 hc_utimes(&DstHost, path, tv);
1166 if (st2Valid && xrename(path, dpath, st2_flags) != 0) {
1167 logerr("%-32s rename-after-copy failed: %s\n",
1168 (dpath ? dpath : spath), strerror(errno)
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);
1179 #ifdef _ST_FLAGS_PRESENT_
1180 if ((stat1->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE)) == 0)
1181 hc_utimes(&DstHost, dpath, tv);
1183 CountSourceReadBytes += size;
1184 CountWriteBytes += size;
1185 CountSourceBytes += size;
1189 logerr("%-32s %s failed: %s\n",
1190 (dpath ? dpath : spath), op, strerror(errno)
1192 hc_remove(&DstHost, path);
1197 logerr("%-32s create (uid %d, euid %d) failed: %s\n",
1198 (dpath ? dpath : spath), getuid(), geteuid(),
1203 hc_close(&SrcHost, fd1);
1205 logerr("%-32s copy: open failed: %s\n",
1206 (dpath ? dpath : spath),
1215 if (!r && hc_stat(&DstHost, dpath, &st2) == 0) {
1216 hltsetdino(hln, st2.st_ino);
1222 } else if (S_ISLNK(stat1->st_mode)) {
1223 char *link1 = malloc(GETLINKSIZE);
1224 char *link2 = malloc(GETLINKSIZE);
1229 n1 = hc_readlink(&SrcHost, spath, link1, GETLINKSIZE - 1);
1231 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1232 n2 = hc_readlink(&DstHost, dpath, link2, GETLINKSIZE - 1);
1234 path = mprintf("%s", dpath);
1238 if (ForceOpt || n1 != n2 || bcmp(link1, link2, n1) != 0) {
1239 hc_umask(&DstHost, ~stat1->st_mode);
1240 xremove(&DstHost, path);
1242 if (hc_symlink(&DstHost, link1, path) < 0) {
1243 logerr("%-32s symlink (%s->%s) failed: %s\n",
1244 (dpath ? dpath : spath), link1, path,
1249 if (DstRootPrivs || ChgrpAllowed(stat1->st_gid))
1250 hc_lchown(&DstHost, path, stat1->st_uid, stat1->st_gid);
1252 * there is no lchmod() or lchflags(), we
1253 * cannot chmod or chflags a softlink.
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));
1262 hc_umask(&DstHost, 000);
1263 CountWriteBytes += n1;
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)");
1274 if (VerboseOpt >= 3)
1277 CountSourceBytes += n1;
1278 CountSourceReadBytes += n1;
1280 CountTargetReadBytes += n2;
1284 logerr("%-32s softlink-failed\n", (dpath ? dpath : spath));
1289 } else if ((S_ISCHR(stat1->st_mode) || S_ISBLK(stat1->st_mode)) && DeviceOpt) {
1294 stat1->st_mode != st2.st_mode ||
1295 stat1->st_rdev != st2.st_rdev ||
1296 !OwnerMatch(stat1, &st2)
1299 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1300 xremove(&DstHost, path);
1302 path = mprintf("%s", dpath);
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);
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),
1315 } else if (VerboseOpt) {
1316 logstd("%-32s dev-ok\n", (dpath ? dpath : spath));
1321 logerr("%-32s dev failed: %s\n",
1322 (dpath ? dpath : spath), strerror(errno)
1326 if (VerboseOpt >= 3)
1327 logstd("%-32s nochange\n", (dpath ? dpath : spath));
1335 if (hln->dino == (ino_t)-1) {
1337 /*hln = NULL; unneeded */
1346 ScanDir(List *list, struct HostConf *host, const char *path,
1347 int64_t *CountReadBytes, int n)
1350 struct HCDirEntry *den;
1351 struct stat *statptr;
1355 * scan .cpignore file for files/directories to ignore
1356 * (only in the source directory, i.e. if n == 0).
1362 char *buf = malloc(GETBUFSIZE);
1366 if (UseCpFile[0] == '/') {
1367 fpath = mprintf("%s", UseCpFile);
1369 fpath = mprintf("%s/%s", path, UseCpFile);
1371 AddList(list, strrchr(fpath, '/') + 1, 1, NULL);
1372 if ((fd = hc_open(host, fpath, O_RDONLY, 0)) >= 0) {
1374 while ((nread = hc_read(host, fd, buf + bufused,
1375 GETBUFSIZE - bufused - 1)) > 0) {
1376 *CountReadBytes += nread;
1379 for (next = buf; (nl = strchr(next, '\n')); next = nl+1) {
1381 AddList(list, next, 1, NULL);
1383 bufused = strlen(next);
1385 bcopy(next, buf, bufused);
1388 /* last line has no trailing newline */
1390 AddList(list, buf, 1, NULL);
1399 * Automatically exclude MD5CacheFile that we create on the
1400 * source from the copy to the destination.
1402 * Automatically exclude a FSMIDCacheFile on the source that
1403 * would otherwise overwrite the one we maintain on the target.
1406 AddList(list, MD5CacheFile, 1, NULL);
1408 AddList(list, FSMIDCacheFile, 1, NULL);
1411 if ((dir = hc_opendir(host, path)) == NULL)
1413 while ((den = hc_readdir(host, dir, &statptr)) != NULL) {
1417 if (strcmp(den->d_name, ".") != 0 && strcmp(den->d_name, "..") != 0)
1418 AddList(list, den->d_name, n, statptr);
1420 hc_closedir(host, dir);
1430 RemoveRecur(const char *dpath, dev_t devNo, struct stat *dstat)
1434 if (dstat == NULL) {
1435 if (hc_lstat(&DstHost, dpath, &st) == 0)
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)) {
1445 if ((dir = hc_opendir(&DstHost, dpath)) != NULL) {
1446 List *list = malloc(sizeof(List));
1448 struct HCDirEntry *den;
1451 while ((den = hc_readdir(&DstHost, dir, &dstat)) != NULL) {
1452 if (strcmp(den->d_name, ".") == 0)
1454 if (strcmp(den->d_name, "..") == 0)
1456 AddList(list, den->d_name, 3, dstat);
1458 hc_closedir(&DstHost, dir);
1459 while ((node = IterateList(list, node, 3)) != NULL) {
1462 ndpath = mprintf("%s/%s", dpath, node->no_Name);
1463 RemoveRecur(ndpath, devNo, node->no_Stat);
1469 if (AskConfirmation && NoRemoveOpt == 0) {
1471 if (hc_rmdir(&DstHost, dpath) < 0) {
1472 logerr("%-32s rmdir failed: %s\n",
1473 dpath, strerror(errno)
1476 CountRemovedItems++;
1481 logstd("%-32s not-removed\n", dpath);
1482 } else if (hc_rmdir(&DstHost, dpath) == 0) {
1484 logstd("%-32s rmdir-ok\n", dpath);
1485 CountRemovedItems++;
1487 logerr("%-32s rmdir failed: %s\n",
1488 dpath, strerror(errno)
1493 if (AskConfirmation && NoRemoveOpt == 0) {
1495 if (xremove(&DstHost, dpath) < 0) {
1496 logerr("%-32s remove failed: %s\n",
1497 dpath, strerror(errno)
1500 CountRemovedItems++;
1505 logstd("%-32s not-removed\n", dpath);
1506 } else if (xremove(&DstHost, dpath) == 0) {
1508 logstd("%-32s remove-ok\n", dpath);
1509 CountRemovedItems++;
1511 logerr("%-32s remove failed: %s\n",
1512 dpath, strerror(errno)
1522 InitList(List *list)
1524 bzero(list, sizeof(List));
1525 list->li_Node.no_Next = &list->li_Node;
1529 ResetList(List *list)
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);
1543 IterateList(List *list, Node *node, int n)
1546 node = list->li_Node.no_Next;
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);
1555 AddList(List *list, const char *name, int n, struct stat *st)
1561 * Scan against wildcards. Only a node value of 1 can be a wildcard
1562 * ( usually scanned from .cpignore )
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)
1570 return(node->no_Value);
1575 * Look for exact match
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);
1584 node = malloc(sizeof(Node) + strlen(name) + 1);
1586 fatal("out of memory");
1588 node->no_Next = list->li_Node.no_Next;
1589 list->li_Node.no_Next = node;
1591 node->no_HNext = list->li_Hash[hv];
1592 list->li_Hash[hv] = node;
1594 strcpy(node->no_Name, name);
1602 shash(const char *s)
1609 if (*s == '*' || *s == '?' ||
1610 *s == '{' || *s == '}' ||
1611 *s == '[' || *s == ']' ||
1616 hv = (hv << 5) ^ *s ^ (hv >> 23);
1619 return(((hv >> 16) ^ hv) & HMASK);
1623 YesNo(const char *path)
1627 fprintf(stderr, "remove %s (Yes/No) [No]? ", path);
1630 first = ch = getchar();
1631 while (ch != '\n' && ch != EOF)
1633 return ((first == 'y' || first == 'Y'));
1637 * xrename() - rename with override
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.
1645 xrename(const char *src, const char *dst, u_long flags)
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);
1660 xlink(const char *src, const char *dst, u_long flags)
1663 #ifdef _ST_FLAGS_PRESENT_
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);
1672 hc_chflags(&DstHost, src, flags);
1682 xremove(struct HostConf *host, const char *path)
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);