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