Debian Codegraph @

generator.c

raw symbols SCIP
1 /*
2 * Routines that are exclusive to the generator process.
3 *
4 * Copyright (C) 1996-2000 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2002 Martin Pool <[email protected]>
7 * Copyright (C) 2003-2023 Wayne Davison
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, visit the http://fsf.org website.
21 */
22
23 #include "rsync.h"
24 #include "inums.h"
25 #include "ifuncs.h"
26
27 extern int dry_run;
28 extern int do_xfers;
29 extern int stdout_format_has_i;
30 extern int logfile_format_has_i;
31 extern int am_root;
32 extern int operator_path_resolve;
33 extern int am_server;
34 extern int am_daemon;
35 extern int inc_recurse;
36 extern int relative_paths;
37 extern int implied_dirs;
38 extern int keep_dirlinks;
39 extern int write_devices;
40 extern int preserve_acls;
41 extern int preserve_xattrs;
42 extern int preserve_links;
43 extern int preserve_devices;
44 extern int preserve_specials;
45 extern int drop_devices;
46 extern int preserve_hard_links;
47 extern int preserve_executability;
48 extern int preserve_perms;
49 extern int preserve_mtimes;
50 extern int omit_dir_times;
51 extern int omit_link_times;
52 extern int delete_mode;
53 extern int delete_before;
54 extern int delete_during;
55 extern int delete_after;
56 extern int missing_args;
57 extern int msgdone_cnt;
58 extern int ignore_errors;
59 extern int remove_source_files;
60 extern int delay_updates;
61 extern int update_only;
62 extern int human_readable;
63 extern int ignore_existing;
64 extern int ignore_non_existing;
65 extern int want_xattr_optim;
66 extern int modify_window;
67 extern int inplace;
68 extern int append_mode;
69 extern int make_backups;
70 extern int csum_length;
71 extern int xfer_sum_len;
72 extern int ignore_times;
73 extern int size_only;
74 extern OFF_T max_size;
75 extern OFF_T min_size;
76 extern int io_error;
77 extern int flist_eof;
78 extern int allowed_lull;
79 extern int sock_f_out;
80 extern int protocol_version;
81 extern int file_total;
82 extern int fuzzy_basis;
83 extern int always_checksum;
84 extern int flist_csum_len;
85 extern char *partial_dir;
86 extern int alt_dest_type;
87 extern int whole_file;
88 extern int list_only;
89 extern int read_batch;
90 extern int write_batch;
91 extern int safe_symlinks;
92 extern int32 block_size;
93 extern int unsort_ndx;
94 extern int max_delete;
95 extern int force_delete;
96 extern int one_file_system;
97 extern int skipped_deletes;
98 extern dev_t filesystem_dev;
99 extern mode_t orig_umask;
100 extern uid_t our_uid;
101 extern char *tmpdir;
102 extern char *basis_dir[MAX_BASIS_DIRS+1];
103 extern struct file_list *cur_flist, *first_flist, *dir_flist;
104 extern filter_rule_list filter_list, daemon_filter_list;
105
106 int maybe_ATTRS_REPORT = 0;
107 int maybe_ATTRS_ACCURATE_TIME = 0;
108
109 static dev_t dev_zero;
110 static int deldelay_size = 0, deldelay_cnt = 0;
111 static char *deldelay_buf = NULL;
112 static int deldelay_fd = -1;
113 static int loopchk_limit;
114 static int dir_tweaking;
115 static int symlink_timeset_failed_flags;
116 static int need_retouch_dir_times;
117 static int need_retouch_dir_perms;
118 static const char *solo_file = NULL;
119
120 /* Forward declarations. */
121 #ifdef SUPPORT_HARD_LINKS
122 static void handle_skipped_hlink(struct file_struct *file, int itemizing,
123 enum logcode code, int f_out);
124 #endif
125
126 #define EARLY_DELAY_DONE_MSG() (!delay_updates)
127 #define EARLY_DELETE_DONE_MSG() (!(delete_during == 2 || delete_after))
128
129 static int start_delete_delay_temp(void)
130 {
131 char fnametmp[MAXPATHLEN];
132 int save_dry_run = dry_run;
133
134 dry_run = 0;
135 if (!get_tmpname(fnametmp, "deldelay", False)
136 || (deldelay_fd = do_mkstemp(fnametmp, 0600)) < 0) {
137 rprintf(FINFO, "NOTE: Unable to create delete-delay temp file%s.\n",
138 inc_recurse ? "" : " -- switching to --delete-after");
139 delete_during = 0;
140 delete_after = !inc_recurse;
141 dry_run = save_dry_run;
142 return 0;
143 }
144 unlink(fnametmp);
145 dry_run = save_dry_run;
146 return 1;
147 }
148
149 static int flush_delete_delay(void)
150 {
151 if (deldelay_fd < 0 && !start_delete_delay_temp())
152 return 0;
153 if (write(deldelay_fd, deldelay_buf, deldelay_cnt) != deldelay_cnt) {
154 rsyserr(FERROR, errno, "flush of delete-delay buffer");
155 delete_during = 0;
156 delete_after = !inc_recurse;
157 close(deldelay_fd);
158 return 0;
159 }
160 deldelay_cnt = 0;
161 return 1;
162 }
163
164 static int remember_delete(struct file_struct *file, const char *fname, int flags)
165 {
166 int len;
167
168 if (deldelay_cnt == deldelay_size && !flush_delete_delay())
169 return 0;
170
171 if (flags & DEL_NO_UID_WRITE)
172 deldelay_buf[deldelay_cnt++] = '!';
173
174 while (1) {
175 len = snprintf(deldelay_buf + deldelay_cnt, deldelay_size - deldelay_cnt,
176 "%x %s%c", (int)file->mode, fname, '\0');
177 if ((deldelay_cnt += len) <= deldelay_size)
178 break;
179 deldelay_cnt -= len;
180 if (!flush_delete_delay())
181 return 0;
182 }
183
184 return 1;
185 }
186
187 static int read_delay_line(char *buf, int *flags_p)
188 {
189 static int read_pos = 0;
190 unsigned int mode;
191 int j, len;
192 char *bp, *past_space;
193
194 while (1) {
195 for (j = read_pos; j < deldelay_cnt && deldelay_buf[j]; j++) {}
196 if (j < deldelay_cnt)
197 break;
198 if (deldelay_fd < 0) {
199 if (j > read_pos)
200 goto invalid_data;
201 return -1;
202 }
203 deldelay_cnt -= read_pos;
204 if (deldelay_cnt == deldelay_size)
205 goto invalid_data;
206 if (deldelay_cnt && read_pos) {
207 memmove(deldelay_buf, deldelay_buf + read_pos,
208 deldelay_cnt);
209 }
210 len = read(deldelay_fd, deldelay_buf + deldelay_cnt,
211 deldelay_size - deldelay_cnt);
212 if (len == 0) {
213 if (deldelay_cnt) {
214 rprintf(FERROR, "ERROR: unexpected EOF in delete-delay file.\n");
215 }
216 return -1;
217 }
218 if (len < 0) {
219 rsyserr(FERROR, errno,
220 "reading delete-delay file");
221 return -1;
222 }
223 deldelay_cnt += len;
224 read_pos = 0;
225 }
226
227 bp = deldelay_buf + read_pos;
228 if (*bp == '!') {
229 bp++;
230 *flags_p = DEL_NO_UID_WRITE;
231 } else
232 *flags_p = 0;
233
234 if (sscanf(bp, "%x ", &mode) != 1) {
235 goto invalid_data;
236 }
237 past_space = strchr(bp, ' ');
238 if (!past_space) {
239 goto invalid_data;
240 }
241 past_space++;
242 /* Name length + NUL. Computed from past_space directly: the old
243 * `j - read_pos - (past_space - bp)` form was off by +1 when a '!'
244 * prefix had advanced bp past read_pos, over-reading deldelay_buf
245 * by one byte on a buffer-filling final entry. */
246 len = (deldelay_buf + j) - past_space + 1;
247 read_pos = j + 1;
248
249 if (len > MAXPATHLEN) {
250 rprintf(FERROR, "ERROR: filename too long in delete-delay file.\n");
251 return -1;
252 }
253
254 /* The caller needs the name in a MAXPATHLEN buffer, so we copy it
255 * instead of returning a pointer to our buffer. */
256 memcpy(buf, past_space, len);
257
258 return mode;
259
260 invalid_data:
261 rprintf(FERROR, "ERROR: invalid data in delete-delay file.\n");
262 return -1;
263 }
264
265 static void do_delayed_deletions(char *delbuf)
266 {
267 int mode, flags;
268
269 if (deldelay_fd >= 0) {
270 if (deldelay_cnt && !flush_delete_delay())
271 return;
272 lseek(deldelay_fd, 0, 0);
273 }
274 while ((mode = read_delay_line(delbuf, &flags)) >= 0)
275 delete_item(delbuf, mode, flags | DEL_RECURSE);
276 if (deldelay_fd >= 0)
277 close(deldelay_fd);
278 }
279
280 /* This function is used to implement per-directory deletion, and is used by
281 * all the --delete-WHEN options. Note that the fbuf pointer must point to a
282 * MAXPATHLEN buffer with the name of the directory in it (the functions we
283 * call will append names onto the end, but the old dir value will be restored
284 * on exit). */
285 static void delete_in_dir(char *fbuf, struct file_struct *file, dev_t fs_dev)
286 {
287 static int already_warned = 0;
288 static struct hashtable *dev_tbl;
289 struct file_list *dirlist;
290 char delbuf[MAXPATHLEN];
291 int dlen, i;
292
293 if (!fbuf) {
294 change_local_filter_dir(NULL, 0, 0);
295 return;
296 }
297
298 if (DEBUG_GTE(DEL, 2))
299 rprintf(FINFO, "delete_in_dir(%s)\n", fbuf);
300
301 if (allowed_lull)
302 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
303
304 if (io_error & IOERR_GENERAL && !ignore_errors) {
305 if (already_warned)
306 return;
307 rprintf(FINFO,
308 "IO error encountered -- skipping file deletion\n");
309 already_warned = 1;
310 return;
311 }
312
313 dlen = strlen(fbuf);
314 change_local_filter_dir(fbuf, dlen, F_DEPTH(file));
315
316 if (one_file_system) {
317 if (!dev_tbl)
318 dev_tbl = hashtable_create(16, HT_KEY64);
319 if (file->flags & FLAG_TOP_DIR) {
320 hashtable_find(dev_tbl, fs_dev+1, "");
321 filesystem_dev = fs_dev;
322 } else if (filesystem_dev != fs_dev) {
323 if (!hashtable_find(dev_tbl, fs_dev+1, NULL))
324 return;
325 filesystem_dev = fs_dev; /* it's a prior top-dir dev */
326 }
327 }
328
329 dirlist = get_dirlist(fbuf, dlen, 0);
330
331 /* If an item in dirlist is not found in flist, delete it
332 * from the filesystem. */
333 for (i = dirlist->used; i--; ) {
334 struct file_struct *fp = dirlist->files[i];
335 if (!F_IS_ACTIVE(fp))
336 continue;
337 if (fp->flags & FLAG_MOUNT_DIR && S_ISDIR(fp->mode)) {
338 if (INFO_GTE(MOUNT, 1))
339 rprintf(FINFO, "cannot delete mount point: %s\n",
340 f_name(fp, NULL));
341 continue;
342 }
343 /* Here we want to match regardless of file type. Replacement
344 * of a file with one of another type is handled separately by
345 * a delete_item call with a DEL_MAKE_ROOM flag. */
346 if (flist_find_ignore_dirness(cur_flist, fp) < 0) {
347 int flags = DEL_RECURSE;
348 if (!(fp->mode & S_IWUSR) && !am_root && fp->flags & FLAG_OWNED_BY_US)
349 flags |= DEL_NO_UID_WRITE;
350 f_name(fp, delbuf);
351 if (delete_during == 2) {
352 if (!remember_delete(fp, delbuf, flags))
353 break;
354 } else
355 delete_item(delbuf, fp->mode, flags);
356 }
357 }
358
359 flist_free(dirlist);
360 }
361
362 /* This deletes any files on the receiving side that are not present on the
363 * sending side. This is used by --delete-before and --delete-after. */
364 static void do_delete_pass(void)
365 {
366 char fbuf[MAXPATHLEN];
367 STRUCT_STAT st;
368 int j;
369
370 /* dry_run is incremented when the destination doesn't exist yet. */
371 if (dry_run > 1 || list_only)
372 return;
373
374 for (j = 0; j < cur_flist->used; j++) {
375 struct file_struct *file = cur_flist->sorted[j];
376
377 if (!F_IS_ACTIVE(file))
378 continue;
379
380 f_name(file, fbuf);
381
382 if (!(file->flags & FLAG_CONTENT_DIR)) {
383 change_local_filter_dir(fbuf, strlen(fbuf), F_DEPTH(file));
384 continue;
385 }
386
387 if (DEBUG_GTE(DEL, 1) && file->flags & FLAG_TOP_DIR)
388 rprintf(FINFO, "deleting in %s\n", fbuf);
389
390 if (link_stat(fbuf, &st, keep_dirlinks) < 0
391 || !S_ISDIR(st.st_mode))
392 continue;
393
394 delete_in_dir(fbuf, file, st.st_dev);
395 }
396 delete_in_dir(NULL, NULL, dev_zero);
397
398 if (INFO_GTE(FLIST, 2) && !am_server)
399 rprintf(FINFO, " \r");
400 }
401
402 static inline int mtime_differs(STRUCT_STAT *stp, struct file_struct *file)
403 {
404 #ifdef ST_MTIME_NSEC
405 return !same_time(stp->st_mtime, stp->ST_MTIME_NSEC, file->modtime, F_MOD_NSEC_or_0(file));
406 #else
407 return !same_time(stp->st_mtime, 0, file->modtime, 0);
408 #endif
409 }
410
411 static inline int any_time_differs(stat_x *sxp, struct file_struct *file, UNUSED(const char *fname))
412 {
413 int differs = mtime_differs(&sxp->st, file);
414 #ifdef SUPPORT_CRTIMES
415 if (!differs && crtimes_ndx) {
416 if (sxp->crtime == 0)
417 sxp->crtime = get_create_time(fname, &sxp->st);
418 differs = !same_time(sxp->crtime, 0, F_CRTIME(file), 0);
419 }
420 #endif
421 return differs;
422 }
423
424 static inline int perms_differ(struct file_struct *file, stat_x *sxp)
425 {
426 if (preserve_perms)
427 return !BITS_EQUAL(sxp->st.st_mode, file->mode, CHMOD_BITS);
428
429 if (preserve_executability)
430 return (sxp->st.st_mode & 0111 ? 1 : 0) ^ (file->mode & 0111 ? 1 : 0);
431
432 return 0;
433 }
434
435 static inline int ownership_differs(struct file_struct *file, stat_x *sxp)
436 {
437 if (am_root && uid_ndx && sxp->st.st_uid != (uid_t)F_OWNER(file))
438 return 1;
439
440 if (gid_ndx && !(file->flags & FLAG_SKIP_GROUP) && sxp->st.st_gid != (gid_t)F_GROUP(file))
441 return 1;
442
443 return 0;
444 }
445
446 #ifdef SUPPORT_ACLS
447 static inline int acls_differ(const char *fname, struct file_struct *file, stat_x *sxp)
448 {
449 if (preserve_acls) {
450 if (!ACL_READY(*sxp))
451 get_acl(fname, sxp);
452 if (set_acl(NULL, file, sxp, file->mode))
453 return 1;
454 }
455
456 return 0;
457 }
458 #endif
459
460 #ifdef SUPPORT_XATTRS
461 static inline int xattrs_differ(const char *fname, struct file_struct *file, stat_x *sxp)
462 {
463 if (preserve_xattrs) {
464 if (!XATTR_READY(*sxp))
465 get_xattr(fname, -1, sxp);
466 if (xattr_diff(file, sxp, 0))
467 return 1;
468 }
469
470 return 0;
471 }
472 #endif
473
474 int unchanged_attrs(const char *fname, struct file_struct *file, stat_x *sxp)
475 {
476 if (S_ISLNK(file->mode)) {
477 #ifdef CAN_SET_SYMLINK_TIMES
478 if (preserve_mtimes && !omit_link_times && any_time_differs(sxp, file, fname))
479 return 0;
480 #endif
481 #ifdef CAN_CHMOD_SYMLINK
482 if (perms_differ(file, sxp))
483 return 0;
484 #endif
485 #ifdef CAN_CHOWN_SYMLINK
486 if (ownership_differs(file, sxp))
487 return 0;
488 #endif
489 #if defined SUPPORT_ACLS && 0 /* no current symlink-ACL support */
490 if (acls_differ(fname, file, sxp))
491 return 0;
492 #endif
493 #if defined SUPPORT_XATTRS && !defined NO_SYMLINK_XATTRS
494 if (xattrs_differ(fname, file, sxp))
495 return 0;
496 #endif
497 } else {
498 if (preserve_mtimes && any_time_differs(sxp, file, fname))
499 return 0;
500 if (perms_differ(file, sxp))
501 return 0;
502 if (ownership_differs(file, sxp))
503 return 0;
504 #ifdef SUPPORT_ACLS
505 if (acls_differ(fname, file, sxp))
506 return 0;
507 #endif
508 #ifdef SUPPORT_XATTRS
509 if (xattrs_differ(fname, file, sxp))
510 return 0;
511 #endif
512 }
513
514 return 1;
515 }
516
517 void itemize(const char *fnamecmp, struct file_struct *file, int ndx, int statret,
518 stat_x *sxp, int32 iflags, uchar fnamecmp_type,
519 const char *xname)
520 {
521 if (statret >= 0) { /* A from-dest-dir statret can == 1! */
522 int keep_time = !preserve_mtimes ? 0
523 : S_ISDIR(file->mode) ? !omit_dir_times
524 : S_ISLNK(file->mode) ? !omit_link_times
525 : 1;
526
527 if (S_ISREG(file->mode) && F_LENGTH(file) != sxp->st.st_size)
528 iflags |= ITEM_REPORT_SIZE;
529 if (file->flags & FLAG_TIME_FAILED) { /* symlinks only */
530 if (iflags & ITEM_LOCAL_CHANGE)
531 iflags |= symlink_timeset_failed_flags;
532 } else if (keep_time
533 ? mtime_differs(&sxp->st, file)
534 : iflags & (ITEM_TRANSFER|ITEM_LOCAL_CHANGE) && !(iflags & ITEM_MATCHED)
535 && (!(iflags & ITEM_XNAME_FOLLOWS) || *xname))
536 iflags |= ITEM_REPORT_TIME;
537 if (atimes_ndx && !S_ISDIR(file->mode) && !S_ISLNK(file->mode)
538 && !same_time(F_ATIME(file), 0, sxp->st.st_atime, 0))
539 iflags |= ITEM_REPORT_ATIME;
540 #ifdef SUPPORT_CRTIMES
541 if (crtimes_ndx) {
542 if (sxp->crtime == 0)
543 sxp->crtime = get_create_time(fnamecmp, &sxp->st);
544 if (!same_time(sxp->crtime, 0, F_CRTIME(file), 0))
545 iflags |= ITEM_REPORT_CRTIME;
546 }
547 #endif
548 #ifndef CAN_CHMOD_SYMLINK
549 if (S_ISLNK(file->mode)) {
550 ;
551 } else
552 #endif
553 if (preserve_perms) {
554 if (!BITS_EQUAL(sxp->st.st_mode, file->mode, CHMOD_BITS))
555 iflags |= ITEM_REPORT_PERMS;
556 } else if (preserve_executability
557 && ((sxp->st.st_mode & 0111 ? 1 : 0) ^ (file->mode & 0111 ? 1 : 0)))
558 iflags |= ITEM_REPORT_PERMS;
559 if (uid_ndx && am_root && (uid_t)F_OWNER(file) != sxp->st.st_uid)
560 iflags |= ITEM_REPORT_OWNER;
561 if (gid_ndx && !(file->flags & FLAG_SKIP_GROUP) && sxp->st.st_gid != (gid_t)F_GROUP(file))
562 iflags |= ITEM_REPORT_GROUP;
563 #ifdef SUPPORT_ACLS
564 if (preserve_acls && !S_ISLNK(file->mode)) {
565 if (!ACL_READY(*sxp))
566 get_acl(fnamecmp, sxp);
567 if (set_acl(NULL, file, sxp, file->mode))
568 iflags |= ITEM_REPORT_ACL;
569 }
570 #endif
571 #ifdef SUPPORT_XATTRS
572 if (preserve_xattrs) {
573 if (!XATTR_READY(*sxp))
574 get_xattr(fnamecmp, -1, sxp);
575 if (xattr_diff(file, sxp, 1))
576 iflags |= ITEM_REPORT_XATTR;
577 }
578 #endif
579 } else {
580 #ifdef SUPPORT_XATTRS
581 if (preserve_xattrs && xattr_diff(file, NULL, 1))
582 iflags |= ITEM_REPORT_XATTR;
583 #endif
584 iflags |= ITEM_IS_NEW;
585 }
586
587 iflags &= 0xffff;
588 if ((iflags & (SIGNIFICANT_ITEM_FLAGS|ITEM_REPORT_XATTR) || INFO_GTE(NAME, 2)
589 || stdout_format_has_i > 1 || (xname && *xname)) && !read_batch) {
590 if (protocol_version >= 29) {
591 if (ndx >= 0)
592 write_ndx(sock_f_out, ndx);
593 write_shortint(sock_f_out, iflags);
594 if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
595 write_byte(sock_f_out, fnamecmp_type);
596 if (iflags & ITEM_XNAME_FOLLOWS)
597 write_vstring(sock_f_out, xname, strlen(xname));
598 #ifdef SUPPORT_XATTRS
599 if (preserve_xattrs && do_xfers
600 && iflags & (ITEM_REPORT_XATTR|ITEM_TRANSFER)) {
601 int fd = iflags & ITEM_REPORT_XATTR
602 && !(want_xattr_optim && BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE))
603 ? sock_f_out : -1;
604 send_xattr_request(NULL, file, fd);
605 }
606 #endif
607 } else if (ndx >= 0) {
608 enum logcode code = logfile_format_has_i ? FINFO : FCLIENT;
609 log_item(code, file, iflags, xname);
610 }
611 }
612 }
613
614 static enum filetype get_file_type(mode_t mode)
615 {
616 if (S_ISREG(mode))
617 return FT_REG;
618 if (S_ISLNK(mode))
619 return FT_SYMLINK;
620 if (S_ISDIR(mode))
621 return FT_DIR;
622 if (IS_SPECIAL(mode))
623 return FT_SPECIAL;
624 if (IS_DEVICE(mode))
625 return FT_DEVICE;
626 return FT_UNSUPPORTED;
627 }
628
629 /* Perform our quick-check heuristic for determining if a file is unchanged. */
630 int quick_check_ok(enum filetype ftype, const char *fn, struct file_struct *file, STRUCT_STAT *st)
631 {
632 switch (ftype) {
633 case FT_REG:
634 if (st->st_size != F_LENGTH(file))
635 return 0;
636
637 /* If always_checksum is set then we use the checksum instead
638 * of the file mtime to determine whether to sync. */
639 if (always_checksum > 0) {
640 char sum[MAX_DIGEST_LEN];
641 file_checksum(fn, st, sum);
642 return memcmp(sum, F_SUM(file), flist_csum_len) == 0;
643 }
644
645 if (size_only > 0)
646 return 1;
647
648 if (ignore_times)
649 return 0;
650
651 if (mtime_differs(st, file))
652 return 0;
653 break;
654 case FT_DIR:
655 break;
656 case FT_SYMLINK: {
657 #ifdef SUPPORT_LINKS
658 char lnk[MAXPATHLEN];
659 int len = do_readlink(fn, lnk, MAXPATHLEN-1);
660 if (len <= 0)
661 return 0;
662 lnk[len] = '\0';
663 if (strcmp(lnk, F_SYMLINK(file)) != 0)
664 return 0;
665 break;
666 #else
667 return -1;
668 #endif
669 }
670 case FT_SPECIAL:
671 if (!BITS_EQUAL(file->mode, st->st_mode, _S_IFMT))
672 return 0;
673 break;
674 case FT_DEVICE: {
675 uint32 *devp = F_RDEV_P(file);
676 if (st->st_rdev != MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp)))
677 return 0;
678 break;
679 }
680 case FT_UNSUPPORTED:
681 return -1;
682 }
683 return 1;
684 }
685
686 /*
687 * set (initialize) the size entries in the per-file sum_struct
688 * calculating dynamic block and checksum sizes.
689 *
690 * This is only called from generate_and_send_sums() but is a separate
691 * function to encapsulate the logic.
692 *
693 * The block size is a rounded square root of file length.
694 *
695 * The checksum size is determined according to:
696 * blocksum_bits = BLOCKSUM_BIAS + 2*log2(file_len) - log2(block_len)
697 * provided by Donovan Baarda which gives a probability of rsync
698 * algorithm corrupting data and falling back using the whole md4
699 * checksums.
700 *
701 * This might be made one of several selectable heuristics.
702 */
703 static void sum_sizes_sqroot(struct sum_struct *sum, int64 len)
704 {
705 int32 blength;
706 int s2length;
707 /* The strong sum can be no longer than the negotiated checksum digest:
708 * a short checksum (e.g. xxh64 = 8 bytes, when xxh128/xxh3 are absent)
709 * makes xfer_sum_len < SUM_LENGTH, and the sender rejects an s2length
710 * larger than xfer_sum_len (io.c). */
711 int max_s2length = MIN(SUM_LENGTH, xfer_sum_len);
712 int64 l;
713
714 if (len < 0) {
715 /* The file length overflowed our int64 var, so we can't process this file. */
716 sum->count = -1; /* indicate overflow error */
717 return;
718 }
719
720 if (block_size)
721 blength = block_size;
722 else if (len <= BLOCK_SIZE * BLOCK_SIZE)
723 blength = BLOCK_SIZE;
724 else {
725 int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
726 int32 c;
727 for (c = 1, l = len; l >>= 2; c <<= 1) {}
728 if (c < 0 || c >= max_blength)
729 blength = max_blength;
730 else {
731 blength = 0;
732 do {
733 blength |= c;
734 if (len < (int64)blength * blength)
735 blength &= ~c;
736 c >>= 1;
737 } while (c >= 8); /* round to multiple of 8 */
738 blength = MAX(blength, BLOCK_SIZE);
739 }
740 }
741
742 if (protocol_version < 27) {
743 s2length = csum_length;
744 } else if (csum_length == SUM_LENGTH) {
745 s2length = max_s2length;
746 } else {
747 int32 c;
748 int b = BLOCKSUM_BIAS;
749 for (l = len; l >>= 1; b += 2) {}
750 for (c = blength; (c >>= 1) && b; b--) {}
751 /* add a bit, subtract rollsum, round up. */
752 s2length = (b + 1 - 32 + 7) / 8; /* --optimize in compiler-- */
753 s2length = MAX(s2length, csum_length);
754 s2length = MIN(s2length, max_s2length);
755 }
756
757 sum->flength = len;
758 sum->blength = blength;
759 sum->s2length = s2length;
760 sum->remainder = (int32)(len % blength);
761 sum->count = (int32)(l = (len / blength) + (sum->remainder != 0));
762
763 if ((int64)sum->count != l)
764 sum->count = -1;
765
766 if (sum->count && DEBUG_GTE(DELTASUM, 2)) {
767 rprintf(FINFO,
768 "count=%s rem=%ld blength=%ld s2length=%d flength=%s\n",
769 big_num(sum->count), (long)sum->remainder, (long)sum->blength,
770 sum->s2length, big_num(sum->flength));
771 }
772 }
773
774
775 /*
776 * Generate and send a stream of signatures/checksums that describe a buffer
777 *
778 * Generate approximately one checksum every block_len bytes.
779 */
780 static int generate_and_send_sums(int fd, OFF_T len, int f_out, int f_copy)
781 {
782 int32 i;
783 struct map_struct *mapbuf;
784 struct sum_struct sum;
785 OFF_T offset = 0;
786
787 sum_sizes_sqroot(&sum, len);
788 if (sum.count < 0)
789 return -1;
790 write_sum_head(f_out, &sum);
791
792 if (append_mode > 0 && f_copy < 0)
793 return 0;
794
795 if (len > 0)
796 mapbuf = map_file(fd, len, MAX_MAP_SIZE, sum.blength);
797 else
798 mapbuf = NULL;
799
800 for (i = 0; i < sum.count; i++) {
801 int32 n1 = (int32)MIN(len, (OFF_T)sum.blength);
802 char *map = map_ptr(mapbuf, offset, n1);
803 char sum2[MAX_DIGEST_LEN];
804 uint32 sum1;
805
806 len -= n1;
807 offset += n1;
808
809 if (f_copy >= 0) {
810 full_write(f_copy, map, n1);
811 if (append_mode > 0)
812 continue;
813 }
814
815 sum1 = get_checksum1(map, n1);
816 get_checksum2(map, n1, sum2);
817
818 if (DEBUG_GTE(DELTASUM, 3)) {
819 rprintf(FINFO,
820 "chunk[%s] offset=%s len=%ld sum1=%08lx\n",
821 big_num(i), big_num(offset - n1), (long)n1,
822 (unsigned long)sum1);
823 }
824 write_int(f_out, sum1);
825 write_buf(f_out, sum2, sum.s2length);
826 }
827
828 if (mapbuf)
829 unmap_file(mapbuf);
830
831 return 0;
832 }
833
834
835 /* Try to find a filename in the same dir as "fname" with a similar name. */
836 static struct file_struct *find_fuzzy(struct file_struct *file, struct file_list *dirlist_array[], uchar *fnamecmp_type_ptr)
837 {
838 int fname_len, fname_suf_len;
839 const char *fname_suf, *fname = file->basename;
840 uint32 lowest_dist = 25 << 16; /* ignore a distance greater than 25 */
841 int i, j;
842 struct file_struct *lowest_fp = NULL;
843
844 fname_len = strlen(fname);
845 fname_suf = find_filename_suffix(fname, fname_len, &fname_suf_len);
846
847 /* Try to find an exact size+mtime match first. */
848 for (i = 0; i < fuzzy_basis; i++) {
849 struct file_list *dirlist = dirlist_array[i];
850
851 if (!dirlist)
852 continue;
853
854 for (j = 0; j < dirlist->used; j++) {
855 struct file_struct *fp = dirlist->files[j];
856
857 if (!F_IS_ACTIVE(fp))
858 continue;
859
860 if (!S_ISREG(fp->mode) || !F_LENGTH(fp) || fp->flags & FLAG_FILE_SENT)
861 continue;
862
863 if (F_LENGTH(fp) == F_LENGTH(file) && same_time(fp->modtime, 0, file->modtime, 0)) {
864 if (DEBUG_GTE(FUZZY, 2))
865 rprintf(FINFO, "fuzzy size/modtime match for %s\n", f_name(fp, NULL));
866 *fnamecmp_type_ptr = FNAMECMP_FUZZY + i;
867 return fp;
868 }
869
870 }
871 }
872
873 for (i = 0; i < fuzzy_basis; i++) {
874 struct file_list *dirlist = dirlist_array[i];
875
876 if (!dirlist)
877 continue;
878
879 for (j = 0; j < dirlist->used; j++) {
880 struct file_struct *fp = dirlist->files[j];
881 const char *suf, *name;
882 int len, suf_len;
883 uint32 dist;
884
885 if (!F_IS_ACTIVE(fp))
886 continue;
887
888 if (!S_ISREG(fp->mode) || !F_LENGTH(fp) || fp->flags & FLAG_FILE_SENT)
889 continue;
890
891 name = fp->basename;
892 len = strlen(name);
893 suf = find_filename_suffix(name, len, &suf_len);
894
895 dist = fuzzy_distance(name, len, fname, fname_len, lowest_dist);
896 /* Add some extra weight to how well the suffixes match unless we've already disqualified
897 * this file based on a heuristic. */
898 if (dist < 0xFFFF0000U) {
899 dist += fuzzy_distance(suf, suf_len, fname_suf, fname_suf_len, 0xFFFF0000U) * 10;
900 }
901 if (DEBUG_GTE(FUZZY, 2)) {
902 rprintf(FINFO, "fuzzy distance for %s = %d.%05d\n",
903 f_name(fp, NULL), (int)(dist>>16), (int)(dist&0xFFFF));
904 }
905 if (dist <= lowest_dist) {
906 lowest_dist = dist;
907 lowest_fp = fp;
908 *fnamecmp_type_ptr = FNAMECMP_FUZZY + i;
909 }
910 }
911 }
912
913 return lowest_fp;
914 }
915
916 /* Copy a file found in our --copy-dest handling. */
917 static int copy_altdest_file(const char *src, const char *dest, struct file_struct *file)
918 {
919 char buf[MAXPATHLEN];
920 const char *copy_to, *partialptr;
921 int save_preserve_xattrs = preserve_xattrs;
922 int ok, fd_w;
923
924 if (inplace) {
925 /* Let copy_file open the destination in place. */
926 fd_w = -1;
927 copy_to = dest;
928 } else {
929 fd_w = open_tmpfile(buf, dest, file);
930 if (fd_w < 0)
931 return -1;
932 copy_to = buf;
933 }
934 cleanup_set(copy_to, NULL, NULL, -1, -1);
935 if (copy_file(src, copy_to, fd_w, file->mode) < 0) {
936 if (INFO_GTE(COPY, 1)) {
937 rsyserr(FINFO, errno, "copy_file %s => %s",
938 full_fname(src), copy_to);
939 }
940 /* Try to clean up. copy_to's parent components are peer-named
941 * and can be raced to a symlink, so resolve each with O_NOFOLLOW
942 * via do_unlink_at() like the other generator-side unlinks. */
943 do_unlink_at(copy_to);
944 cleanup_disable();
945 return -1;
946 }
947 partialptr = partial_dir ? partial_dir_fname(dest) : NULL;
948 preserve_xattrs = 0; /* xattrs were copied with file */
949 ok = finish_transfer(dest, copy_to, src, partialptr, file, 1, 0);
950 preserve_xattrs = save_preserve_xattrs;
951 cleanup_disable();
952 return ok ? 0 : -1;
953 }
954
955 /* Stat an alternate-basis candidate (basis_dir[j]/fname) for a daemon /./
956 * inner-module chroot through the secure resolver, so a --compare/copy/link-dest
957 * basis can't reach outside the inner module via a symlinked parent (the kernel
958 * chroot confines only the outer path). secure_relative_open() refuses a parent
959 * that escapes beneath the module root. Plain link_stat() everywhere else --
960 * the non-chroot daemon sanitizes basis paths already, and a local receiver must
961 * still follow an operator's --link-dest=../backup. */
962 static int basis_link_stat(const char *path, STRUCT_STAT *stp)
963 {
964 extern int am_chrooted;
965 extern int operator_path_resolve;
966 extern unsigned int module_dirlen;
967 #if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY
968 /* The basis dir (--link-dest/--compare-dest/--copy-dest) is an operator-
969 * supplied path. For a non-daemon receiver, resolve it with the ownership
970 * walk: a symlink component owned by uid 0 or the euid (the operator's own
971 * basis dir, e.g. --link-dest=/var/backups) is followed, a foreign-owned one
972 * is refused -- absolute and relative alike. Refusing it makes the basis
973 * look absent, so the file transfers normally instead of being read/linked/
974 * skipped through an attacker's symlink. --insecure-links restores legacy
975 * following; a daemon keeps its stronger confinement (chroot / secure
976 * resolver) below. Only when am_root >= 0: link_stat_at() omits the
977 * fake-super %stat xattr that link_stat() folds in, so --fake-super keeps
978 * the plain path (a lower-severity, non-root basis lookup). */
979 if (!am_daemon && am_root >= 0 && !symlink_optout_allowed()) {
980 const char *leaf;
981 int dfd = owner_walk_parent(path, &leaf);
982 int r, e;
983 if (dfd < 0)
984 return -1;
985 r = link_stat_at(dfd, leaf, stp, 0);
986 e = errno;
987 close(dfd);
988 errno = e;
989 return r;
990 }
991 /* A non-chroot daemon serving an operator/peer alt-dest basis: resolve through
992 * the ownership walk with module-ROOT confinement (operator_path_resolve) so an
993 * in-module symlink whose target lands OUTSIDE the module is refused -- the
994 * basis then looks absent and the file transfers normally instead of being
995 * stat'd/read/linked through the link (closes the --compare-dest=/E read
996 * oracle). "insecure links = yes" falls through to the legacy link_stat()
997 * below, restoring 3.2.7 following. Only an ABSOLUTE basis (rooted under the
998 * module by check_alt_basis_dirs, so it can reach an in-module symlink) is
999 * confined here; a RELATIVE basis (--link-dest=../01) is a dest-relative
1000 * sibling whose "../" is already clamped to the module root by sanitize_path,
1001 * and must keep the plain link_stat below (#915/#930). The leaf is taken
1002 * under the confined parent with O_NOFOLLOW/AT_SYMLINK_NOFOLLOW, so
1003 * --copy-links can't follow a leaf symlink out of the module. */
1004 if (am_daemon && !am_chrooted && path[0] == '/' && !symlink_optout_allowed()) {
1005 const char *leaf;
1006 int dfd, e, save = operator_path_resolve;
1007 operator_path_resolve = 1;
1008 dfd = owner_walk_parent(path, &leaf);
1009 operator_path_resolve = save;
1010 if (dfd < 0)
1011 return -1;
1012 if (am_root >= 0) {
1013 int r = do_lstat_atfd(dfd, leaf, stp);
1014 e = errno;
1015 close(dfd);
1016 errno = e;
1017 return r;
1018 }
1019 #ifdef SUPPORT_XATTRS
1020 {
1021 /* --fake-super: O_NOFOLLOW-open the held leaf (the daemon owns its
1022 * fake-super files) so the %stat xattr link_stat() would fold is
1023 * preserved while a leaf symlink is still refused. */
1024 int lfd = do_open_atfd(dfd, leaf, O_RDONLY | O_NOFOLLOW | O_NONBLOCK, 0);
1025 STRUCT_STAT xst;
1026 e = errno;
1027 close(dfd);
1028 if (lfd < 0) { errno = e; return -1; }
1029 if (do_fstat(lfd, stp) < 0) { e = errno; close(lfd); errno = e; return -1; }
1030 if (get_stat_xattr(NULL, lfd, stp, &xst) == 0)
1031 *stp = xst;
1032 close(lfd);
1033 return 0;
1034 }
1035 #else
1036 {
1037 int r = do_lstat_atfd(dfd, leaf, stp);
1038 e = errno;
1039 close(dfd);
1040 errno = e;
1041 return r;
1042 }
1043 #endif
1044 }
1045 #endif
1046 if (am_daemon && am_chrooted && module_dirlen && path[0] != '/' && !symlink_optout_allowed()) {
1047 const char *slash = strrchr(path, '/');
1048 if (slash) {
1049 char dir[MAXPATHLEN];
1050 size_t dlen = (size_t)(slash - path);
1051 int dfd, r, e;
1052 if (dlen >= sizeof dir) { errno = ENAMETOOLONG; return -1; }
1053 memcpy(dir, path, dlen);
1054 dir[dlen] = '\0';
1055 if ((dfd = secure_relative_open(NULL, dir, O_RDONLY | O_DIRECTORY, 0)) < 0)
1056 return -1;
1057 r = link_stat_at(dfd, slash + 1, stp, 0);
1058 e = errno;
1059 close(dfd);
1060 errno = e;
1061 return r;
1062 }
1063 }
1064 return link_stat(path, stp, 0);
1065 }
1066
1067 /* This is only called for regular files. We return -2 if we've finished
1068 * handling the file, -1 if no dest-linking occurred, or a non-negative
1069 * value if we found an alternate basis file. If we're called with the
1070 * find_exact_for_existing flag, the destination file already exists, so
1071 * we only try to find an exact alt-dest match. In this case, the returns
1072 * are only -2 & -1 (both as above). */
1073 static int try_dests_reg(struct file_struct *file, char *fname, int ndx,
1074 char *cmpbuf, stat_x *sxp, int find_exact_for_existing,
1075 int itemizing, enum logcode code)
1076 {
1077 STRUCT_STAT real_st = sxp->st;
1078 int best_match = -1;
1079 int match_level = 0;
1080 int j = 0;
1081
1082 do {
1083 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
1084 if (basis_link_stat(cmpbuf, &sxp->st) < 0 || !S_ISREG(sxp->st.st_mode))
1085 continue;
1086 if (match_level == 0) {
1087 best_match = j;
1088 match_level = 1;
1089 }
1090 if (!quick_check_ok(FT_REG, cmpbuf, file, &sxp->st))
1091 continue;
1092 if (match_level == 1) {
1093 best_match = j;
1094 match_level = 2;
1095 }
1096 if (unchanged_attrs(cmpbuf, file, sxp)) {
1097 best_match = j;
1098 match_level = 3;
1099 break;
1100 }
1101 free_stat_x(sxp);
1102 } while (basis_dir[++j] != NULL);
1103
1104 if (!match_level)
1105 goto got_nothing_for_ya;
1106
1107 if (j != best_match) {
1108 j = best_match;
1109 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
1110 if (basis_link_stat(cmpbuf, &sxp->st) < 0)
1111 goto got_nothing_for_ya;
1112 }
1113
1114 if (match_level == 3 && alt_dest_type != COPY_DEST) {
1115 if (find_exact_for_existing) {
1116 if (alt_dest_type == LINK_DEST && real_st.st_dev == sxp->st.st_dev && real_st.st_ino == sxp->st.st_ino)
1117 return -1;
1118 if (do_unlink_at(fname) < 0 && errno != ENOENT)
1119 goto got_nothing_for_ya;
1120 }
1121 #ifdef SUPPORT_HARD_LINKS
1122 if (alt_dest_type == LINK_DEST) {
1123 /* For a NON-daemon receiver the basis dir is an operator path:
1124 * resolve the link source via the ownership walk so a foreign-owned
1125 * symlink raced in after the basis_link_stat() check is still
1126 * refused (matching basis_link_stat's !am_daemon gate). A daemon
1127 * keeps its stronger module-anchored confinement (do_link_at's
1128 * secure_relpath_active path) -- the ownership walk would follow an
1129 * operator-owned symlink out of the module. */
1130 int hlok, op = !am_daemon;
1131 if (op)
1132 operator_path_resolve = 1;
1133 hlok = hard_link_one(file, fname, cmpbuf, 1);
1134 if (op)
1135 operator_path_resolve = 0;
1136 if (!hlok)
1137 goto try_a_copy;
1138 if (atimes_ndx)
1139 set_file_attrs(fname, file, sxp, NULL, 0);
1140 if (preserve_hard_links && F_IS_HLINKED(file))
1141 finish_hard_link(file, fname, ndx, &sxp->st, itemizing, code, j);
1142 if (!maybe_ATTRS_REPORT && (INFO_GTE(NAME, 2) || stdout_format_has_i > 1)) {
1143 itemize(cmpbuf, file, ndx, 1, sxp,
1144 ITEM_LOCAL_CHANGE | ITEM_XNAME_FOLLOWS,
1145 0, "");
1146 }
1147 } else
1148 #endif
1149 {
1150 if (itemizing)
1151 itemize(cmpbuf, file, ndx, 0, sxp, 0, 0, NULL);
1152 }
1153 if (INFO_GTE(NAME, 2) && maybe_ATTRS_REPORT)
1154 rprintf(FCLIENT, "%s is uptodate\n", fname);
1155 return -2;
1156 }
1157
1158 if (find_exact_for_existing)
1159 goto got_nothing_for_ya;
1160
1161 if (match_level >= 2) {
1162 #ifdef SUPPORT_HARD_LINKS
1163 try_a_copy: /* Copy the file locally. */
1164 #endif
1165 /* NB: the copy-dest basis read is deliberately NOT routed through the
1166 * ownership walk: copy_altdest_file()->copy_file() also opens the dest
1167 * and copies xattrs through a held O_NOFOLLOW fd, and forcing
1168 * operator_path_resolve across that re-opens the copy_xattrs parent-
1169 * symlink race (copy-xattrs-symlink-race). basis_link_stat() already
1170 * refuses a foreign-owned basis symlink, closing the static escape; the
1171 * post-stat race on an absolute copy-dest basis is a documented residual. */
1172 if (!dry_run && copy_altdest_file(cmpbuf, fname, file) < 0) {
1173 if (find_exact_for_existing) /* Can get here via hard-link failure */
1174 goto got_nothing_for_ya;
1175 return -1;
1176 }
1177 if (itemizing)
1178 itemize(cmpbuf, file, ndx, 0, sxp, ITEM_LOCAL_CHANGE, 0, NULL);
1179 if (maybe_ATTRS_REPORT
1180 && ((!itemizing && INFO_GTE(NAME, 1) && match_level == 2)
1181 || (INFO_GTE(NAME, 2) && match_level == 3))) {
1182 code = match_level == 3 ? FCLIENT : FINFO;
1183 rprintf(code, "%s%s\n", fname,
1184 match_level == 3 ? " is uptodate" : "");
1185 }
1186 #ifdef SUPPORT_HARD_LINKS
1187 if (preserve_hard_links && F_IS_HLINKED(file))
1188 finish_hard_link(file, fname, ndx, &sxp->st, itemizing, code, -1);
1189 #endif
1190 return -2;
1191 }
1192
1193 return FNAMECMP_BASIS_DIR_LOW + j;
1194
1195 got_nothing_for_ya:
1196 sxp->st = real_st;
1197 return -1;
1198 }
1199
1200 /* This is only called for non-regular files. We return -2 if we've finished
1201 * handling the file, -3 if we matched one but the destination refused to
1202 * hard-link it (the caller creates it instead, and must not report it again),
1203 * or -1 if no dest-linking occurred, or a non-negative value if we found an
1204 * alternate basis file. */
1205 static int try_dests_non(struct file_struct *file, char *fname, int ndx,
1206 char *cmpbuf, stat_x *sxp, int itemizing,
1207 enum logcode code)
1208 {
1209 int best_match = -1;
1210 int match_level = 0;
1211 enum filetype ftype = get_file_type(file->mode);
1212 int j = 0;
1213
1214 #ifndef SUPPORT_LINKS
1215 if (ftype == FT_SYMLINK)
1216 return -1;
1217 #endif
1218 if (ftype == FT_REG || ftype == FT_UNSUPPORTED) {
1219 rprintf(FERROR,
1220 "internal: try_dests_non() called with invalid mode (%o)\n",
1221 (int)file->mode);
1222 exit_cleanup(RERR_UNSUPPORTED);
1223 }
1224
1225 do {
1226 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
1227 if (basis_link_stat(cmpbuf, &sxp->st) < 0)
1228 continue;
1229 if (ftype != get_file_type(sxp->st.st_mode))
1230 continue;
1231 if (match_level < 1) {
1232 match_level = 1;
1233 best_match = j;
1234 }
1235 if (!quick_check_ok(ftype, cmpbuf, file, &sxp->st))
1236 continue;
1237 if (match_level < 2) {
1238 match_level = 2;
1239 best_match = j;
1240 }
1241 if (unchanged_attrs(cmpbuf, file, sxp)) {
1242 match_level = 3;
1243 best_match = j;
1244 break;
1245 }
1246 } while (basis_dir[++j] != NULL);
1247
1248 if (!match_level)
1249 return -1;
1250
1251 if (j != best_match) {
1252 j = best_match;
1253 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
1254 if (basis_link_stat(cmpbuf, &sxp->st) < 0)
1255 return -1;
1256 }
1257
1258 if (match_level == 3) {
1259 int cannot_hardlink = 0;
1260 #ifdef SUPPORT_HARD_LINKS
1261 if (alt_dest_type == LINK_DEST
1262 #ifndef CAN_HARDLINK_SYMLINK
1263 && !S_ISLNK(file->mode)
1264 #endif
1265 #ifndef CAN_HARDLINK_SPECIAL
1266 && !IS_SPECIAL(file->mode) && !IS_DEVICE(file->mode)
1267 #endif
1268 && !S_ISDIR(file->mode)) {
1269 if (do_link_at(cmpbuf, fname) < 0) {
1270 /* CAN_HARDLINK_SYMLINK/_SPECIAL answer for whatever
1271 * filesystem the build tree sat on; the destination is
1272 * free to disagree, and one host can hold both (macOS
1273 * builds on APFS, backs up to HFS+). A refusal here is
1274 * that same answer arriving late, so fall back to a copy
1275 * as a build without the macro does -- the caller creates
1276 * the entry either way, so failing the transfer only cost
1277 * the exit status.
1278 *
1279 * Every errno, as the regular-file path next door already
1280 * does (try_dests_reg -> hard_link_one -> try_a_copy).
1281 * Picking out the "cannot" errnos is not possible anyway:
1282 * link(2) documents EPERM both for a filesystem with no
1283 * hard-link support and for an ordinary permission
1284 * refusal, and FUSE reports ENOSYS for the same thing.
1285 *
1286 * The rest report themselves: ENOSPC/EDQUOT/EROFS fail the
1287 * copy too, EMLINK and EXDEV mean it was never linkable.
1288 * EIO alone goes unremarked, deliberately -- a diagnostic
1289 * here lands in --link-dest's itemised output. */
1290 cannot_hardlink = 1;
1291 match_level = 2;
1292 } else if (preserve_hard_links && F_IS_HLINKED(file))
1293 finish_hard_link(file, fname, ndx, NULL, itemizing, code, -1);
1294 } else
1295 #endif
1296 match_level = 2;
1297 if (itemizing && stdout_format_has_i
1298 && (INFO_GTE(NAME, 2) || stdout_format_has_i > 1)) {
1299 int chg = alt_dest_type == COMPARE_DEST && ftype != FT_DIR ? 0
1300 : ITEM_LOCAL_CHANGE + (match_level == 3 ? ITEM_XNAME_FOLLOWS : 0);
1301 char *lp = match_level == 3 ? "" : NULL;
1302 itemize(cmpbuf, file, ndx, 0, sxp, chg + ITEM_MATCHED, 0, lp);
1303 }
1304 if (INFO_GTE(NAME, 2) && maybe_ATTRS_REPORT) {
1305 rprintf(FCLIENT, "%s%s is uptodate\n",
1306 fname, ftype == FT_DIR ? "/" : "");
1307 }
1308 /* -2 tells the caller the entry is already up to date, which for
1309 * --link-dest means "skip it". We could not link it, so say -3
1310 * instead: no caller claims that, and the fall-through creates the
1311 * entry -- the same place a build without the macro ends up. */
1312 return cannot_hardlink ? -3 : -2;
1313 }
1314
1315 return j;
1316 }
1317
1318 static void list_file_entry(struct file_struct *f)
1319 {
1320 char permbuf[PERMSTRING_SIZE];
1321 const char *mtime_str = timestring(f->modtime);
1322 int size_width = human_readable ? 14 : 11;
1323 int mtime_width = 1 + strlen(mtime_str);
1324 int atime_width = atimes_ndx ? mtime_width : 0;
1325 int crtime_width = crtimes_ndx ? mtime_width : 0;
1326
1327 if (!F_IS_ACTIVE(f)) {
1328 /* this can happen if duplicate names were removed */
1329 return;
1330 }
1331
1332 /* TODO: indicate '+' if the entry has an ACL. */
1333
1334 if (missing_args == 2 && f->mode == 0) {
1335 rprintf(FINFO, "%-*s %s\n",
1336 10 + 1 + size_width + mtime_width + atime_width + crtime_width, "*missing",
1337 f_name(f, NULL));
1338 } else {
1339 const char *atime_str = atimes_ndx && !S_ISDIR(f->mode) ? timestring(F_ATIME(f)) : "";
1340 const char *crtime_str = crtimes_ndx ? timestring(F_CRTIME(f)) : "";
1341 const char *arrow, *lnk;
1342
1343 permstring(permbuf, f->mode);
1344
1345 #ifdef SUPPORT_LINKS
1346 if (preserve_links && S_ISLNK(f->mode)) {
1347 arrow = " -> ";
1348 lnk = F_SYMLINK(f);
1349 } else
1350 #endif
1351 arrow = lnk = "";
1352
1353 rprintf(FINFO, "%s %*s %s%*s%*s %s%s%s\n",
1354 permbuf, size_width, human_num(F_LENGTH(f)),
1355 timestring(f->modtime), atime_width, atime_str, crtime_width, crtime_str,
1356 f_name(f, NULL), arrow, lnk);
1357 }
1358 }
1359
1360 static int phase = 0;
1361 static int dflt_perms;
1362
1363 static int implied_dirs_are_missing;
1364 /* Helper for recv_generator's skip_dir and dry_missing_dir tests. */
1365 static BOOL is_below(struct file_struct *file, struct file_struct *subtree)
1366 {
1367 return F_DEPTH(file) > F_DEPTH(subtree)
1368 && (!implied_dirs_are_missing || f_name_has_prefix(file, subtree));
1369 }
1370
1371 /* Acts on the indicated item in cur_flist whose name is fname. If a dir,
1372 * make sure it exists, and has the right permissions/timestamp info. For
1373 * all other non-regular files (symlinks, etc.) we create them here. For
1374 * regular files that have changed, we try to find a basis file and then
1375 * start sending checksums. The ndx is the file's unique index value.
1376 *
1377 * The fname parameter must point to a MAXPATHLEN buffer! (e.g it gets
1378 * passed to delete_item(), which can use it during a recursive delete.)
1379 *
1380 * Note that f_out is set to -1 when doing final directory-permission and
1381 * modification-time repair. */
1382
1383 /* Held-dirfd helpers for the per-entry ops below: when the secure resolver is
1384 * active they act on the entry's basename relative to its cached directory fd
1385 * (held_dfd_for, keyed on file->dirname), else fall back to the full-path
1386 * do_*_at wrappers (behaviour-identical). held_dfd_for() declines when fname
1387 * isn't in file->dirname (e.g. the single-file local_name dest), and the leaf
1388 * is derived from fname, not file->basename. */
1389 static int gen_entry_stat(const char *fname, struct file_struct *file,
1390 STRUCT_STAT *stp, int follow_dirlinks)
1391 {
1392 int dfd;
1393 /* link_stat_at folds in no fake-super xattr, so only use it when
1394 * am_root >= 0 (where link_stat's get_stat_xattr is a no-op anyway). */
1395 if (am_root >= 0 && (dfd = held_dfd_for(fname, file)) >= 0) {
1396 const char *slash = strrchr(fname, '/');
1397 return link_stat_at(dfd, slash ? slash + 1 : fname, stp, follow_dirlinks);
1398 }
1399 return link_stat(fname, stp, follow_dirlinks);
1400 }
1401
1402 static int gen_entry_mkdir(char *fname, struct file_struct *file, mode_t mode)
1403 {
1404 int dfd = held_dfd_for(fname, file);
1405 if (dfd >= 0) {
1406 const char *slash = strrchr(fname, '/');
1407 return do_mkdir_atfd(dfd, slash ? slash + 1 : fname, mode);
1408 }
1409 return do_mkdir_at(fname, mode);
1410 }
1411
1412 static int gen_entry_chmod(const char *fname, struct file_struct *file, mode_t mode)
1413 {
1414 int dfd = held_dfd_for(fname, file);
1415 if (dfd >= 0) {
1416 const char *slash = strrchr(fname, '/');
1417 return do_chmod_atfd(dfd, slash ? slash + 1 : fname, mode);
1418 }
1419 return do_chmod_at(fname, mode);
1420 }
1421
1422 static void gen_entry_set_times(const char *fname, struct file_struct *file, STRUCT_STAT *stp)
1423 {
1424 int dfd = held_dfd_for(fname, file);
1425 if (dfd >= 0) {
1426 const char *slash = strrchr(fname, '/');
1427 if (set_times_at(dfd, slash ? slash + 1 : fname, stp) != -2)
1428 return; /* handled (success or error) by the at-on-dfd tier */
1429 }
1430 set_times(fname, stp);
1431 }
1432
1433 static int gen_entry_symlink(const char *slnk, const char *path, struct file_struct *file)
1434 {
1435 int dfd = held_dfd_for(path, file);
1436 if (dfd >= 0) {
1437 const char *slash = strrchr(path, '/');
1438 return do_symlink_atfd(slnk, dfd, slash ? slash + 1 : path);
1439 }
1440 return do_symlink_at(slnk, path);
1441 }
1442
1443 /* True when this build compiled no fd-relative primitive able to create this
1444 * kind of node. That is a property of the build, not of the call, so it is
1445 * decided here rather than inferred from an errno. */
1446 static int no_atfd_mknod_primitive(mode_t mode)
1447 {
1448 #ifndef AT_FDCWD
1449 (void)mode;
1450 return 1;
1451 #else
1452 /* --fake-super creates the placeholder with openat(), which exists
1453 * wherever AT_FDCWD does, so a failure there is a real failure and is
1454 * deliberately NOT retried unconfined -- even though a runtime denial
1455 * (a seccomp policy permitting open() but not openat()) would then fail
1456 * a create that the errno-based test used to let through. */
1457 if (am_root < 0)
1458 return 0;
1459 # ifdef HAVE_MKNODAT
1460 (void)mode;
1461 return 0;
1462 # elif defined(HAVE_MKFIFOAT)
1463 return !S_ISFIFO(mode); /* FIFOs are covered; device nodes are not */
1464 # else
1465 (void)mode;
1466 return 1;
1467 # endif
1468 #endif
1469 }
1470
1471 static int gen_entry_mknod(const char *path, struct file_struct *file, mode_t mode, dev_t rdev)
1472 {
1473 int dfd;
1474 /* do_mknod_atfd can't create a socket (no portable bindat); fall back. */
1475 if (!S_ISSOCK(mode) && (dfd = held_dfd_for(path, file)) >= 0) {
1476 const char *slash = strrchr(path, '/');
1477 int ret = do_mknod_atfd(dfd, slash ? slash + 1 : path, mode, rdev);
1478 /* Fall through to the unconfined path-based create only where this
1479 * build compiled no fd-relative primitive for this kind of node --
1480 * SECURITY.md's rule for a platform that cannot be secure at all.
1481 * Testing errno == ENOSYS is not that test: a live mknodat() or
1482 * mkfifoat() can return ENOSYS too (an unimplemented FUSE mknod,
1483 * or seccomp), which would drop confinement on a platform that
1484 * does have the secure primitive. */
1485 if (ret == 0 || !no_atfd_mknod_primitive(mode))
1486 return ret;
1487 }
1488 return do_mknod_at(path, mode, rdev);
1489 }
1490
1491 static int gen_entry_unlink(const char *path, struct file_struct *file)
1492 {
1493 int dfd = held_dfd_for(path, file);
1494 if (dfd >= 0) {
1495 const char *slash = strrchr(path, '/');
1496 return do_unlink_atfd(dfd, slash ? slash + 1 : path, 0);
1497 }
1498 return do_unlink_at(path);
1499 }
1500
1501 /* opath and npath are both expected to live in the entry's directory (the
1502 * tmp -> final rename); when both resolve to the held dir fd the rename is a
1503 * single renameat() within it, else fall back to the full-path wrapper. */
1504 static int gen_entry_rename(const char *opath, const char *npath, struct file_struct *file)
1505 {
1506 int odfd = held_dfd_for(opath, file);
1507 int ndfd = held_dfd_for(npath, file);
1508 if (odfd >= 0 && ndfd >= 0) {
1509 const char *os = strrchr(opath, '/');
1510 const char *ns = strrchr(npath, '/');
1511 return do_rename_atfd(odfd, os ? os + 1 : opath, ndfd, ns ? ns + 1 : npath);
1512 }
1513 return do_rename_at(opath, npath);
1514 }
1515
1516 #ifdef SUPPORT_XATTRS
1517 /* Copy xattrs from src onto fname through a held, O_NOFOLLOW-opened fd so a
1518 * parent-symlink race can't redirect the setxattr. A hardened receiver always
1519 * uses a confined fd -- via the cached dir fd, or a secure re-pin when that
1520 * misses -- and refuses rather than path-write if it can't pin; only a
1521 * non-hardened receiver falls back to the path-based copy (matches
1522 * set_file_attrs' held-fd handling). */
1523 static int gen_entry_copy_xattrs(const char *src, const char *fname, struct file_struct *file)
1524 {
1525 int dfd = held_dfd_for(fname, file);
1526 int xfd = -1, sfd = -1, ret;
1527 if (dfd >= 0) {
1528 const char *slash = strrchr(fname, '/');
1529 xfd = openat(dfd, slash ? slash + 1 : fname,
1530 O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_NOCTTY | O_CLOEXEC);
1531 if (xfd < 0) {
1532 /* We hold a confined parent dirfd but couldn't pin the
1533 * leaf (e.g. it was raced to a symlink) -- refuse rather
1534 * than fall back to a path-based set that would follow the
1535 * parent components. */
1536 rsyserr(FERROR_XFER, errno,
1537 "gen_entry_copy_xattrs: openat(%s) failed",
1538 full_fname(fname));
1539 return -1;
1540 }
1541 }
1542 #if defined AT_FDCWD && defined O_NOFOLLOW
1543 else if (secure_relpath_active()) {
1544 /* No cached parent dirfd (a path deeper than the dirfd cache, or a raced
1545 * parent) but we must confine: re-pin the dest leaf through the secure
1546 * resolver so copy_xattrs uses fsetxattr, not a path-based lsetxattr a
1547 * flipped parent could redirect out of tree. A raced parent/leaf makes
1548 * this fail -> refuse rather than path-write. */
1549 int odir = 0;
1550 # ifdef O_DIRECTORY
1551 if (S_ISDIR(file->mode))
1552 odir = O_DIRECTORY;
1553 # endif
1554 xfd = secure_relative_open(NULL, fname,
1555 O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_NOCTTY | O_CLOEXEC | odir, 0);
1556 if (xfd < 0) {
1557 rsyserr(FERROR_XFER, errno,
1558 "gen_entry_copy_xattrs: secure open of %s failed",
1559 full_fname(fname));
1560 return -1;
1561 }
1562 }
1563 #endif
1564 /* Pin the SOURCE (alt-dest basis) leaf too so the xattr READ can't be raced
1565 * out of tree (copy_file does the same for its content+xattr source). A
1566 * relative basis goes through the RESOLVE_BENEATH resolver; an absolute one
1567 * through the operator ownership walk. Refuse (don't path-read) when we are
1568 * meant to confine but can't pin; a non-hardened receiver path-reads (sfd<0). */
1569 #if defined AT_FDCWD && defined O_NOFOLLOW
1570 if (secure_relpath_active() && src && *src && !symlink_optout_allowed()) {
1571 int odir = 0;
1572 #ifdef O_DIRECTORY
1573 if (S_ISDIR(file->mode)) /* secure_relative_open rejects a dir leaf without this */
1574 odir = O_DIRECTORY;
1575 #endif
1576 if (src[0] != '/')
1577 sfd = secure_relative_open(NULL, src, O_RDONLY | O_NOFOLLOW | odir, 0);
1578 else {
1579 int save = operator_path_resolve, sdfd, e;
1580 const char *leaf;
1581 operator_path_resolve = 1;
1582 sdfd = owner_walk_parent(src, &leaf);
1583 operator_path_resolve = save;
1584 if (sdfd >= 0) {
1585 sfd = openat(sdfd, leaf, O_RDONLY | O_NOFOLLOW | odir | O_NONBLOCK | O_NOCTTY | O_CLOEXEC);
1586 e = errno; close(sdfd); errno = e;
1587 }
1588 }
1589 if (sfd < 0) {
1590 rsyserr(FERROR_XFER, errno,
1591 "gen_entry_copy_xattrs: secure open of basis %s failed",
1592 full_fname(src));
1593 if (xfd >= 0)
1594 close(xfd);
1595 return -1;
1596 }
1597 }
1598 #endif
1599 ret = copy_xattrs(src, sfd, fname, xfd);
1600 if (sfd >= 0)
1601 close(sfd);
1602 if (xfd >= 0)
1603 close(xfd);
1604 return ret;
1605 }
1606 #endif
1607
1608 static void recv_generator(char *fname, struct file_struct *file, int ndx,
1609 int itemizing, enum logcode code, int f_out)
1610 {
1611 static const char *parent_dirname = "";
1612 static struct file_struct *prior_dir_file = NULL;
1613 /* Missing dir not created due to --dry-run; will still be scanned. */
1614 static struct file_struct *dry_missing_dir = NULL;
1615 /* Missing dir whose contents are skipped altogether due to
1616 * --ignore-non-existing, daemon exclude, or mkdir failure. */
1617 static struct file_struct *skip_dir = NULL;
1618 static struct file_list *fuzzy_dirlist[MAX_BASIS_DIRS+1];
1619 static int need_fuzzy_dirlist = 0;
1620 struct file_struct *fuzzy_file = NULL;
1621 int fd = -1, f_copy = -1;
1622 stat_x sx = {0}, real_sx = {0};
1623 STRUCT_STAT partial_st;
1624 struct file_struct *back_file = NULL;
1625 int statret, real_ret, stat_errno;
1626 char *fnamecmp, *partialptr, *backupptr = NULL;
1627 char fnamecmpbuf[MAXPATHLEN];
1628 uchar fnamecmp_type;
1629 int del_opts = delete_mode || force_delete ? DEL_RECURSE : 0;
1630 enum filetype stype, ftype = get_file_type(file->mode);
1631 int is_dir = ftype != FT_DIR ? 0
1632 : inc_recurse && ndx != cur_flist->ndx_start - 1 ? -1
1633 : 1;
1634
1635 if (DEBUG_GTE(GENR, 1))
1636 rprintf(FINFO, "recv_generator(%s,%d)\n", fname, ndx);
1637
1638 if (list_only) {
1639 if (is_dir < 0
1640 || (is_dir && !implied_dirs && file->flags & FLAG_IMPLIED_DIR))
1641 return;
1642 list_file_entry(file);
1643 return;
1644 }
1645
1646 maybe_ATTRS_ACCURATE_TIME = always_checksum ? ATTRS_ACCURATE_TIME : 0;
1647
1648 if (skip_dir) {
1649 if (is_below(file, skip_dir)) {
1650 if (is_dir)
1651 file->flags |= FLAG_MISSING_DIR;
1652 #ifdef SUPPORT_HARD_LINKS
1653 else if (F_IS_HLINKED(file))
1654 handle_skipped_hlink(file, itemizing, code, f_out);
1655 #endif
1656 return;
1657 }
1658 skip_dir = NULL;
1659 }
1660
1661 init_stat_x(&sx);
1662 if (daemon_filter_list.head && (*fname != '.' || fname[1])) {
1663 if (check_filter(&daemon_filter_list, FLOG, fname, is_dir) < 0) {
1664 if (is_dir < 0)
1665 return;
1666 #ifdef SUPPORT_HARD_LINKS
1667 if (F_IS_HLINKED(file))
1668 handle_skipped_hlink(file, itemizing, code, f_out);
1669 #endif
1670 rprintf(FERROR_XFER,
1671 "ERROR: daemon refused to receive %s \"%s\"\n",
1672 is_dir ? "directory" : "file", fname);
1673 if (is_dir)
1674 goto skipping_dir_contents;
1675 return;
1676 }
1677 }
1678
1679 if (dry_run > 1 || (dry_missing_dir && is_below(file, dry_missing_dir))) {
1680 int i;
1681 parent_is_dry_missing:
1682 for (i = 0; i < fuzzy_basis; i++) {
1683 if (fuzzy_dirlist[i]) {
1684 flist_free(fuzzy_dirlist[i]);
1685 fuzzy_dirlist[i] = NULL;
1686 }
1687 }
1688 parent_dirname = "";
1689 statret = -1;
1690 stat_errno = ENOENT;
1691 } else {
1692 const char *dn = file->dirname ? file->dirname : ".";
1693 dry_missing_dir = NULL;
1694 if (parent_dirname != dn && strcmp(parent_dirname, dn) != 0) {
1695 /* Each parent dir must be in the file list or the flist data is bad.
1696 * Optimization: most of the time the parent dir will be the last dir
1697 * this function was asked to process in the file list. */
1698 if (!inc_recurse
1699 && (*dn != '.' || dn[1]) /* Avoid an issue with --relative and the "." dir. */
1700 && (!prior_dir_file || strcmp(dn, f_name(prior_dir_file, NULL)) != 0)) {
1701 int ok = 0, j = flist_find_name(cur_flist, dn, -1);
1702 if (j >= 0) {
1703 struct file_struct *f = cur_flist->sorted[j];
1704 if (S_ISDIR(f->mode) || (missing_args == 2 && !file->mode && !f->mode))
1705 ok = 1;
1706 }
1707 /* The --delete-missing-args option can actually put invalid entries into
1708 * the file list, so if that option was specified, we'll just complain about
1709 * it and allow it. */
1710 if (!ok && missing_args == 2 && file->mode == 0 && j < 0)
1711 rprintf(FERROR, "WARNING: parent dir is absent in the file list: %s\n", dn);
1712 else if (!ok) {
1713 rprintf(FERROR, "ABORTING due to invalid path from sender: %s/%s\n",
1714 dn, file->basename);
1715 exit_cleanup(RERR_PROTOCOL);
1716 }
1717 }
1718 if (relative_paths && !implied_dirs && file->mode != 0
1719 && do_stat_at(dn, &sx.st) < 0) {
1720 if (dry_run)
1721 goto parent_is_dry_missing;
1722 if (make_path(fname, MKP_DROP_NAME | MKP_SKIP_SLASH) < 0) {
1723 rsyserr(FERROR_XFER, errno,
1724 "recv_generator: mkdir %s failed",
1725 full_fname(dn));
1726 }
1727 }
1728 if (fuzzy_basis) {
1729 int i;
1730 for (i = 0; i < fuzzy_basis; i++) {
1731 if (fuzzy_dirlist[i]) {
1732 flist_free(fuzzy_dirlist[i]);
1733 fuzzy_dirlist[i] = NULL;
1734 }
1735 }
1736 need_fuzzy_dirlist = 1;
1737 }
1738 #ifdef SUPPORT_ACLS
1739 if (!preserve_perms)
1740 dflt_perms = default_perms_for_dir(dn);
1741 #endif
1742 }
1743 parent_dirname = dn;
1744
1745 statret = gen_entry_stat(fname, file, &sx.st, keep_dirlinks && is_dir);
1746 stat_errno = errno;
1747 }
1748
1749 if (missing_args == 2 && file->mode == 0) {
1750 if (filter_list.head && check_filter(&filter_list, FINFO, fname, is_dir) < 0)
1751 return;
1752 if (statret == 0)
1753 delete_item(fname, sx.st.st_mode, del_opts);
1754 return;
1755 }
1756
1757 if (ignore_non_existing > 0 && statret == -1 && stat_errno == ENOENT) {
1758 if (is_dir) {
1759 if (is_dir < 0)
1760 return;
1761 skip_dir = file;
1762 file->flags |= FLAG_MISSING_DIR;
1763 }
1764 #ifdef SUPPORT_HARD_LINKS
1765 else if (F_IS_HLINKED(file))
1766 handle_skipped_hlink(file, itemizing, code, f_out);
1767 #endif
1768 if (INFO_GTE(SKIP, 1)) {
1769 rprintf(FINFO, "not creating new %s \"%s\"\n",
1770 is_dir ? "directory" : "file", fname);
1771 }
1772 return;
1773 }
1774
1775 if (statret == 0 && !(sx.st.st_mode & S_IWUSR)
1776 && !am_root && sx.st.st_uid == our_uid)
1777 del_opts |= DEL_NO_UID_WRITE;
1778
1779 if (statret == 0)
1780 stype = get_file_type(sx.st.st_mode);
1781 else
1782 stype = FT_UNSUPPORTED;
1783
1784 if (ignore_existing > 0 && statret == 0
1785 && (!is_dir || stype != FT_DIR)) {
1786 if (INFO_GTE(SKIP, 1) && is_dir >= 0) {
1787 const char *suf = "";
1788 if (INFO_GTE(SKIP, 2)) {
1789 if (ftype != stype)
1790 suf = " (type change)";
1791 else if (!quick_check_ok(ftype, fname, file, &sx.st))
1792 suf = always_checksum ? " (sum change)" : " (file change)";
1793 else if (!unchanged_attrs(fname, file, &sx))
1794 suf = " (attr change)";
1795 else
1796 suf = " (uptodate)";
1797 }
1798 rprintf(FINFO, "%s exists%s\n", fname, suf);
1799 }
1800 #ifdef SUPPORT_HARD_LINKS
1801 if (F_IS_HLINKED(file))
1802 handle_skipped_hlink(file, itemizing, code, f_out);
1803 #endif
1804 goto cleanup;
1805 }
1806
1807 fnamecmp = fname;
1808
1809 if (is_dir) {
1810 mode_t added_perms;
1811 if (!implied_dirs && file->flags & FLAG_IMPLIED_DIR)
1812 goto cleanup;
1813 if (am_root < 0) {
1814 /* For --fake-super, the dir must be useable by the copying
1815 * user, just like it would be for root. */
1816 added_perms = S_IRUSR|S_IWUSR|S_IXUSR;
1817 } else
1818 added_perms = 0;
1819 if (is_dir < 0) {
1820 if (!preserve_mtimes || omit_dir_times)
1821 goto cleanup;
1822 /* In inc_recurse mode we want to make sure any missing
1823 * directories get created while we're still processing
1824 * the parent dir (which allows us to touch the parent
1825 * dir's mtime right away). We will handle the dir in
1826 * full later (right before we handle its contents). */
1827 if (statret == 0
1828 && (stype == FT_DIR
1829 || delete_item(fname, sx.st.st_mode, del_opts | DEL_FOR_DIR) != 0))
1830 goto cleanup; /* Any errors get reported later. */
1831 if (gen_entry_mkdir(fname, file, (file->mode|added_perms) & 0700) == 0)
1832 file->flags |= FLAG_DIR_CREATED;
1833 goto cleanup;
1834 }
1835 /* The file to be received is a directory, so we need
1836 * to prepare appropriately. If there is already a
1837 * file of that name and it is *not* a directory, then
1838 * we need to delete it. If it doesn't exist, then
1839 * (perhaps recursively) create it. */
1840 if (statret == 0 && stype != FT_DIR) {
1841 if (delete_item(fname, sx.st.st_mode, del_opts | DEL_FOR_DIR) != 0)
1842 goto skipping_dir_contents;
1843 statret = -1;
1844 }
1845 if (dry_run && statret != 0) {
1846 if (!dry_missing_dir)
1847 dry_missing_dir = file;
1848 file->flags |= FLAG_MISSING_DIR;
1849 }
1850 init_stat_x(&real_sx);
1851 real_sx.st = sx.st;
1852 real_ret = statret;
1853 if (file->flags & FLAG_DIR_CREATED)
1854 statret = -1;
1855 if (!preserve_perms) { /* See comment in non-dir code below. */
1856 file->mode = dest_mode(file->mode, sx.st.st_mode, dflt_perms, statret == 0);
1857 }
1858 if (statret != 0 && basis_dir[0] != NULL) {
1859 int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &sx, itemizing, code);
1860 if (j == -2) {
1861 itemizing = 0;
1862 code = FNONE;
1863 statret = 1;
1864 } else if (j >= 0) {
1865 statret = 1;
1866 fnamecmp = fnamecmpbuf;
1867 }
1868 }
1869 if (itemizing && f_out != -1) {
1870 itemize(fnamecmp, file, ndx, statret, &sx,
1871 statret ? ITEM_LOCAL_CHANGE : 0, 0, NULL);
1872 }
1873 if (real_ret != 0 && gen_entry_mkdir(fname, file, file->mode|added_perms) < 0 && errno != EEXIST) {
1874 /* The parent may have just been created by make_path(), so
1875 * drop any cached (failed) dir fd before the retry. */
1876 reset_dir_fd_cache();
1877 if (!relative_paths || errno != ENOENT
1878 || make_path(fname, MKP_DROP_NAME | MKP_SKIP_SLASH) < 0
1879 || (gen_entry_mkdir(fname, file, file->mode|added_perms) < 0 && errno != EEXIST)) {
1880 rsyserr(FERROR_XFER, errno,
1881 "recv_generator: mkdir %s failed",
1882 full_fname(fname));
1883 skipping_dir_contents:
1884 rprintf(FERROR, "*** Skipping any contents from this failed directory ***\n");
1885 skip_dir = file;
1886 file->flags |= FLAG_MISSING_DIR;
1887 goto cleanup;
1888 }
1889 }
1890
1891 #ifdef SUPPORT_XATTRS
1892 if (preserve_xattrs && statret == 1)
1893 gen_entry_copy_xattrs(fnamecmpbuf, fname, file);
1894 #endif
1895 if (set_file_attrs(fname, file, real_ret ? NULL : &real_sx, NULL, 0)
1896 && INFO_GTE(NAME, 1) && code != FNONE && f_out != -1)
1897 rprintf(code, "%s/\n", fname);
1898
1899 /* We need to ensure that the dirs in the transfer have both
1900 * readable and writable permissions during the time we are
1901 * putting files within them. This is then restored to the
1902 * former permissions after the transfer is done. */
1903 #ifdef HAVE_CHMOD
1904 if (!am_root && (file->mode & S_IRWXU) != S_IRWXU && dir_tweaking) {
1905 mode_t mode = file->mode | S_IRWXU;
1906 if (gen_entry_chmod(fname, file, mode) < 0) {
1907 rsyserr(FERROR_XFER, errno,
1908 "failed to modify permissions on %s",
1909 full_fname(fname));
1910 }
1911 need_retouch_dir_perms = 1;
1912 }
1913 #endif
1914
1915 if (real_ret != 0 && one_file_system)
1916 real_sx.st.st_dev = filesystem_dev;
1917 if (inc_recurse) {
1918 if (one_file_system) {
1919 uint32 *devp = F_DIR_DEV_P(file);
1920 DEV_MAJOR(devp) = major(real_sx.st.st_dev);
1921 DEV_MINOR(devp) = minor(real_sx.st.st_dev);
1922 }
1923 }
1924 else if (delete_during && f_out != -1 && !phase
1925 && !(file->flags & FLAG_MISSING_DIR)) {
1926 if (file->flags & FLAG_CONTENT_DIR)
1927 delete_in_dir(fname, file, real_sx.st.st_dev);
1928 else
1929 change_local_filter_dir(fname, strlen(fname), F_DEPTH(file));
1930 }
1931 prior_dir_file = file;
1932 goto cleanup;
1933 }
1934
1935 /* If we're not preserving permissions, change the file-list's
1936 * mode based on the local permissions and some heuristics. */
1937 if (!preserve_perms) {
1938 int exists = statret == 0 && stype != FT_DIR;
1939 file->mode = dest_mode(file->mode, sx.st.st_mode, dflt_perms, exists);
1940 }
1941
1942 #ifdef SUPPORT_HARD_LINKS
1943 if (preserve_hard_links && F_HLINK_NOT_FIRST(file)
1944 && hard_link_check(file, ndx, fname, statret, &sx, itemizing, code))
1945 goto cleanup;
1946 #endif
1947
1948 if (preserve_links && ftype == FT_SYMLINK) {
1949 #ifdef SUPPORT_LINKS
1950 const char *sl = F_SYMLINK(file);
1951 if (safe_symlinks && unsafe_symlink(sl, fname)) {
1952 if (INFO_GTE(NAME, 1)) {
1953 if (solo_file) {
1954 /* fname contains the destination path, but we
1955 * want to report the source path. */
1956 fname = f_name(file, NULL);
1957 }
1958 rprintf(FINFO,
1959 "ignoring unsafe symlink \"%s\" -> \"%s\"\n",
1960 fname, sl);
1961 }
1962 goto cleanup;
1963 }
1964 if (statret == 0) {
1965 if (stype == FT_SYMLINK && quick_check_ok(stype, fname, file, &sx.st)) {
1966 /* The link is pointing to the right place. */
1967 set_file_attrs(fname, file, &sx, NULL, maybe_ATTRS_REPORT);
1968 if (itemizing)
1969 itemize(fname, file, ndx, 0, &sx, 0, 0, NULL);
1970 #ifdef SUPPORT_HARD_LINKS
1971 if (preserve_hard_links && F_IS_HLINKED(file))
1972 finish_hard_link(file, fname, ndx, &sx.st, itemizing, code, -1);
1973 #endif
1974 if (remove_source_files == 1)
1975 goto return_with_success;
1976 goto cleanup;
1977 }
1978 } else if (basis_dir[0] != NULL) {
1979 int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &sx, itemizing, code);
1980 if (j == -3) {
1981 /* The destination cannot hard-link this type. Land exactly
1982 * where a build without CAN_HARDLINK_SYMLINK lands: create
1983 * the entry, but leave the reporting to the itemisation
1984 * try_dests_non() already emitted. */
1985 itemizing = 0;
1986 code = FNONE;
1987 } else if (j == -2) {
1988 #ifndef CAN_HARDLINK_SYMLINK
1989 if (alt_dest_type == LINK_DEST) {
1990 /* Resort to --copy-dest behavior. */
1991 } else
1992 #endif
1993 if (alt_dest_type != COPY_DEST)
1994 goto cleanup;
1995 itemizing = 0;
1996 code = FNONE;
1997 } else if (j >= 0) {
1998 statret = 1;
1999 fnamecmp = fnamecmpbuf;
2000 }
2001 }
2002 if (atomic_create(file, fname, sl, NULL, MAKEDEV(0, 0), &sx, statret == 0 ? DEL_FOR_SYMLINK : 0)) {
2003 set_file_attrs(fname, file, NULL, NULL, 0);
2004 if (itemizing) {
2005 if (statret == 0 && stype != FT_SYMLINK)
2006 statret = -1;
2007 itemize(fnamecmp, file, ndx, statret, &sx,
2008 ITEM_LOCAL_CHANGE|ITEM_REPORT_CHANGE, 0, NULL);
2009 }
2010 if (code != FNONE && INFO_GTE(NAME, 1))
2011 rprintf(code, "%s -> %s\n", fname, sl);
2012 #ifdef SUPPORT_HARD_LINKS
2013 if (preserve_hard_links && F_IS_HLINKED(file))
2014 finish_hard_link(file, fname, ndx, NULL, itemizing, code, -1);
2015 #endif
2016 /* This does not check remove_source_files == 1
2017 * because this is one of the items that the old
2018 * --remove-sent-files option would remove. */
2019 if (remove_source_files)
2020 goto return_with_success;
2021 }
2022 #endif
2023 goto cleanup;
2024 }
2025
2026 /* --drop-D refuses to CREATE devices/specials without touching
2027 * preserve_devices/preserve_specials, which also frame the file list's
2028 * rdev fields -- clearing those on one end of a connection alone
2029 * desynchronises it. Falls through to the "skipping non-regular file"
2030 * path below, exactly as --no-D reaches it. */
2031 if (!drop_devices
2032 && ((am_root && preserve_devices && ftype == FT_DEVICE)
2033 || (preserve_specials && ftype == FT_SPECIAL))) {
2034 dev_t rdev;
2035 int del_for_flag;
2036 /* Whether the dest existed, captured before the type-mismatch
2037 * flip below clears statret -- so atomic_create() gets a delete
2038 * flag (and reads sx.st) only when sx.st was actually stat'd. */
2039 int dest_existed = (statret == 0);
2040 if (ftype == FT_DEVICE) {
2041 uint32 *devp = F_RDEV_P(file);
2042 rdev = MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp));
2043 del_for_flag = DEL_FOR_DEVICE;
2044 } else {
2045 rdev = 0;
2046 del_for_flag = DEL_FOR_SPECIAL;
2047 }
2048 if (statret == 0) {
2049 if (ftype != stype)
2050 statret = -1;
2051 else if (quick_check_ok(ftype, fname, file, &sx.st)) {
2052 /* The device or special file is identical. */
2053 set_file_attrs(fname, file, &sx, NULL, maybe_ATTRS_REPORT);
2054 if (itemizing)
2055 itemize(fname, file, ndx, 0, &sx, 0, 0, NULL);
2056 #ifdef SUPPORT_HARD_LINKS
2057 if (preserve_hard_links && F_IS_HLINKED(file))
2058 finish_hard_link(file, fname, ndx, &sx.st, itemizing, code, -1);
2059 #endif
2060 if (remove_source_files == 1)
2061 goto return_with_success;
2062 goto cleanup;
2063 }
2064 } else if (basis_dir[0] != NULL) {
2065 int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &sx, itemizing, code);
2066 if (j == -3) {
2067 /* As above: a destination that cannot hard-link this type
2068 * behaves like a build without CAN_HARDLINK_SPECIAL. */
2069 itemizing = 0;
2070 code = FNONE;
2071 } else if (j == -2) {
2072 #ifndef CAN_HARDLINK_SPECIAL
2073 if (alt_dest_type == LINK_DEST) {
2074 /* Resort to --copy-dest behavior. */
2075 } else
2076 #endif
2077 if (alt_dest_type != COPY_DEST)
2078 goto cleanup;
2079 itemizing = 0;
2080 code = FNONE;
2081 } else if (j >= 0) {
2082 statret = 1;
2083 fnamecmp = fnamecmpbuf;
2084 }
2085 }
2086 if (DEBUG_GTE(GENR, 1)) {
2087 rprintf(FINFO, "mknod(%s, 0%o, [%ld,%ld])\n",
2088 fname, (int)file->mode,
2089 (long)major(rdev), (long)minor(rdev));
2090 }
2091 if (atomic_create(file, fname, NULL, NULL, rdev, &sx, dest_existed ? del_for_flag : 0)) {
2092 set_file_attrs(fname, file, NULL, NULL, 0);
2093 if (itemizing) {
2094 itemize(fnamecmp, file, ndx, statret, &sx,
2095 ITEM_LOCAL_CHANGE|ITEM_REPORT_CHANGE, 0, NULL);
2096 }
2097 if (code != FNONE && INFO_GTE(NAME, 1))
2098 rprintf(code, "%s\n", fname);
2099 #ifdef SUPPORT_HARD_LINKS
2100 if (preserve_hard_links && F_IS_HLINKED(file))
2101 finish_hard_link(file, fname, ndx, NULL, itemizing, code, -1);
2102 #endif
2103 if (remove_source_files == 1)
2104 goto return_with_success;
2105 }
2106 goto cleanup;
2107 }
2108
2109 if (ftype != FT_REG) {
2110 if (INFO_GTE(NONREG, 1)) {
2111 if (solo_file)
2112 fname = f_name(file, NULL);
2113 rprintf(FINFO, "skipping non-regular file \"%s\"\n", fname);
2114 }
2115 goto cleanup;
2116 }
2117
2118 if (max_size >= 0 && F_LENGTH(file) > max_size) {
2119 if (INFO_GTE(SKIP, 1)) {
2120 if (solo_file)
2121 fname = f_name(file, NULL);
2122 rprintf(FINFO, "%s is over max-size\n", fname);
2123 }
2124 goto cleanup;
2125 }
2126 if (min_size >= 0 && F_LENGTH(file) < min_size) {
2127 if (INFO_GTE(SKIP, 1)) {
2128 if (solo_file)
2129 fname = f_name(file, NULL);
2130 rprintf(FINFO, "%s is under min-size\n", fname);
2131 }
2132 goto cleanup;
2133 }
2134
2135 if (update_only > 0 && statret == 0 && stype == ftype
2136 && file->modtime - sx.st.st_mtime < modify_window) {
2137 if (INFO_GTE(SKIP, 1))
2138 rprintf(FINFO, "%s is newer\n", fname);
2139 #ifdef SUPPORT_HARD_LINKS
2140 if (F_IS_HLINKED(file))
2141 handle_skipped_hlink(file, itemizing, code, f_out);
2142 #endif
2143 goto cleanup;
2144 }
2145
2146 fnamecmp_type = FNAMECMP_FNAME;
2147
2148 if (statret == 0 && !(stype == FT_REG || (write_devices && stype == FT_DEVICE))) {
2149 if (delete_item(fname, sx.st.st_mode, del_opts | DEL_FOR_FILE) != 0)
2150 goto cleanup;
2151 statret = -1;
2152 stat_errno = ENOENT;
2153 }
2154
2155 if (basis_dir[0] != NULL && (statret != 0 || alt_dest_type != COPY_DEST)) {
2156 int j = try_dests_reg(file, fname, ndx, fnamecmpbuf, &sx, statret == 0, itemizing, code);
2157 if (j == -2) {
2158 if (remove_source_files == 1)
2159 goto return_with_success;
2160 goto cleanup;
2161 }
2162 if (j >= 0) {
2163 fnamecmp = fnamecmpbuf;
2164 fnamecmp_type = j;
2165 statret = 0;
2166 }
2167 }
2168
2169 init_stat_x(&real_sx);
2170 real_sx.st = sx.st; /* Don't copy xattr/acl pointers, as they would free wrong. */
2171 real_ret = statret;
2172
2173 if (partial_dir && (partialptr = partial_dir_fname(fname)) != NULL
2174 && link_stat(partialptr, &partial_st, 0) == 0
2175 && S_ISREG(partial_st.st_mode)) {
2176 if (statret != 0)
2177 goto prepare_to_open;
2178 } else
2179 partialptr = NULL;
2180
2181 if (statret != 0 && fuzzy_basis) {
2182 if (need_fuzzy_dirlist) {
2183 const char *dn = file->dirname ? file->dirname : ".";
2184 int i;
2185 strlcpy(fnamecmpbuf, dn, sizeof fnamecmpbuf);
2186 for (i = 0; i < fuzzy_basis; i++) {
2187 if (i && pathjoin(fnamecmpbuf, MAXPATHLEN, basis_dir[i-1], dn) >= MAXPATHLEN)
2188 continue;
2189 fuzzy_dirlist[i] = get_dirlist(fnamecmpbuf, -1, GDL_IGNORE_FILTER_RULES | GDL_PERHAPS_DIR);
2190 if (fuzzy_dirlist[i] && fuzzy_dirlist[i]->used == 0) {
2191 flist_free(fuzzy_dirlist[i]);
2192 fuzzy_dirlist[i] = NULL;
2193 }
2194 }
2195 need_fuzzy_dirlist = 0;
2196 }
2197
2198 /* Sets fnamecmp_type to FNAMECMP_FUZZY or above. */
2199 fuzzy_file = find_fuzzy(file, fuzzy_dirlist, &fnamecmp_type);
2200 if (fuzzy_file) {
2201 f_name(fuzzy_file, fnamecmpbuf);
2202 if (DEBUG_GTE(FUZZY, 1)) {
2203 rprintf(FINFO, "fuzzy basis selected for %s: %s\n",
2204 fname, fnamecmpbuf);
2205 }
2206 sx.st.st_size = F_LENGTH(fuzzy_file);
2207 statret = 0;
2208 fnamecmp = fnamecmpbuf;
2209 }
2210 }
2211
2212 if (statret != 0) {
2213 #ifdef SUPPORT_HARD_LINKS
2214 if (preserve_hard_links && F_HLINK_NOT_LAST(file)) {
2215 cur_flist->in_progress++;
2216 goto cleanup;
2217 }
2218 #endif
2219 if (stat_errno == ENOENT)
2220 goto notify_others;
2221 rsyserr(FERROR_XFER, stat_errno, "recv_generator: failed to stat %s",
2222 full_fname(fname));
2223 goto cleanup;
2224 }
2225
2226 if (write_devices && IS_DEVICE(sx.st.st_mode) && sx.st.st_size == 0) {
2227 /* This early open into fd skips the regular open below. */
2228 if ((fd = do_open_nofollow(fnamecmp, O_RDONLY)) >= 0)
2229 real_sx.st.st_size = sx.st.st_size = get_device_size(fd, fnamecmp);
2230 }
2231
2232 if (fnamecmp_type <= FNAMECMP_BASIS_DIR_HIGH)
2233 ;
2234 else if (fnamecmp_type >= FNAMECMP_FUZZY)
2235 ;
2236 else if (quick_check_ok(FT_REG, fnamecmp, file, &sx.st)) {
2237 if (partialptr) {
2238 /* The --partial-dir basis is an operator/peer path: unlink it
2239 * through the exclude-aware ownership walk so a symlinked
2240 * partial-dir can't delete a file in an excluded subtree. */
2241 operator_path_resolve = 1;
2242 do_unlink_at(partialptr);
2243 operator_path_resolve = 0;
2244 handle_partial_dir(partialptr, PDIR_DELETE);
2245 }
2246 set_file_attrs(fname, file, &sx, NULL, maybe_ATTRS_REPORT | maybe_ATTRS_ACCURATE_TIME);
2247 if (itemizing)
2248 itemize(fnamecmp, file, ndx, statret, &sx, 0, 0, NULL);
2249 #ifdef SUPPORT_HARD_LINKS
2250 if (preserve_hard_links && F_IS_HLINKED(file))
2251 finish_hard_link(file, fname, ndx, &sx.st, itemizing, code, -1);
2252 #endif
2253 if (remove_source_files != 1)
2254 goto cleanup;
2255 return_with_success:
2256 if (!dry_run)
2257 send_msg_success(fname, ndx);
2258 goto cleanup;
2259 }
2260
2261 if (append_mode > 0 && sx.st.st_size >= F_LENGTH(file)) {
2262 #ifdef SUPPORT_HARD_LINKS
2263 if (F_IS_HLINKED(file))
2264 handle_skipped_hlink(file, itemizing, code, f_out);
2265 #endif
2266 goto cleanup;
2267 }
2268
2269 prepare_to_open:
2270 if (partialptr) {
2271 sx.st = partial_st;
2272 fnamecmp = partialptr;
2273 fnamecmp_type = FNAMECMP_PARTIAL_DIR;
2274 statret = 0;
2275 }
2276
2277 if (!do_xfers)
2278 goto notify_others;
2279
2280 if (read_batch || whole_file) {
2281 if (inplace && make_backups > 0 && fnamecmp_type == FNAMECMP_FNAME) {
2282 /* The --backup-dir (backupptr) is an operator path; this in-place
2283 * backup bypasses make_backup(), so set operator_path_resolve here
2284 * too -- get_backup_name() (make_path) and copy_file() then resolve
2285 * it with the ownership walk instead of following any symlink. */
2286 operator_path_resolve = 1;
2287 if (!(backupptr = get_backup_name(fname))) {
2288 operator_path_resolve = 0;
2289 goto cleanup;
2290 }
2291 if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) {
2292 operator_path_resolve = 0;
2293 goto pretend_missing;
2294 }
2295 if (copy_file(fname, backupptr, -1, back_file->mode) < 0) {
2296 operator_path_resolve = 0;
2297 unmake_file(back_file);
2298 back_file = NULL;
2299 goto cleanup;
2300 }
2301 operator_path_resolve = 0;
2302 }
2303 goto notify_others;
2304 }
2305
2306 if (fuzzy_dirlist[0]) {
2307 int j = flist_find(fuzzy_dirlist[0], file);
2308 if (j >= 0) /* don't use changing file as future fuzzy basis */
2309 fuzzy_dirlist[0]->files[j]->flags |= FLAG_FILE_SENT;
2310 }
2311
2312 /* open the file */
2313 if (fd < 0 && (fd = do_open_checklinks(fnamecmp)) < 0) {
2314 rsyserr(FERROR, errno, "failed to open %s, continuing",
2315 full_fname(fnamecmp));
2316 pretend_missing:
2317 /* pretend the file didn't exist */
2318 #ifdef SUPPORT_HARD_LINKS
2319 if (preserve_hard_links && F_HLINK_NOT_LAST(file)) {
2320 cur_flist->in_progress++;
2321 goto cleanup;
2322 }
2323 #endif
2324 statret = real_ret = -1;
2325 goto notify_others;
2326 }
2327
2328 if (inplace && make_backups > 0 && fnamecmp_type == FNAMECMP_FNAME) {
2329 /* Operator --backup-dir, bypassing make_backup(): resolve get_backup_name()
2330 * (make_path), the unlink and the create with the ownership walk. */
2331 operator_path_resolve = 1;
2332 if (!(backupptr = get_backup_name(fname))) {
2333 operator_path_resolve = 0;
2334 goto cleanup;
2335 }
2336 if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) {
2337 operator_path_resolve = 0;
2338 goto pretend_missing;
2339 }
2340 if (robust_unlink(backupptr) && errno != ENOENT) {
2341 operator_path_resolve = 0;
2342 rsyserr(FERROR_XFER, errno, "unlink %s",
2343 full_fname(backupptr));
2344 unmake_file(back_file);
2345 back_file = NULL;
2346 goto cleanup;
2347 }
2348 if ((f_copy = do_open_at(backupptr, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600)) < 0) {
2349 operator_path_resolve = 0;
2350 rsyserr(FERROR_XFER, errno, "open %s", full_fname(backupptr));
2351 unmake_file(back_file);
2352 back_file = NULL;
2353 goto cleanup;
2354 }
2355 operator_path_resolve = 0;
2356 fnamecmp_type = FNAMECMP_BACKUP;
2357 }
2358
2359 if (DEBUG_GTE(DELTASUM, 3)) {
2360 rprintf(FINFO, "gen mapped %s of size %s\n",
2361 fnamecmp, big_num(sx.st.st_size));
2362 }
2363
2364 if (DEBUG_GTE(DELTASUM, 2))
2365 rprintf(FINFO, "generating and sending sums for %d\n", ndx);
2366
2367 notify_others:
2368 if (remove_source_files && !delay_updates && !phase && !dry_run)
2369 increment_active_files(ndx, itemizing, code);
2370 if (inc_recurse && (!dry_run || write_batch < 0))
2371 cur_flist->in_progress++;
2372 #ifdef SUPPORT_HARD_LINKS
2373 if (preserve_hard_links && F_IS_HLINKED(file))
2374 file->flags |= FLAG_FILE_SENT;
2375 #endif
2376 write_ndx(f_out, ndx);
2377 if (itemizing) {
2378 int iflags = ITEM_TRANSFER;
2379 if (always_checksum > 0)
2380 iflags |= ITEM_REPORT_CHANGE;
2381 if (fnamecmp_type != FNAMECMP_FNAME)
2382 iflags |= ITEM_BASIS_TYPE_FOLLOWS;
2383 if (fnamecmp_type >= FNAMECMP_FUZZY)
2384 iflags |= ITEM_XNAME_FOLLOWS;
2385 itemize(fnamecmp, file, -1, real_ret, &real_sx, iflags, fnamecmp_type,
2386 fuzzy_file ? fuzzy_file->basename : NULL);
2387 free_stat_x(&real_sx);
2388 }
2389
2390 if (!do_xfers) {
2391 #ifdef SUPPORT_HARD_LINKS
2392 if (preserve_hard_links && F_IS_HLINKED(file))
2393 finish_hard_link(file, fname, ndx, &sx.st, itemizing, code, -1);
2394 #endif
2395 goto cleanup;
2396 }
2397 if (read_batch)
2398 goto cleanup;
2399
2400 if (statret != 0 || whole_file)
2401 write_sum_head(f_out, NULL);
2402 else if (sx.st.st_size <= 0) {
2403 write_sum_head(f_out, NULL);
2404 } else {
2405 if (generate_and_send_sums(fd, sx.st.st_size, f_out, f_copy) < 0) {
2406 rprintf(FWARNING,
2407 "WARNING: file is too large for checksum sending: %s\n",
2408 fnamecmp);
2409 write_sum_head(f_out, NULL);
2410 }
2411 }
2412
2413 cleanup:
2414 if (fd >= 0)
2415 close(fd);
2416 if (back_file) {
2417 int save_preserve_xattrs = preserve_xattrs;
2418 #ifdef SUPPORT_XATTRS
2419 /* The delta-backup path wrote backupptr via the held f_copy, so
2420 * copy its xattrs through that fd here. The whole-file/inplace
2421 * path (f_copy < 0) backed it up via copy_file(), which already
2422 * copied the xattrs through its own held fd -- don't repeat it
2423 * with a path-based set a parent-symlink race could redirect. */
2424 if (preserve_xattrs && f_copy >= 0) {
2425 /* Read fname's xattrs through a confined fd so the copy onto the
2426 * held backup fd can't be fed an out-of-module source by a raced
2427 * parent symlink; a hardened race skips rather than path-reads. */
2428 int bfd = backup_source_fd(fname);
2429 if (!backup_metadata_hardened() || bfd >= 0)
2430 copy_xattrs(fname, bfd, backupptr, f_copy);
2431 if (bfd >= 0)
2432 close(bfd);
2433 preserve_xattrs = 0;
2434 }
2435 #endif
2436 if (f_copy >= 0)
2437 close(f_copy);
2438 /* backupptr's data/xattrs were written safely (confined create under
2439 * operator_path_resolve, held-fd xattr copy above). This metadata set
2440 * re-resolves backupptr by path and is NOT wrapped in operator mode:
2441 * set_file_attrs() also drives the path-based xattr set whose held-fd
2442 * race-fix operator mode would defeat (cf. the copy-dest note in
2443 * try_dests_reg). The static --backup-dir escape is already closed; a
2444 * parent-symlink flipped in after the confined create races only these
2445 * chmod/chown/times -- a documented residual. */
2446 set_file_attrs(backupptr, back_file, NULL, NULL, 0);
2447 preserve_xattrs = save_preserve_xattrs;
2448 if (INFO_GTE(BACKUP, 1)) {
2449 rprintf(FINFO, "backed up %s to %s\n",
2450 fname, backupptr);
2451 }
2452 unmake_file(back_file);
2453 }
2454
2455 free_stat_x(&sx);
2456 free_stat_x(&real_sx);
2457 }
2458
2459 /* If we are replacing an existing hard link, symlink, device, or special file,
2460 * create a temp-name item and rename it into place. A symlimk specifies slnk,
2461 * a hard link specifies hlnk, otherwise we create a device based on rdev.
2462 * Specify 0 for the del_for_flag if there is not a file to replace. This
2463 * returns 1 on success and 0 on failure. */
2464 int atomic_create(struct file_struct *file, char *fname, const char *slnk, const char *hlnk,
2465 dev_t rdev, stat_x *sxp, int del_for_flag)
2466 {
2467 char tmpname[MAXPATHLEN];
2468 const char *create_name;
2469 int skip_atomic, dir_in_the_way = del_for_flag && S_ISDIR(sxp->st.st_mode);
2470
2471 if (!del_for_flag || dir_in_the_way || tmpdir || !get_tmpname(tmpname, fname, True))
2472 skip_atomic = 1;
2473 else
2474 skip_atomic = 0;
2475
2476 if (del_for_flag) {
2477 if (make_backups > 0 && !dir_in_the_way) {
2478 if (!make_backup(fname, skip_atomic))
2479 return 0;
2480 } else if (skip_atomic) {
2481 int del_opts = delete_mode || force_delete ? DEL_RECURSE : 0;
2482 if (delete_item(fname, sxp->st.st_mode, del_opts | del_for_flag) != 0)
2483 return 0;
2484 }
2485 }
2486
2487 create_name = skip_atomic ? fname : tmpname;
2488
2489 if (slnk) {
2490 #ifdef SUPPORT_LINKS
2491 if (gen_entry_symlink(slnk, create_name, file) < 0) {
2492 rsyserr(FERROR_XFER, errno, "symlink %s -> \"%s\" failed",
2493 full_fname(create_name), slnk);
2494 return 0;
2495 }
2496 #else
2497 return 0;
2498 #endif
2499 } else if (hlnk) {
2500 #ifdef SUPPORT_HARD_LINKS
2501 if (!hard_link_one(file, create_name, hlnk, 0))
2502 return 0;
2503 #else
2504 return 0;
2505 #endif
2506 } else {
2507 if (gen_entry_mknod(create_name, file, file->mode, rdev) < 0) {
2508 int e = errno;
2509 /* A nested socket can't be created race-safely where there is no
2510 * bindat() (the BSDs, macOS, Solaris): syscall.c returns EOPNOTSUPP
2511 * rather than re-resolving an unsafe parent. A socket inode is only
2512 * a placeholder -- a live socket isn't usefully transferred -- so
2513 * skip it with a warning instead of failing the whole transfer
2514 * (got_xfer_error -> exit 23). Top-level sockets still create via
2515 * the path-based bind() fallback. */
2516 if (S_ISSOCK(file->mode) && (e == EOPNOTSUPP || e == ENOSYS)) {
2517 rprintf(FWARNING, "skipping socket (creation unsupported here): %s\n",
2518 full_fname(create_name));
2519 return 0;
2520 }
2521 rsyserr(FERROR_XFER, e, "mknod %s failed",
2522 full_fname(create_name));
2523 return 0;
2524 }
2525 }
2526
2527 if (!skip_atomic) {
2528 if (gen_entry_rename(tmpname, fname, file) < 0) {
2529 char *full_tmpname = strdup(full_fname(tmpname));
2530 if (full_tmpname == NULL)
2531 out_of_memory("atomic_create");
2532 rsyserr(FERROR_XFER, errno, "rename %s -> \"%s\" failed",
2533 full_tmpname, full_fname(fname));
2534 free(full_tmpname);
2535 gen_entry_unlink(tmpname, file);
2536 return 0;
2537 }
2538 }
2539
2540 return 1;
2541 }
2542
2543 #ifdef SUPPORT_HARD_LINKS
2544 static void handle_skipped_hlink(struct file_struct *file, int itemizing,
2545 enum logcode code, int f_out)
2546 {
2547 char fbuf[MAXPATHLEN];
2548 int new_last_ndx;
2549 struct file_list *save_flist = cur_flist;
2550
2551 /* If we skip the last item in a chain of links and there was a
2552 * prior non-skipped hard-link waiting to finish, finish it now. */
2553 if ((new_last_ndx = skip_hard_link(file, &cur_flist)) < 0)
2554 return;
2555
2556 file = cur_flist->files[new_last_ndx - cur_flist->ndx_start];
2557 cur_flist->in_progress--; /* undo prior increment */
2558 f_name(file, fbuf);
2559 recv_generator(fbuf, file, new_last_ndx, itemizing, code, f_out);
2560
2561 cur_flist = save_flist;
2562 }
2563 #endif
2564
2565 static void touch_up_dirs(struct file_list *flist, int ndx)
2566 {
2567 static int counter = 0;
2568 struct file_struct *file;
2569 char *fname;
2570 BOOL fix_dir_perms;
2571 int i, start, end;
2572
2573 if (ndx < 0) {
2574 start = 0;
2575 end = flist->used - 1;
2576 } else
2577 start = end = ndx;
2578
2579 /* Fix any directory permissions that were modified during the
2580 * transfer and/or re-set any tweaked modified-time values. */
2581 for (i = start; i <= end; i++, counter++) {
2582 file = flist->files[i];
2583 if (!F_IS_ACTIVE(file))
2584 continue;
2585 if (!S_ISDIR(file->mode)
2586 || (!implied_dirs && file->flags & FLAG_IMPLIED_DIR))
2587 continue;
2588 if (DEBUG_GTE(TIME, 2)) {
2589 fname = f_name(file, NULL);
2590 rprintf(FINFO, "touch_up_dirs: %s (%d)\n",
2591 NS(fname), i);
2592 }
2593 /* Be sure not to retouch permissions with --fake-super. */
2594 fix_dir_perms = !am_root && !(file->mode & S_IWUSR);
2595 if (file->flags & FLAG_MISSING_DIR || !(need_retouch_dir_times || fix_dir_perms))
2596 continue;
2597 fname = f_name(file, NULL);
2598 if (fix_dir_perms)
2599 gen_entry_chmod(fname, file, file->mode);
2600 if (need_retouch_dir_times) {
2601 STRUCT_STAT st;
2602 if (gen_entry_stat(fname, file, &st, 0) == 0 && mtime_differs(&st, file)) {
2603 st.st_mtime = file->modtime;
2604 #ifdef ST_MTIME_NSEC
2605 st.ST_MTIME_NSEC = F_MOD_NSEC_or_0(file);
2606 #endif
2607 gen_entry_set_times(fname, file, &st);
2608 }
2609 }
2610 if (counter >= loopchk_limit) {
2611 if (allowed_lull)
2612 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
2613 else
2614 maybe_flush_socket(0);
2615 counter = 0;
2616 }
2617 }
2618 }
2619
2620 void check_for_finished_files(int itemizing, enum logcode code, int check_redo)
2621 {
2622 struct file_struct *file;
2623 struct file_list *flist;
2624 char fbuf[MAXPATHLEN];
2625 int ndx;
2626
2627 while (1) {
2628 #ifdef SUPPORT_HARD_LINKS
2629 if (preserve_hard_links && (ndx = get_hlink_num()) != -1) {
2630 int send_failed = (ndx == -2);
2631 if (send_failed)
2632 ndx = get_hlink_num();
2633 flist = flist_for_ndx(ndx, "check_for_finished_files.1");
2634 if (ndx < flist->ndx_start)
2635 exit_cleanup(RERR_PROTOCOL);
2636 file = flist->files[ndx - flist->ndx_start];
2637 assert(file->flags & FLAG_HLINKED);
2638 if (send_failed)
2639 handle_skipped_hlink(file, itemizing, code, sock_f_out);
2640 else
2641 finish_hard_link(file, f_name(file, fbuf), ndx, NULL, itemizing, code, -1);
2642 flist->in_progress--;
2643 continue;
2644 }
2645 #endif
2646
2647 if (check_redo && (ndx = get_redo_num()) != -1) {
2648 OFF_T save_max_size = max_size;
2649 OFF_T save_min_size = min_size;
2650 csum_length = SUM_LENGTH;
2651 max_size = -1;
2652 min_size = -1;
2653 ignore_existing = -ignore_existing;
2654 ignore_non_existing = -ignore_non_existing;
2655 update_only = -update_only;
2656 always_checksum = -always_checksum;
2657 size_only = -size_only;
2658 append_mode = -append_mode;
2659 make_backups = -make_backups; /* avoid dup backup w/inplace */
2660 ignore_times++;
2661
2662 flist = cur_flist;
2663 cur_flist = flist_for_ndx(ndx, "check_for_finished_files.2");
2664 if (ndx < cur_flist->ndx_start)
2665 exit_cleanup(RERR_PROTOCOL);
2666
2667 file = cur_flist->files[ndx - cur_flist->ndx_start];
2668 if (solo_file)
2669 strlcpy(fbuf, solo_file, sizeof fbuf);
2670 else
2671 f_name(file, fbuf);
2672 recv_generator(fbuf, file, ndx, itemizing, code, sock_f_out);
2673 cur_flist->to_redo--;
2674
2675 cur_flist = flist;
2676
2677 csum_length = SHORT_SUM_LENGTH;
2678 max_size = save_max_size;
2679 min_size = save_min_size;
2680 ignore_existing = -ignore_existing;
2681 ignore_non_existing = -ignore_non_existing;
2682 update_only = -update_only;
2683 always_checksum = -always_checksum;
2684 size_only = -size_only;
2685 append_mode = -append_mode;
2686 make_backups = -make_backups;
2687 ignore_times--;
2688 continue;
2689 }
2690
2691 if (cur_flist == first_flist)
2692 break;
2693
2694 /* We only get here if inc_recurse is enabled. */
2695 if (first_flist->in_progress || first_flist->to_redo)
2696 break;
2697
2698 write_ndx(sock_f_out, NDX_DONE);
2699 if (!read_batch && !flist_eof) {
2700 int old_total = 0;
2701 for (flist = first_flist; flist != cur_flist; flist = flist->next)
2702 old_total += flist->used;
2703 maybe_flush_socket(!flist_eof && file_total - old_total < MIN_FILECNT_LOOKAHEAD/2);
2704 }
2705
2706 if (delete_during == 2 || !dir_tweaking) {
2707 /* Skip directory touch-up. */
2708 } else if (first_flist->parent_ndx >= 0
2709 && first_flist->parent_ndx < dir_flist->used)
2710 touch_up_dirs(dir_flist, first_flist->parent_ndx);
2711
2712 flist_free(first_flist); /* updates first_flist */
2713 }
2714 }
2715
2716 void generate_files(int f_out, const char *local_name)
2717 {
2718 int i, ndx, next_loopchk = 0;
2719 char fbuf[MAXPATHLEN];
2720 int itemizing;
2721 enum logcode code;
2722 int save_info_flist = info_levels[INFO_FLIST];
2723 int save_info_progress = info_levels[INFO_PROGRESS];
2724
2725 if (protocol_version >= 29) {
2726 itemizing = 1;
2727 maybe_ATTRS_REPORT = stdout_format_has_i ? 0 : ATTRS_REPORT;
2728 code = logfile_format_has_i ? FNONE : FLOG;
2729 } else if (am_daemon) {
2730 itemizing = logfile_format_has_i && do_xfers;
2731 maybe_ATTRS_REPORT = ATTRS_REPORT;
2732 code = itemizing || !do_xfers ? FCLIENT : FINFO;
2733 } else if (!am_server) {
2734 itemizing = stdout_format_has_i;
2735 maybe_ATTRS_REPORT = stdout_format_has_i ? 0 : ATTRS_REPORT;
2736 code = itemizing ? FNONE : FINFO;
2737 } else {
2738 itemizing = 0;
2739 maybe_ATTRS_REPORT = ATTRS_REPORT;
2740 code = FINFO;
2741 }
2742 solo_file = local_name;
2743 dir_tweaking = !(list_only || solo_file || dry_run);
2744 need_retouch_dir_times = preserve_mtimes && !omit_dir_times;
2745 loopchk_limit = allowed_lull ? allowed_lull * 5 : 200;
2746 symlink_timeset_failed_flags = ITEM_REPORT_TIME
2747 | (protocol_version >= 30 || !am_server ? ITEM_REPORT_TIMEFAIL : 0);
2748 implied_dirs_are_missing = relative_paths && !implied_dirs && protocol_version < 30;
2749
2750 if (DEBUG_GTE(GENR, 1))
2751 rprintf(FINFO, "generator starting pid=%d\n", (int)getpid());
2752
2753 if (delete_before && !solo_file && cur_flist->used > 0)
2754 do_delete_pass();
2755 if (delete_during == 2) {
2756 deldelay_size = BIGPATHBUFLEN * 4;
2757 deldelay_buf = new_array(char, deldelay_size);
2758 }
2759 info_levels[INFO_FLIST] = info_levels[INFO_PROGRESS] = 0;
2760
2761 if (append_mode > 0 || whole_file < 0)
2762 whole_file = 0;
2763 if (DEBUG_GTE(FLIST, 1)) {
2764 rprintf(FINFO, "delta-transmission %s\n",
2765 whole_file
2766 ? "disabled for local transfer or --whole-file"
2767 : "enabled");
2768 }
2769
2770 dflt_perms = (ACCESSPERMS & ~orig_umask);
2771
2772 do {
2773 #ifdef SUPPORT_HARD_LINKS
2774 if (preserve_hard_links && inc_recurse) {
2775 while (!flist_eof && file_total < MIN_FILECNT_LOOKAHEAD/2)
2776 wait_for_receiver();
2777 }
2778 #endif
2779
2780 if (inc_recurse && cur_flist->parent_ndx >= 0
2781 && cur_flist->parent_ndx < dir_flist->used) {
2782 struct file_struct *fp = dir_flist->files[cur_flist->parent_ndx];
2783 if (solo_file)
2784 strlcpy(fbuf, solo_file, sizeof fbuf);
2785 else
2786 f_name(fp, fbuf);
2787 ndx = cur_flist->ndx_start - 1;
2788 recv_generator(fbuf, fp, ndx, itemizing, code, f_out);
2789 if (delete_during && dry_run < 2 && !list_only
2790 && !(fp->flags & FLAG_MISSING_DIR)) {
2791 if (fp->flags & FLAG_CONTENT_DIR) {
2792 dev_t dirdev;
2793 if (one_file_system) {
2794 uint32 *devp = F_DIR_DEV_P(fp);
2795 dirdev = MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp));
2796 } else
2797 dirdev = MAKEDEV(0, 0);
2798 delete_in_dir(fbuf, fp, dirdev);
2799 } else
2800 change_local_filter_dir(fbuf, strlen(fbuf), F_DEPTH(fp));
2801 }
2802 }
2803 for (i = cur_flist->low; i <= cur_flist->high; i++) {
2804 struct file_struct *file = cur_flist->sorted[i];
2805
2806 if (!F_IS_ACTIVE(file))
2807 continue;
2808
2809 if (unsort_ndx)
2810 ndx = F_NDX(file);
2811 else
2812 ndx = i + cur_flist->ndx_start;
2813
2814 if (solo_file)
2815 strlcpy(fbuf, solo_file, sizeof fbuf);
2816 else
2817 f_name(file, fbuf);
2818 recv_generator(fbuf, file, ndx, itemizing, code, f_out);
2819
2820 check_for_finished_files(itemizing, code, 0);
2821
2822 if (i + cur_flist->ndx_start >= next_loopchk) {
2823 if (allowed_lull)
2824 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
2825 else
2826 maybe_flush_socket(0);
2827 next_loopchk += loopchk_limit;
2828 }
2829 }
2830
2831 if (!inc_recurse) {
2832 write_ndx(f_out, NDX_DONE);
2833 break;
2834 }
2835
2836 while (1) {
2837 check_for_finished_files(itemizing, code, 1);
2838 if (cur_flist->next || flist_eof)
2839 break;
2840 wait_for_receiver();
2841 }
2842 } while ((cur_flist = cur_flist->next) != NULL);
2843
2844 if (delete_during)
2845 delete_in_dir(NULL, NULL, dev_zero);
2846 phase++;
2847 if (DEBUG_GTE(GENR, 1))
2848 rprintf(FINFO, "generate_files phase=%d\n", phase);
2849
2850 while (1) {
2851 check_for_finished_files(itemizing, code, 1);
2852 if (msgdone_cnt)
2853 break;
2854 wait_for_receiver();
2855 }
2856
2857 phase++;
2858 if (DEBUG_GTE(GENR, 1))
2859 rprintf(FINFO, "generate_files phase=%d\n", phase);
2860
2861 write_ndx(f_out, NDX_DONE);
2862
2863 /* Reduce round-trip lag-time for a useless delay-updates phase. */
2864 if (protocol_version >= 29 && EARLY_DELAY_DONE_MSG())
2865 write_ndx(f_out, NDX_DONE);
2866
2867 if (protocol_version >= 31 && EARLY_DELETE_DONE_MSG()) {
2868 if (delete_mode || force_delete || read_batch)
2869 write_del_stats(f_out);
2870 if (EARLY_DELAY_DONE_MSG()) /* Can't send this before delay */
2871 write_ndx(f_out, NDX_DONE);
2872 }
2873
2874 /* Read MSG_DONE for the redo phase (and any prior messages). */
2875 while (1) {
2876 check_for_finished_files(itemizing, code, 0);
2877 if (msgdone_cnt > 1)
2878 break;
2879 wait_for_receiver();
2880 }
2881
2882 if (protocol_version >= 29) {
2883 phase++;
2884 if (DEBUG_GTE(GENR, 1))
2885 rprintf(FINFO, "generate_files phase=%d\n", phase);
2886 if (!EARLY_DELAY_DONE_MSG()) {
2887 write_ndx(f_out, NDX_DONE);
2888 if (protocol_version >= 31 && EARLY_DELETE_DONE_MSG())
2889 write_ndx(f_out, NDX_DONE);
2890 }
2891 /* Read MSG_DONE for delay-updates phase & prior messages. */
2892 while (msgdone_cnt == 2)
2893 wait_for_receiver();
2894 }
2895
2896 info_levels[INFO_FLIST] = save_info_flist;
2897 info_levels[INFO_PROGRESS] = save_info_progress;
2898
2899 if (delete_during == 2)
2900 do_delayed_deletions(fbuf);
2901 if (delete_after && !solo_file && file_total > 0)
2902 do_delete_pass();
2903
2904 if (max_delete >= 0 && skipped_deletes) {
2905 rprintf(FWARNING,
2906 "Deletions stopped due to --max-delete limit (%d skipped)\n",
2907 skipped_deletes);
2908 io_error |= IOERR_DEL_LIMIT;
2909 }
2910
2911 if (protocol_version >= 31) {
2912 if (!EARLY_DELETE_DONE_MSG()) {
2913 if (delete_mode || force_delete || read_batch)
2914 write_del_stats(f_out);
2915 write_ndx(f_out, NDX_DONE);
2916 }
2917
2918 /* Read MSG_DONE for late-delete phase & prior messages. */
2919 while (msgdone_cnt == 3)
2920 wait_for_receiver();
2921 }
2922
2923 if ((need_retouch_dir_perms || need_retouch_dir_times)
2924 && dir_tweaking && (!inc_recurse || delete_during == 2))
2925 touch_up_dirs(dir_flist, -1);
2926
2927 if (DEBUG_GTE(GENR, 1))
2928 rprintf(FINFO, "generate_files finished\n");
2929 }