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;
152 int EnableDirectoryRetries;
157 const char *ssh_argv[16];
161 const char *UseCpFile;
162 const char *UseHLPath;
163 const char *MD5CacheFile;
164 const char *FSMIDCacheFile;
166 int64_t CountSourceBytes;
167 int64_t CountSourceItems;
168 int64_t CountCopiedItems;
169 int64_t CountSourceReadBytes;
170 int64_t CountTargetReadBytes;
171 int64_t CountWriteBytes;
172 int64_t CountRemovedItems;
173 int64_t CountLinkedItems;
175 struct HostConf SrcHost;
176 struct HostConf DstHost;
179 main(int ac, char **av)
186 struct timeval start;
187 struct copy_info info;
189 signal(SIGPIPE, SIG_IGN);
191 gettimeofday(&start, NULL);
193 while ((opt = getopt(ac, av, ":CdnF:fH:Ii:j:K:klM:mopqRSs:uVvX:x")) != -1) {
195 /* TODO: sort the branches */
222 UseCpFile = ".cpignore";
232 fatal("too many -F options");
233 ssh_argv[ssh_argc++] = optarg;
245 AskConfirmation = getbool(optarg);
248 DeviceOpt = getbool(optarg);
251 SafetyOpt = getbool(optarg);
258 FSMIDCacheFile = ".FSMID.CHECK";
262 FSMIDCacheFile = optarg;
266 MD5CacheFile = optarg;
270 MD5CacheFile = ".MD5.CHECKSUMS";
273 setvbuf(stdout, NULL, _IOLBF, 0);
276 fatal("missing argument for option: -%c\n", optopt);
280 fatal("illegal option: -%c\n", optopt);
296 fatal("too many arguments");
299 * If we are told to go into slave mode, run the HC protocol
302 DstRootPrivs = (geteuid() == 0);
308 * Extract the source and/or/neither target [user@]host and
309 * make any required connections.
311 if (src && (ptr = SplitRemote(src)) != NULL) {
315 fatal("The MD5 options are not currently supported for remote sources");
316 if (hc_connect(&SrcHost, ReadOnlyOpt) < 0)
318 } else if (ReadOnlyOpt)
319 fatal("The -R option is only supported for remote sources");
321 if (dst && (ptr = SplitRemote(dst)) != NULL) {
325 fatal("The FSMID options are not currently supported for remote targets");
326 if (hc_connect(&DstHost, 0) < 0)
331 * dst may be NULL only if -m option is specified,
332 * which forces an update of the MD5 checksums
334 if (dst == NULL && UseMD5Opt == 0) {
340 DstRootPrivs = (hc_geteuid(&DstHost) == 0);
342 GroupCount = hc_getgroups(&DstHost, &GroupList);
346 fprintf(stderr, "DstRootPrivs == %s\n", DstRootPrivs ? "true" : "false");
347 fprintf(stderr, "GroupCount == %d\n", GroupCount);
348 for (i = 0; i < GroupCount; i++)
349 fprintf(stderr, "Group[%d] == %d\n", i, GroupList[i]);
352 bzero(&info, sizeof(info));
354 DstBaseLen = strlen(dst);
357 info.sdevNo = (dev_t)-1;
358 info.ddevNo = (dev_t)-1;
359 i = DoCopy(&info, NULL, -1);
363 info.sdevNo = (dev_t)-1;
364 info.ddevNo = (dev_t)-1;
365 i = DoCopy(&info, NULL, -1);
372 if (SummaryOpt && i == 0) {
376 gettimeofday(&end, NULL);
378 /* don't count stat's in our byte statistics */
379 CountSourceBytes += sizeof(struct stat) * CountSourceItems;
380 CountSourceReadBytes += sizeof(struct stat) * CountSourceItems;
381 CountWriteBytes += sizeof(struct stat) * CountCopiedItems;
382 CountWriteBytes += sizeof(struct stat) * CountRemovedItems;
385 duration = (end.tv_sec - start.tv_sec);
386 duration += (double)(end.tv_usec - start.tv_usec) / 1000000.0;
389 logstd("cpdup completed successfully\n");
390 logstd("%lld bytes source, %lld src bytes read, %lld tgt bytes read\n"
391 "%lld bytes written (%.1fX speedup)\n",
392 (long long)CountSourceBytes,
393 (long long)CountSourceReadBytes,
394 (long long)CountTargetReadBytes,
395 (long long)CountWriteBytes,
396 ((double)CountSourceBytes * 2.0) / ((double)(CountSourceReadBytes + CountTargetReadBytes + CountWriteBytes)));
397 logstd("%lld source items, %lld items copied, %lld items linked, "
398 "%lld things deleted\n",
399 (long long)CountSourceItems,
400 (long long)CountCopiedItems,
401 (long long)CountLinkedItems,
402 (long long)CountRemovedItems);
403 logstd("%.1f seconds %5d Kbytes/sec synced %5d Kbytes/sec scanned\n",
405 (int)((CountSourceReadBytes + CountTargetReadBytes + CountWriteBytes) / duration / 1024.0),
406 (int)(CountSourceBytes / duration / 1024.0));
408 exit((i == 0) ? 0 : 1);
412 getbool(const char *str)
414 if (strcmp(str, "0") == 0)
416 if (strcmp(str, "1") == 0)
418 fatal("option requires boolean argument (0 or 1): -%c\n", optopt);
424 * Check if path specifies a remote path, using the same syntax as scp(1),
425 * i.e. a path is considered remote if the first colon is not preceded by
426 * a slash, so e.g. "./foo:bar" is considered local.
427 * If a remote path is detected, the colon is replaced with a null byte,
428 * and the return value is a pointer to the next character.
429 * Otherwise NULL is returned.
432 SplitRemote(char *path)
436 if (path[(cindex = strcspn(path, ":/"))] == ':') {
438 return (path + cindex);
444 * Check if group g is in our GroupList.
446 * Typically the number of groups a user belongs to isn't large
447 * enough to warrant more effort than a simple linear search.
448 * However, we perform an optimization by moving a group to the
449 * top of the list when we have a hit. This assumes that there
450 * isn't much variance in the gids of files that a non-root user
451 * copies. So most of the time the search will terminate on the
452 * first element of the list.
455 ChgrpAllowed(gid_t g)
459 for (i = 0; i < GroupCount; i++)
460 if (GroupList[i] == g) {
462 /* Optimize: Move g to the front of the list. */
464 GroupList[i] = GroupList[i - 1];
473 * The following two functions return true if the ownership (UID + GID)
474 * or the flags of two files match, respectively.
476 * Only perform weak checking if we don't have sufficient privileges on
477 * the target machine, so we don't waste transfers with things that are
478 * bound to fail anyway.
481 OwnerMatch(struct stat *st1, struct stat *st2)
484 /* Both UID and GID must match. */
485 return (st1->st_uid == st2->st_uid && st1->st_gid == st2->st_gid);
487 /* Ignore UID, and also ignore GID if we can't chgrp to that group. */
488 return (st1->st_gid == st2->st_gid || !ChgrpAllowed(st1->st_gid));
491 #ifdef _ST_FLAGS_PRESENT_
493 FlagsMatch(struct stat *st1, struct stat *st2)
496 return (st1->st_flags == st2->st_flags);
498 /* Only consider the user-settable flags. */
499 return (((st1->st_flags ^ st2->st_flags) & UF_SETTABLE) == 0);
504 static struct hlink *
505 hltlookup(struct stat *stp)
510 n = stp->st_ino & HLMASK;
512 for (hl = hltable[n]; hl; hl = hl->next) {
513 if (hl->ino == stp->st_ino) {
522 static struct hlink *
523 hltadd(struct stat *stp, const char *path)
526 int plen = strlen(path);
529 new = malloc(offsetof(struct hlink, name[plen + 1]));
531 fatal("out of memory");
534 /* initialize and link the new element into the table */
535 new->ino = stp->st_ino;
536 new->dino = (ino_t)-1;
538 bcopy(path, new->name, plen + 1);
541 n = stp->st_ino & HLMASK;
542 new->next = hltable[n];
544 hltable[n]->prev = new;
551 hltsetdino(struct hlink *hl, ino_t inum)
557 hltdelete(struct hlink *hl)
559 assert(hl->refs == 1);
563 hl->next->prev = hl->prev;
564 hl->prev->next = hl->next;
567 hl->next->prev = NULL;
569 hltable[hl->ino & HLMASK] = hl->next;
576 hltrels(struct hlink *hl)
578 assert(hl->refs == 1);
583 * If UseHLPath is defined check to see if the file in question is
584 * the same as the source file, and if it is return a pointer to the
585 * -H path based file for hardlinking. Else return NULL.
588 checkHLPath(struct stat *st1, const char *spath, const char *dpath)
594 asprintf(&hpath, "%s%s", UseHLPath, dpath + DstBaseLen);
597 * stat info matches ?
599 if (hc_stat(&DstHost, hpath, &sthl) < 0 ||
600 st1->st_size != sthl.st_size ||
601 st1->st_mtime != sthl.st_mtime ||
602 !OwnerMatch(st1, &sthl) ||
603 !FlagsMatch(st1, &sthl)
610 * If ForceOpt or ValidateOpt is set we have to compare the files
612 if (ForceOpt || ValidateOpt) {
613 error = validate_check(spath, hpath);
623 * Return 0 if the contents of the file <spath> matches the contents of
627 validate_check(const char *spath, const char *dpath)
633 fd1 = hc_open(&SrcHost, spath, O_RDONLY, 0);
634 fd2 = hc_open(&DstHost, dpath, O_RDONLY, 0);
637 if (fd1 >= 0 && fd2 >= 0) {
640 char *iobuf1 = malloc(GETIOSIZE);
641 char *iobuf2 = malloc(GETIOSIZE);
643 while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
644 CountSourceReadBytes += n;
645 x = hc_read(&DstHost, fd2, iobuf2, GETIOSIZE);
647 CountTargetReadBytes += x;
650 if (bcmp(iobuf1, iobuf2, n) != 0)
659 hc_close(&SrcHost, fd1);
661 hc_close(&DstHost, fd2);
666 DoCopy(copy_info_t info, struct stat *stat1, int depth)
668 const char *spath = info->spath;
669 const char *dpath = info->dpath;
670 dev_t sdevNo = info->sdevNo;
671 dev_t ddevNo = info->ddevNo;
674 unsigned long st2_flags;
675 int r, mres, fres, st2Valid;
679 r = mres = fres = st2Valid = 0;
685 if (hc_lstat(&SrcHost, spath, &st1) != 0) {
692 /* skip snapshot files because they're sparse and _huge_ */
693 if (stat1->st_flags & SF_SNAPSHOT)
696 st2.st_mode = 0; /* in case lstat fails */
697 st2.st_flags = 0; /* in case lstat fails */
698 if (dpath && hc_lstat(&DstHost, dpath, &st2) == 0) {
700 #ifdef _ST_FLAGS_PRESENT_
701 st2_flags = st2.st_flags;
705 if (S_ISREG(stat1->st_mode))
706 size = stat1->st_size;
712 if (S_ISREG(stat1->st_mode) && stat1->st_nlink > 1 && dpath) {
713 if ((hln = hltlookup(stat1)) != NULL) {
717 if (st2.st_ino == hln->dino) {
719 * hard link is already correct, nothing to do
722 logstd("%-32s nochange\n", (dpath) ? dpath : spath);
723 if (hln->nlinked == stat1->st_nlink) {
732 * hard link is not correct, attempt to unlink it
734 if (xremove(&DstHost, dpath) < 0) {
735 logerr("%-32s hardlink: unable to unlink: %s\n",
736 ((dpath) ? dpath : spath), strerror(errno));
745 if (xlink(hln->name, dpath, stat1->st_flags) < 0) {
746 int tryrelink = (errno == EMLINK);
747 logerr("%-32s hardlink: unable to link to %s: %s\n",
748 (dpath ? dpath : spath), hln->name, strerror(errno)
753 logerr("%-20s hardlink: will attempt to copy normally\n",
754 (dpath ? dpath : spath));
759 if (hln->nlinked == stat1->st_nlink) {
765 logstd("%-32s hardlink: %s\n",
766 (dpath ? dpath : spath),
767 (st2Valid ? "relinked" : "linked")
778 * first instance of hardlink must be copied normally
781 hln = hltadd(stat1, dpath);
786 * Do we need to copy the file/dir/link/whatever? Early termination
787 * if we do not. Always redo links. Directories are always traversed
788 * except when the FSMID options are used.
790 * NOTE: st2Valid is true only if dpath != NULL *and* dpath stats good.
795 && stat1->st_mode == st2.st_mode
796 && FlagsMatch(stat1, &st2)
798 if (S_ISLNK(stat1->st_mode) || S_ISDIR(stat1->st_mode)) {
800 * If FSMID tracking is turned on we can avoid recursing through
801 * an entire directory subtree if the FSMID matches.
803 #ifdef _ST_FSMID_PRESENT_
805 (UseFSMIDOpt && (fres = fsmid_check(stat1->st_fsmid, dpath)) == 0)
807 if (VerboseOpt >= 3) {
808 if (UseFSMIDOpt) /* always true!?! */
809 logstd("%-32s fsmid-nochange\n", (dpath ? dpath : spath));
811 logstd("%-32s nochange\n", (dpath ? dpath : spath));
819 stat1->st_size == st2.st_size &&
820 (ValidateOpt == 2 || stat1->st_mtime == st2.st_mtime) &&
821 OwnerMatch(stat1, &st2)
823 && (UseMD5Opt == 0 || !S_ISREG(stat1->st_mode) ||
824 (mres = md5_check(spath, dpath)) == 0)
826 #ifdef _ST_FSMID_PRESENT_
827 && (UseFSMIDOpt == 0 ||
828 (fres = fsmid_check(stat1->st_fsmid, dpath)) == 0)
830 && (ValidateOpt == 0 || !S_ISREG(stat1->st_mode) ||
831 validate_check(spath, dpath) == 0)
834 * The files are identical, but if we are running as
835 * root we might need to adjust ownership/group/flags.
838 int changedflags = 0;
841 hltsetdino(hln, st2.st_ino);
843 if (!OwnerMatch(stat1, &st2)) {
844 hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid);
847 #ifdef _ST_FLAGS_PRESENT_
848 if (!FlagsMatch(stat1, &st2)) {
849 hc_chflags(&DstHost, dpath, stat1->st_flags);
853 if (VerboseOpt >= 3) {
856 logstd("%-32s md5-nochange",
857 (dpath ? dpath : spath));
861 logstd("%-32s fsmid-nochange",
862 (dpath ? dpath : spath));
863 } else if (ValidateOpt) {
864 logstd("%-32s nochange (contents validated)",
865 (dpath ? dpath : spath));
867 logstd("%-32s nochange", (dpath ? dpath : spath));
870 logstd(" (uid/gid differ)");
872 logstd(" (flags differ)");
875 CountSourceBytes += size;
882 if (st2Valid && !S_ISDIR(stat1->st_mode) && S_ISDIR(st2.st_mode)) {
884 logerr("%-32s SAFETY - refusing to copy file over directory\n",
885 (dpath ? dpath : spath)
889 goto done; /* continue with the cpdup anyway */
891 if (QuietOpt == 0 || AskConfirmation) {
892 logstd("%-32s WARNING: non-directory source will blow away\n"
893 "%-32s preexisting dest directory, continuing anyway!\n",
894 ((dpath) ? dpath : spath), "");
897 RemoveRecur(dpath, ddevNo, &st2);
902 * The various comparisons failed, copy it.
904 if (S_ISDIR(stat1->st_mode)) {
908 logerr("%-32s/ fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
911 if (!st2Valid || S_ISDIR(st2.st_mode) == 0) {
913 xremove(&DstHost, dpath);
914 if (hc_mkdir(&DstHost, dpath, stat1->st_mode | 0700) != 0) {
915 logerr("%s: mkdir failed: %s\n",
916 (dpath ? dpath : spath), strerror(errno));
920 if (hc_lstat(&DstHost, dpath, &st2) != 0) {
921 if (NotForRealOpt == 0)
922 logerr("%s: lstat of newly made dir failed: %s\n",
923 (dpath ? dpath : spath), strerror(errno));
930 if (!OwnerMatch(stat1, &st2) &&
931 hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid) != 0
933 logerr("%s: chown of newly made dir failed: %s\n",
934 (dpath ? dpath : spath), strerror(errno));
936 /* Note that we should not set skipdir = 1 here. */
942 * Directory must be scanable by root for cpdup to
943 * work. We'll fix it later if the directory isn't
944 * supposed to be readable ( which is why we fixup
945 * st2.st_mode to match what we did ).
947 if ((st2.st_mode & 0700) != 0700) {
948 hc_chmod(&DstHost, dpath, st2.st_mode | 0700);
952 logstd("%s\n", dpath ? dpath : spath);
957 * When copying a directory, stop if the source crosses a mount
960 if (sdevNo != (dev_t)-1 && stat1->st_dev != sdevNo)
963 sdevNo = stat1->st_dev;
966 * When copying a directory, stop if the destination crosses
969 * The target directory will have been created and stat'd
970 * for st2 if it did not previously exist. st2Valid is left
971 * as a flag. If the stat failed st2 will still only have its
972 * default initialization.
974 * So we simply assume here that the directory is within the
975 * current target mount if we had to create it (aka st2Valid is 0)
976 * and we leave ddevNo alone.
979 if (ddevNo != (dev_t)-1 && st2.st_dev != ddevNo)
986 List *list = malloc(sizeof(List));
990 logstd("Scanning %s ...\n", spath);
992 if (ScanDir(list, &SrcHost, spath, &CountSourceReadBytes, 0) == 0) {
994 while ((node = IterateList(list, node, 0)) != NULL) {
998 nspath = mprintf("%s/%s", spath, node->no_Name);
1000 ndpath = mprintf("%s/%s", dpath, node->no_Name);
1002 info->spath = nspath;
1003 info->dpath = ndpath;
1004 info->sdevNo = sdevNo;
1005 info->ddevNo = ddevNo;
1007 r += DoCopy(info, node->no_Stat, depth);
1009 r += DoCopy(info, node->no_Stat, depth + 1);
1018 * Remove files/directories from destination that do not appear
1021 if (dpath && ScanDir(list, &DstHost, dpath,
1022 &CountTargetReadBytes, 3) == 0) {
1024 while ((node = IterateList(list, node, 3)) != NULL) {
1026 * If object does not exist in source or .cpignore
1027 * then recursively remove it.
1031 ndpath = mprintf("%s/%s", dpath, node->no_Name);
1032 RemoveRecur(ndpath, ddevNo, node->no_Stat);
1041 if (dpath && st2Valid) {
1042 struct timeval tv[2];
1044 if (ForceOpt || !OwnerMatch(stat1, &st2))
1045 hc_chown(&DstHost, dpath, stat1->st_uid, stat1->st_gid);
1046 if (stat1->st_mode != st2.st_mode)
1047 hc_chmod(&DstHost, dpath, stat1->st_mode);
1048 #ifdef _ST_FLAGS_PRESENT_
1049 if (!FlagsMatch(stat1, &st2))
1050 hc_chflags(&DstHost, dpath, stat1->st_flags);
1052 if (ForceOpt || stat1->st_mtime != st2.st_mtime) {
1053 bzero(tv, sizeof(tv));
1054 tv[0].tv_sec = stat1->st_mtime;
1055 tv[1].tv_sec = stat1->st_mtime;
1056 hc_utimes(&DstHost, dpath, tv);
1059 } else if (dpath == NULL) {
1061 * If dpath is NULL, we are just updating the MD5
1064 if (UseMD5Opt && S_ISREG(stat1->st_mode)) {
1065 mres = md5_check(spath, NULL);
1067 if (VerboseOpt > 1) {
1069 logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1071 logstd("%-32s md5-ok\n", (dpath) ? dpath : spath);
1072 } else if (!QuietOpt && mres < 0) {
1073 logstd("%-32s md5-update\n", (dpath) ? dpath : spath);
1077 } else if (S_ISREG(stat1->st_mode)) {
1084 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1086 path = mprintf("%s", dpath);
1089 * Handle check failure message.
1093 logerr("%-32s md5-CHECK-FAILED\n", (dpath) ? dpath : spath);
1097 logerr("%-32s fsmid-CHECK-FAILED\n", (dpath) ? dpath : spath);
1100 * Not quite ready to do the copy yet. If UseHLPath is defined,
1101 * see if we can hardlink instead.
1103 * If we can hardlink, and the target exists, we have to remove it
1104 * first or the hardlink will fail. This can occur in a number of
1105 * situations but most typically when the '-f -H' combination is
1108 if (UseHLPath && (hpath = checkHLPath(stat1, spath, dpath)) != NULL) {
1110 xremove(&DstHost, dpath);
1111 if (hc_link(&DstHost, hpath, dpath) == 0) {
1114 logstd("%-32s hardlinked(-H)\n",
1115 (dpath ? dpath : spath));
1121 * Shucks, we may have hit a filesystem hard linking limit,
1122 * we have to copy instead.
1127 if ((fd1 = hc_open(&SrcHost, spath, O_RDONLY, 0)) >= 0) {
1128 if ((fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL, 0600)) < 0) {
1130 * There could be a .tmp file from a previously interrupted
1131 * run, delete and retry. Fail if we still can't get at it.
1133 #ifdef _ST_FLAGS_PRESENT_
1134 hc_chflags(&DstHost, path, 0);
1136 hc_remove(&DstHost, path);
1137 fd2 = hc_open(&DstHost, path, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600);
1141 char *iobuf1 = malloc(GETIOSIZE);
1145 * Matt: What about holes?
1148 while ((n = hc_read(&SrcHost, fd1, iobuf1, GETIOSIZE)) > 0) {
1150 if (hc_write(&DstHost, fd2, iobuf1, n) != n)
1154 hc_close(&DstHost, fd2);
1156 struct timeval tv[2];
1158 bzero(tv, sizeof(tv));
1159 tv[0].tv_sec = stat1->st_mtime;
1160 tv[1].tv_sec = stat1->st_mtime;
1162 if (DstRootPrivs || ChgrpAllowed(stat1->st_gid))
1163 hc_chown(&DstHost, path, stat1->st_uid, stat1->st_gid);
1164 hc_chmod(&DstHost, path, stat1->st_mode);
1165 #ifdef _ST_FLAGS_PRESENT_
1166 if (stat1->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE))
1167 hc_utimes(&DstHost, path, tv);
1169 hc_utimes(&DstHost, path, tv);
1171 if (st2Valid && xrename(path, dpath, st2_flags) != 0) {
1172 logerr("%-32s rename-after-copy failed: %s\n",
1173 (dpath ? dpath : spath), strerror(errno)
1178 logstd("%-32s copy-ok\n", (dpath ? dpath : spath));
1179 #ifdef _ST_FLAGS_PRESENT_
1180 if (DstRootPrivs ? stat1->st_flags : stat1->st_flags & UF_SETTABLE)
1181 hc_chflags(&DstHost, dpath, stat1->st_flags);
1184 #ifdef _ST_FLAGS_PRESENT_
1185 if ((stat1->st_flags & (UF_IMMUTABLE|SF_IMMUTABLE)) == 0)
1186 hc_utimes(&DstHost, dpath, tv);
1188 CountSourceReadBytes += size;
1189 CountWriteBytes += size;
1190 CountSourceBytes += size;
1194 logerr("%-32s %s failed: %s\n",
1195 (dpath ? dpath : spath), op, strerror(errno)
1197 hc_remove(&DstHost, path);
1202 logerr("%-32s create (uid %d, euid %d) failed: %s\n",
1203 (dpath ? dpath : spath), getuid(), geteuid(),
1208 hc_close(&SrcHost, fd1);
1210 logerr("%-32s copy: open failed: %s\n",
1211 (dpath ? dpath : spath),
1220 if (!r && hc_stat(&DstHost, dpath, &st2) == 0) {
1221 hltsetdino(hln, st2.st_ino);
1227 } else if (S_ISLNK(stat1->st_mode)) {
1228 char *link1 = malloc(GETLINKSIZE);
1229 char *link2 = malloc(GETLINKSIZE);
1234 n1 = hc_readlink(&SrcHost, spath, link1, GETLINKSIZE - 1);
1236 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1237 n2 = hc_readlink(&DstHost, dpath, link2, GETLINKSIZE - 1);
1239 path = mprintf("%s", dpath);
1243 if (ForceOpt || n1 != n2 || bcmp(link1, link2, n1) != 0) {
1244 hc_umask(&DstHost, ~stat1->st_mode);
1245 xremove(&DstHost, path);
1247 if (hc_symlink(&DstHost, link1, path) < 0) {
1248 logerr("%-32s symlink (%s->%s) failed: %s\n",
1249 (dpath ? dpath : spath), link1, path,
1254 if (DstRootPrivs || ChgrpAllowed(stat1->st_gid))
1255 hc_lchown(&DstHost, path, stat1->st_uid, stat1->st_gid);
1257 * there is no lchmod() or lchflags(), we
1258 * cannot chmod or chflags a softlink.
1260 if (st2Valid && xrename(path, dpath, st2_flags) != 0) {
1261 logerr("%-32s rename softlink (%s->%s) failed: %s\n",
1262 (dpath ? dpath : spath),
1263 path, dpath, strerror(errno));
1264 } else if (VerboseOpt) {
1265 logstd("%-32s softlink-ok\n", (dpath ? dpath : spath));
1267 hc_umask(&DstHost, 000);
1268 CountWriteBytes += n1;
1272 if (VerboseOpt >= 3)
1273 logstd("%-32s nochange", (dpath ? dpath : spath));
1274 if (!OwnerMatch(stat1, &st2)) {
1275 hc_lchown(&DstHost, dpath, stat1->st_uid, stat1->st_gid);
1276 if (VerboseOpt >= 3)
1277 logstd(" (uid/gid differ)");
1279 if (VerboseOpt >= 3)
1282 CountSourceBytes += n1;
1283 CountSourceReadBytes += n1;
1285 CountTargetReadBytes += n2;
1289 logerr("%-32s softlink-failed\n", (dpath ? dpath : spath));
1294 } else if ((S_ISCHR(stat1->st_mode) || S_ISBLK(stat1->st_mode)) && DeviceOpt) {
1299 stat1->st_mode != st2.st_mode ||
1300 stat1->st_rdev != st2.st_rdev ||
1301 !OwnerMatch(stat1, &st2)
1304 path = mprintf("%s.tmp%d", dpath, (int)getpid());
1305 xremove(&DstHost, path);
1307 path = mprintf("%s", dpath);
1310 if (hc_mknod(&DstHost, path, stat1->st_mode, stat1->st_rdev) == 0) {
1311 hc_chmod(&DstHost, path, stat1->st_mode);
1312 hc_chown(&DstHost, path, stat1->st_uid, stat1->st_gid);
1314 xremove(&DstHost, dpath);
1315 if (st2Valid && xrename(path, dpath, st2_flags) != 0) {
1316 logerr("%-32s dev-rename-after-create failed: %s\n",
1317 (dpath ? dpath : spath),
1320 } else if (VerboseOpt) {
1321 logstd("%-32s dev-ok\n", (dpath ? dpath : spath));
1326 logerr("%-32s dev failed: %s\n",
1327 (dpath ? dpath : spath), strerror(errno)
1331 if (VerboseOpt >= 3)
1332 logstd("%-32s nochange\n", (dpath ? dpath : spath));
1340 if (hln->dino == (ino_t)-1) {
1342 /*hln = NULL; unneeded */
1351 ScanDir(List *list, struct HostConf *host, const char *path,
1352 int64_t *CountReadBytes, int n)
1355 struct HCDirEntry *den;
1356 struct stat *statptr;
1360 * scan .cpignore file for files/directories to ignore
1361 * (only in the source directory, i.e. if n == 0).
1367 char *buf = malloc(GETBUFSIZE);
1371 if (UseCpFile[0] == '/') {
1372 fpath = mprintf("%s", UseCpFile);
1374 fpath = mprintf("%s/%s", path, UseCpFile);
1376 AddList(list, strrchr(fpath, '/') + 1, 1, NULL);
1377 if ((fd = hc_open(host, fpath, O_RDONLY, 0)) >= 0) {
1379 while ((nread = hc_read(host, fd, buf + bufused,
1380 GETBUFSIZE - bufused - 1)) > 0) {
1381 *CountReadBytes += nread;
1384 for (next = buf; (nl = strchr(next, '\n')); next = nl+1) {
1386 AddList(list, next, 1, NULL);
1388 bufused = strlen(next);
1390 bcopy(next, buf, bufused);
1393 /* last line has no trailing newline */
1395 AddList(list, buf, 1, NULL);
1404 * Automatically exclude MD5CacheFile that we create on the
1405 * source from the copy to the destination.
1407 * Automatically exclude a FSMIDCacheFile on the source that
1408 * would otherwise overwrite the one we maintain on the target.
1411 AddList(list, MD5CacheFile, 1, NULL);
1413 AddList(list, FSMIDCacheFile, 1, NULL);
1416 if ((dir = hc_opendir(host, path)) == NULL)
1418 while ((den = hc_readdir(host, dir, &statptr)) != NULL) {
1422 if (strcmp(den->d_name, ".") != 0 && strcmp(den->d_name, "..") != 0)
1423 AddList(list, den->d_name, n, statptr);
1425 hc_closedir(host, dir);
1435 RemoveRecur(const char *dpath, dev_t devNo, struct stat *dstat)
1439 if (dstat == NULL) {
1440 if (hc_lstat(&DstHost, dpath, &st) == 0)
1443 if (dstat != NULL) {
1444 if (devNo == (dev_t)-1)
1445 devNo = dstat->st_dev;
1446 if (dstat->st_dev == devNo) {
1447 if (S_ISDIR(dstat->st_mode)) {
1450 if ((dir = hc_opendir(&DstHost, dpath)) != NULL) {
1451 List *list = malloc(sizeof(List));
1453 struct HCDirEntry *den;
1456 while ((den = hc_readdir(&DstHost, dir, &dstat)) != NULL) {
1457 if (strcmp(den->d_name, ".") == 0)
1459 if (strcmp(den->d_name, "..") == 0)
1461 AddList(list, den->d_name, 3, dstat);
1463 hc_closedir(&DstHost, dir);
1464 while ((node = IterateList(list, node, 3)) != NULL) {
1467 ndpath = mprintf("%s/%s", dpath, node->no_Name);
1468 RemoveRecur(ndpath, devNo, node->no_Stat);
1474 if (AskConfirmation && NoRemoveOpt == 0) {
1476 if (hc_rmdir(&DstHost, dpath) < 0) {
1477 logerr("%-32s rmdir failed: %s\n",
1478 dpath, strerror(errno)
1481 CountRemovedItems++;
1486 logstd("%-32s not-removed\n", dpath);
1487 } else if (hc_rmdir(&DstHost, dpath) == 0) {
1489 logstd("%-32s rmdir-ok\n", dpath);
1490 CountRemovedItems++;
1492 logerr("%-32s rmdir failed: %s\n",
1493 dpath, strerror(errno)
1498 if (AskConfirmation && NoRemoveOpt == 0) {
1500 if (xremove(&DstHost, dpath) < 0) {
1501 logerr("%-32s remove failed: %s\n",
1502 dpath, strerror(errno)
1505 CountRemovedItems++;
1510 logstd("%-32s not-removed\n", dpath);
1511 } else if (xremove(&DstHost, dpath) == 0) {
1513 logstd("%-32s remove-ok\n", dpath);
1514 CountRemovedItems++;
1516 logerr("%-32s remove failed: %s\n",
1517 dpath, strerror(errno)
1527 InitList(List *list)
1529 bzero(list, sizeof(List));
1530 list->li_Node.no_Next = &list->li_Node;
1534 ResetList(List *list)
1538 while ((node = list->li_Node.no_Next) != &list->li_Node) {
1539 list->li_Node.no_Next = node->no_Next;
1540 if (node->no_Stat != NULL)
1541 free(node->no_Stat);
1548 IterateList(List *list, Node *node, int n)
1551 node = list->li_Node.no_Next;
1553 node = node->no_Next;
1554 while (node->no_Value != n && node != &list->li_Node)
1555 node = node->no_Next;
1556 return (node == &list->li_Node ? NULL : node);
1560 AddList(List *list, const char *name, int n, struct stat *st)
1566 * Scan against wildcards. Only a node value of 1 can be a wildcard
1567 * ( usually scanned from .cpignore )
1570 for (node = list->li_Hash[0]; node; node = node->no_HNext) {
1571 if (strcmp(name, node->no_Name) == 0 ||
1572 (n != 1 && node->no_Value == 1 &&
1573 fnmatch(node->no_Name, name, 0) == 0)
1575 return(node->no_Value);
1580 * Look for exact match
1584 for (node = list->li_Hash[hv]; node; node = node->no_HNext) {
1585 if (strcmp(name, node->no_Name) == 0) {
1586 return(node->no_Value);
1589 node = malloc(sizeof(Node) + strlen(name) + 1);
1591 fatal("out of memory");
1593 node->no_Next = list->li_Node.no_Next;
1594 list->li_Node.no_Next = node;
1596 node->no_HNext = list->li_Hash[hv];
1597 list->li_Hash[hv] = node;
1599 strcpy(node->no_Name, name);
1607 shash(const char *s)
1614 if (*s == '*' || *s == '?' ||
1615 *s == '{' || *s == '}' ||
1616 *s == '[' || *s == ']' ||
1621 hv = (hv << 5) ^ *s ^ (hv >> 23);
1624 return(((hv >> 16) ^ hv) & HMASK);
1628 YesNo(const char *path)
1632 fprintf(stderr, "remove %s (Yes/No) [No]? ", path);
1635 first = ch = getchar();
1636 while (ch != '\n' && ch != EOF)
1638 return ((first == 'y' || first == 'Y'));
1642 * xrename() - rename with override
1644 * If the rename fails, attempt to override st_flags on the
1645 * destination and rename again. If that fails too, try to
1646 * set the flags back the way they were and give up.
1650 xrename(const char *src, const char *dst, u_long flags)
1654 if ((r = hc_rename(&DstHost, src, dst)) < 0) {
1655 #ifdef _ST_FLAGS_PRESENT_
1656 hc_chflags(&DstHost, dst, 0);
1657 if ((r = hc_rename(&DstHost, src, dst)) < 0)
1658 hc_chflags(&DstHost, dst, flags);
1665 xlink(const char *src, const char *dst, u_long flags)
1668 #ifdef _ST_FLAGS_PRESENT_
1672 if ((r = hc_link(&DstHost, src, dst)) < 0) {
1673 #ifdef _ST_FLAGS_PRESENT_
1674 hc_chflags(&DstHost, src, 0);
1675 r = hc_link(&DstHost, src, dst);
1677 hc_chflags(&DstHost, src, flags);
1687 xremove(struct HostConf *host, const char *path)
1691 res = hc_remove(host, path);
1692 #ifdef _ST_FLAGS_PRESENT_
1693 if (res == -EPERM) {
1694 hc_chflags(host, path, 0);
1695 res = hc_remove(host, path);