Debian Codegraph @

flist.c

raw symbols SCIP
1 /*
2 * Generate and receive file lists.
3 *
4 * Copyright (C) 1996 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2001, 2002 Martin Pool <[email protected]>
7 * Copyright (C) 2002-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 "ifuncs.h"
25 #include "rounding.h"
26 #include "inums.h"
27 #include "io.h"
28
29 extern int am_root;
30 extern int am_server;
31 extern int am_daemon;
32 extern int am_chrooted;
33 extern char *module_dir;
34 extern unsigned int module_dirlen;
35 extern int module_dirfd;
36 extern unsigned int curr_dir_len;
37 extern int am_sender;
38 extern int am_generator;
39 extern int inc_recurse;
40 extern int always_checksum;
41 extern int module_id;
42 extern int ignore_errors;
43 extern int numeric_ids;
44 extern int quiet;
45 extern int recurse;
46 extern int use_qsort;
47 extern int xfer_dirs;
48 extern int filesfrom_fd;
49 extern int one_file_system;
50 extern int copy_devices;
51 extern int copy_dirlinks;
52 extern int preserve_uid;
53 extern int preserve_gid;
54 extern int preserve_acls;
55 extern int preserve_xattrs;
56 extern int preserve_links;
57 extern int preserve_hard_links;
58 extern int preserve_devices;
59 extern int preserve_specials;
60 extern int delete_during;
61 extern int missing_args;
62 extern int eol_nulls;
63 extern int atimes_ndx;
64 extern int crtimes_ndx;
65 extern int relative_paths;
66 extern int implied_dirs;
67 extern int ignore_perishable;
68 extern int non_perishable_cnt;
69 extern int prune_empty_dirs;
70 extern int copy_links;
71 extern int copy_unsafe_links;
72 extern int insecure_links;
73 extern int protocol_version;
74 extern int sanitize_paths;
75 extern int munge_symlinks;
76 extern int use_safe_inc_flist;
77 extern int need_unsorted_flist;
78 extern int sender_symlink_iconv;
79 extern int output_needs_newline;
80 extern int sender_keeps_checksum;
81 extern int trust_sender_filter;
82 extern int unsort_ndx;
83 extern uid_t our_uid;
84 extern struct stats stats;
85 extern char *filesfrom_host;
86 extern char *usermap, *groupmap;
87
88 extern struct name_num_item *file_sum_nni;
89
90 extern char curr_dir[MAXPATHLEN];
91
92 extern struct chmod_mode_struct *chmod_modes;
93
94 extern filter_rule_list filter_list, implied_filter_list, daemon_filter_list;
95
96 #ifdef ICONV_OPTION
97 extern int filesfrom_convert;
98 extern iconv_t ic_send, ic_recv;
99 #endif
100
101 #define PTR_SIZE (sizeof (struct file_struct *))
102
103 int io_error;
104 int flist_csum_len;
105 dev_t filesystem_dev; /* used to implement -x */
106
107 struct file_list *cur_flist, *first_flist, *dir_flist;
108 int send_dir_ndx = -1, send_dir_depth = -1;
109 int flist_cnt = 0; /* how many (non-tmp) file list objects exist */
110 int file_total = 0; /* total of all active items over all file-lists */
111 int file_old_total = 0; /* total of active items that will soon be gone */
112 int flist_eof = 0; /* all the file-lists are now known */
113 int xfer_flags_as_varint = 0;
114
115 #define NORMAL_NAME 0
116 #define SLASH_ENDING_NAME 1
117 #define DOTDIR_NAME 2
118 #define MISSING_NAME 3
119
120 /* Starting from protocol version 26, we always use 64-bit ino_t and dev_t
121 * internally, even if this platform does not allow files to have 64-bit inums.
122 * The only exception is if we're on a platform with no 64-bit type at all.
123 *
124 * Because we use read_longint() to get these off the wire, if you transfer
125 * devices or (for protocols < 30) hardlinks with dev or inum > 2**32 to a
126 * machine with no 64-bit types then you will get an overflow error.
127 *
128 * Note that if you transfer devices from a 64-bit-devt machine (say, Solaris)
129 * to a 32-bit-devt machine (say, Linux-2.2/x86) then the device numbers will
130 * be truncated. But it's a kind of silly thing to do anyhow. */
131
132 /* The tmp_* vars are used as a cache area by make_file() to store data
133 * that the sender doesn't need to remember in its file list. The data
134 * will survive just long enough to be used by send_file_entry(). */
135 static dev_t tmp_rdev;
136 #ifdef SUPPORT_HARD_LINKS
137 static int64 tmp_dev = -1, tmp_ino;
138 #endif
139 static char tmp_sum[MAX_DIGEST_LEN];
140
141 #ifdef ST_MTIME_NSEC
142 /* Return st_mtim nsec if it is in the wire-valid range, else 0. */
143 static inline uint32 wire_mtime_nsec_from_stat(const STRUCT_STAT *stp)
144 {
145 unsigned long nsec = (unsigned long)stp->ST_MTIME_NSEC;
146
147 if (nsec > MAX_WIRE_NSEC)
148 return 0;
149 return (uint32)nsec;
150 }
151 #endif
152
153 static char empty_sum[MAX_DIGEST_LEN];
154 static int flist_count_offset; /* for --delete --progress */
155 static int show_filelist_progress;
156
157 static struct file_list *flist_new(int flags, const char *msg);
158 static void flist_sort_and_clean(struct file_list *flist, int strip_root);
159 static void output_flist(struct file_list *flist);
160
161 void init_flist(void)
162 {
163 if (DEBUG_GTE(FLIST, 4)) {
164 rprintf(FINFO, "FILE_STRUCT_LEN=%d, EXTRA_LEN=%d\n",
165 (int)FILE_STRUCT_LEN, (int)EXTRA_LEN);
166 }
167 /* Note that this isn't identical to file_sum_len in the case of CSUM_MD4_ARCHAIC: */
168 flist_csum_len = csum_len_for_type(file_sum_nni->num, 1);
169
170 show_filelist_progress = INFO_GTE(FLIST, 1) && xfer_dirs && !am_server && !inc_recurse;
171 }
172
173 static void start_filelist_progress(char *kind)
174 {
175 if (quiet)
176 return;
177 rprintf(FCLIENT, "%s ... ", kind);
178 output_needs_newline = 1;
179 rflush(FINFO);
180 }
181
182 static void emit_filelist_progress(int count)
183 {
184 if (quiet)
185 return;
186 if (output_needs_newline == 2) /* avoid a newline in the middle of this filelist-progress output */
187 output_needs_newline = 0;
188 rprintf(FCLIENT, " %d files...\r", count);
189 output_needs_newline = 2;
190 }
191
192 static void maybe_emit_filelist_progress(int count)
193 {
194 if (INFO_GTE(FLIST, 2) && show_filelist_progress && (count % 100) == 0)
195 emit_filelist_progress(count);
196 }
197
198 static void finish_filelist_progress(const struct file_list *flist)
199 {
200 output_needs_newline = 0;
201 if (INFO_GTE(FLIST, 2)) {
202 /* This overwrites the progress line */
203 rprintf(FINFO, "%d file%sto consider\n",
204 flist->used, flist->used == 1 ? " " : "s ");
205 } else {
206 rprintf(FINFO, "done\n");
207 }
208 }
209
210 void show_flist_stats(void)
211 {
212 /* Nothing yet */
213 }
214
215 /* Stat either a symlink or its referent, depending on the settings of
216 * copy_links, copy_unsafe_links, etc. Returns -1 on error, 0 on success.
217 *
218 * If path is the name of a symlink, then the linkbuf buffer (which must hold
219 * MAXPATHLEN chars) will be set to the symlink's target string.
220 *
221 * The stat structure pointed to by stp will contain information about the
222 * link or the referent as appropriate, if they exist. */
223 /* Set by send_directory() to the fd of the directory it is currently scanning
224 * (and that dir's path prefix), so the per-entry stat can go through the
225 * already-open dir fd instead of re-resolving the full path for every entry.
226 * Pure performance and sender-side only -- the scanned dir is already open, so
227 * fstatat(scan_dirfd, basename) is identical to lstat(scandir/basename); no
228 * confinement is implied or needed. */
229 static int scan_dirfd = -1;
230 static const char *scan_dir_prefix;
231 static int scan_dir_prefix_len;
232
233 static int scan_link_stat(const char *path, STRUCT_STAT *stp, int follow_dirlinks)
234 {
235 /* Use the held scan fd only for a single component directly inside the
236 * scanned dir, and only when am_root >= 0 (link_stat_at folds in no
237 * fake-super %stat xattr; link_stat does so via get_stat_xattr, a no-op
238 * once am_root >= 0). */
239 if (scan_dirfd >= 0 && am_root >= 0
240 && strncmp(path, scan_dir_prefix, scan_dir_prefix_len) == 0
241 && path[scan_dir_prefix_len] == '/'
242 && strchr(path + scan_dir_prefix_len + 1, '/') == NULL)
243 return link_stat_at(scan_dirfd, path + scan_dir_prefix_len + 1, stp, follow_dirlinks);
244 return link_stat(path, stp, follow_dirlinks);
245 }
246
247 static int scan_readlink(const char *path, char *linkbuf, size_t bufsiz)
248 {
249 if (scan_dirfd >= 0 && am_root >= 0
250 && strncmp(path, scan_dir_prefix, scan_dir_prefix_len) == 0
251 && path[scan_dir_prefix_len] == '/'
252 && strchr(path + scan_dir_prefix_len + 1, '/') == NULL)
253 return do_readlink_atfd(scan_dirfd, path + scan_dir_prefix_len + 1, linkbuf, bufsiz);
254 return do_readlink(path, linkbuf, bufsiz);
255 }
256
257 static int readlink_stat(const char *path, STRUCT_STAT *stp, char *linkbuf)
258 {
259 #ifdef SUPPORT_LINKS
260 if (scan_link_stat(path, stp, copy_dirlinks) < 0)
261 return -1;
262 if (S_ISLNK(stp->st_mode)) {
263 int llen = scan_readlink(path, linkbuf, MAXPATHLEN - 1);
264 if (llen < 0)
265 return -1;
266 linkbuf[llen] = '\0';
267 if (copy_unsafe_links && unsafe_symlink(linkbuf, path)) {
268 if (INFO_GTE(SYMSAFE, 1)) {
269 rprintf(FINFO,"copying unsafe symlink \"%s\" -> \"%s\"\n",
270 path, linkbuf);
271 }
272 return x_stat(path, stp, NULL);
273 }
274 if (munge_symlinks && am_sender && llen > SYMLINK_PREFIX_LEN
275 && strncmp(linkbuf, SYMLINK_PREFIX, SYMLINK_PREFIX_LEN) == 0) {
276 memmove(linkbuf, linkbuf + SYMLINK_PREFIX_LEN,
277 llen - SYMLINK_PREFIX_LEN + 1);
278 }
279 }
280 return 0;
281 #else
282 return x_stat(path, stp, NULL);
283 #endif
284 }
285
286 int link_stat(const char *path, STRUCT_STAT *stp, int follow_dirlinks)
287 {
288 #ifdef SUPPORT_LINKS
289 if (copy_links)
290 return x_stat(path, stp, NULL);
291 if (x_lstat(path, stp, NULL) < 0)
292 return -1;
293 if (follow_dirlinks && S_ISLNK(stp->st_mode)) {
294 STRUCT_STAT st;
295 if (x_stat(path, &st, NULL) == 0 && S_ISDIR(st.st_mode))
296 *stp = st;
297 }
298 return 0;
299 #else
300 return x_stat(path, stp, NULL);
301 #endif
302 }
303
304 /* Held-dirfd variant of link_stat(): stat single-component `name` relative to
305 * directory fd `dfd`, instead of re-resolving a full path. Equivalent to
306 * link_stat() only when NOT in --fake-super mode -- x_stat/x_lstat fold the
307 * fake-super %stat xattr into the result via get_stat_xattr(), which is a
308 * path-based no-op once am_root >= 0. Callers therefore use this only when
309 * am_root >= 0 (and a valid dfd), falling back to link_stat() otherwise. */
310 int link_stat_at(int dfd, const char *name, STRUCT_STAT *stp, int follow_dirlinks)
311 {
312 #ifdef SUPPORT_LINKS
313 if (copy_links)
314 return do_stat_atfd(dfd, name, stp);
315 if (do_lstat_atfd(dfd, name, stp) < 0)
316 return -1;
317 if (follow_dirlinks && S_ISLNK(stp->st_mode)) {
318 STRUCT_STAT st;
319 if (do_stat_atfd(dfd, name, &st) == 0 && S_ISDIR(st.st_mode))
320 *stp = st;
321 }
322 return 0;
323 #else
324 return do_stat_atfd(dfd, name, stp);
325 #endif
326 }
327
328 static inline int path_is_daemon_excluded(char *path, int ignore_filename)
329 {
330 if (daemon_filter_list.head) {
331 char *slash = path;
332
333 while ((slash = strchr(slash+1, '/')) != NULL) {
334 int ret;
335 *slash = '\0';
336 ret = check_filter(&daemon_filter_list, FLOG, path, 1);
337 *slash = '/';
338 if (ret < 0) {
339 errno = ENOENT;
340 return 1;
341 }
342 }
343
344 if (!ignore_filename
345 && check_filter(&daemon_filter_list, FLOG, path, 1) < 0) {
346 errno = ENOENT;
347 return 1;
348 }
349 }
350
351 return 0;
352 }
353
354 static inline int is_excluded(const char *fname, int is_dir, int filter_level)
355 {
356 return name_is_excluded(fname, is_dir ? NAME_IS_DIR : NAME_IS_FILE, filter_level);
357 }
358
359 static void send_directory(int f, struct file_list *flist,
360 char *fbuf, int len, int flags);
361
362 static const char *pathname, *orig_dir;
363 static int pathname_len;
364
365 /* Make sure flist can hold at least flist->used + extra entries. */
366 static void flist_expand(struct file_list *flist, int extra)
367 {
368 struct file_struct **new_ptr;
369
370 /* Refuse BEFORE any int arithmetic below can overflow: used+extra (computed
371 * in the early-return and the cap below) and the malloced growth math. Only
372 * reachable past INT_MAX entries (my_alloc's --max-alloc cap normally stops
373 * the list growing anywhere near there). */
374 if (extra < 0 || flist->used < 0 || flist->used > INT_MAX - extra)
375 goto too_large;
376
377 if (flist->used + extra <= flist->malloced)
378 return;
379
380 if (flist->malloced < FLIST_START)
381 flist->malloced = FLIST_START;
382 else if (flist->malloced >= FLIST_LINEAR) {
383 if (flist->malloced > INT_MAX - FLIST_LINEAR)
384 goto too_large;
385 flist->malloced += FLIST_LINEAR;
386 } else if (flist->malloced < FLIST_START_LARGE/16) {
387 if (flist->malloced > INT_MAX/4)
388 goto too_large;
389 flist->malloced *= 4;
390 } else {
391 if (flist->malloced > INT_MAX/2)
392 goto too_large;
393 flist->malloced *= 2;
394 }
395
396 /* In case count jumped or we are starting the list
397 * with a known size just set it. */
398 if (flist->malloced < flist->used + extra)
399 flist->malloced = flist->used + extra;
400
401 new_ptr = realloc_array(flist->files, struct file_struct *, flist->malloced);
402
403 if (DEBUG_GTE(FLIST, 1) && flist->files) {
404 rprintf(FCLIENT, "[%s] expand file_list pointer array to %s bytes, did%s move\n",
405 who_am_i(),
406 big_num(sizeof flist->files[0] * flist->malloced),
407 (new_ptr == flist->files) ? " not" : "");
408 }
409
410 flist->files = new_ptr;
411 return;
412
413 too_large:
414 rprintf(FERROR, "[%s] file list has grown too large to expand\n", who_am_i());
415 exit_cleanup(RERR_MALLOC);
416 }
417
418 static void flist_done_allocating(struct file_list *flist)
419 {
420 void *ptr = pool_boundary(flist->file_pool, 8*1024);
421 if (flist->pool_boundary == ptr)
422 flist->pool_boundary = NULL; /* list didn't use any pool memory */
423 else
424 flist->pool_boundary = ptr;
425 }
426
427 /* Call this with EITHER (1) "file, NULL, 0" to chdir() to the file's
428 * F_PATHNAME(), or (2) "NULL, dir, dirlen" to chdir() to the supplied dir,
429 * with dir == NULL taken to be the starting directory, and dirlen < 0
430 * indicating that strdup(dir) should be called and then the -dirlen length
431 * value checked to ensure that it is not daemon-excluded. */
432 int change_pathname(struct file_struct *file, const char *dir, int dirlen)
433 {
434 if (dirlen < 0) {
435 char *cpy = strdup(dir);
436 if (*cpy != '/')
437 change_dir(orig_dir, CD_SKIP_CHDIR);
438 if (path_is_daemon_excluded(cpy, 0))
439 goto chdir_error;
440 dir = cpy;
441 dirlen = -dirlen;
442 } else {
443 if (file) {
444 if (pathname == F_PATHNAME(file))
445 return 1;
446 dir = F_PATHNAME(file);
447 if (dir)
448 dirlen = strlen(dir);
449 } else if (pathname == dir)
450 return 1;
451 if (dir && *dir != '/')
452 change_dir(orig_dir, CD_SKIP_CHDIR);
453 }
454
455 pathname = dir;
456 pathname_len = dirlen;
457
458 if (!dir)
459 dir = orig_dir;
460
461 if (!change_dir(dir, CD_NORMAL)) {
462 chdir_error:
463 io_error |= IOERR_GENERAL;
464 rsyserr(FERROR_XFER, errno, "change_dir %s failed", full_fname(dir));
465 if (dir != orig_dir)
466 change_dir(orig_dir, CD_NORMAL);
467 pathname = NULL;
468 pathname_len = 0;
469 return 0;
470 }
471
472 return 1;
473 }
474
475 static void send_file_entry(int f, const char *fname, struct file_struct *file,
476 #ifdef SUPPORT_LINKS
477 const char *symlink_name, int symlink_len,
478 #endif
479 int ndx, int first_ndx)
480 {
481 static time_t modtime, atime;
482 #ifdef SUPPORT_CRTIMES
483 static time_t crtime;
484 #endif
485 static mode_t mode;
486 #ifdef SUPPORT_HARD_LINKS
487 static int64 dev;
488 #endif
489 static dev_t rdev;
490 static uint32 rdev_major;
491 static uid_t uid;
492 static gid_t gid;
493 static const char *user_name, *group_name;
494 static char lastname[MAXPATHLEN];
495 #ifdef SUPPORT_HARD_LINKS
496 int first_hlink_ndx = -1;
497 #endif
498 int l1, l2;
499 int xflags;
500
501 /* Initialize starting value of xflags and adjust counts. */
502 if (S_ISREG(file->mode))
503 xflags = 0;
504 else if (S_ISDIR(file->mode)) {
505 stats.num_dirs++;
506 if (protocol_version >= 30) {
507 if (file->flags & FLAG_CONTENT_DIR)
508 xflags = file->flags & FLAG_TOP_DIR;
509 else if (file->flags & FLAG_IMPLIED_DIR)
510 xflags = XMIT_TOP_DIR | XMIT_NO_CONTENT_DIR;
511 else
512 xflags = XMIT_NO_CONTENT_DIR;
513 } else
514 xflags = file->flags & FLAG_TOP_DIR; /* FLAG_TOP_DIR == XMIT_TOP_DIR */
515 } else {
516 if (S_ISLNK(file->mode))
517 stats.num_symlinks++;
518 else if (IS_DEVICE(file->mode))
519 stats.num_devices++;
520 else if (IS_SPECIAL(file->mode))
521 stats.num_specials++;
522 xflags = 0;
523 }
524
525 if (file->mode == mode)
526 xflags |= XMIT_SAME_MODE;
527 else
528 mode = file->mode;
529
530 if (preserve_devices && IS_DEVICE(mode)) {
531 if (protocol_version < 28) {
532 if (tmp_rdev == rdev)
533 xflags |= XMIT_SAME_RDEV_pre28;
534 else
535 rdev = tmp_rdev;
536 } else {
537 rdev = tmp_rdev;
538 if ((uint32)major(rdev) == rdev_major)
539 xflags |= XMIT_SAME_RDEV_MAJOR;
540 else
541 rdev_major = major(rdev);
542 if (protocol_version < 30 && (uint32)minor(rdev) <= 0xFFu)
543 xflags |= XMIT_RDEV_MINOR_8_pre30;
544 }
545 } else if (preserve_specials && IS_SPECIAL(mode) && protocol_version < 31) {
546 /* Special files don't need an rdev number, so just make
547 * the historical transmission of the value efficient. */
548 if (protocol_version < 28)
549 xflags |= XMIT_SAME_RDEV_pre28;
550 else {
551 rdev = MAKEDEV(rdev_major, 0);
552 xflags |= XMIT_SAME_RDEV_MAJOR;
553 if (protocol_version < 30)
554 xflags |= XMIT_RDEV_MINOR_8_pre30;
555 }
556 } else if (protocol_version < 28)
557 rdev = MAKEDEV(0, 0);
558 if (!preserve_uid || ((uid_t)F_OWNER(file) == uid && *lastname))
559 xflags |= XMIT_SAME_UID;
560 else {
561 uid = F_OWNER(file);
562 if (!numeric_ids) {
563 user_name = add_uid(uid);
564 if (inc_recurse && user_name)
565 xflags |= XMIT_USER_NAME_FOLLOWS;
566 }
567 }
568 if (!preserve_gid || ((gid_t)F_GROUP(file) == gid && *lastname))
569 xflags |= XMIT_SAME_GID;
570 else {
571 gid = F_GROUP(file);
572 if (!numeric_ids) {
573 group_name = add_gid(gid);
574 if (inc_recurse && group_name)
575 xflags |= XMIT_GROUP_NAME_FOLLOWS;
576 }
577 }
578 if (file->modtime == modtime)
579 xflags |= XMIT_SAME_TIME;
580 else
581 modtime = file->modtime;
582 if (NSEC_BUMP(file) && protocol_version >= 31)
583 xflags |= XMIT_MOD_NSEC;
584 if (atimes_ndx && !S_ISDIR(mode)) {
585 if (F_ATIME(file) == atime)
586 xflags |= XMIT_SAME_ATIME;
587 else
588 atime = F_ATIME(file);
589 }
590 #ifdef SUPPORT_CRTIMES
591 if (crtimes_ndx) {
592 crtime = F_CRTIME(file);
593 if (crtime == modtime)
594 xflags |= XMIT_CRTIME_EQ_MTIME;
595 }
596 #endif
597
598 #ifdef SUPPORT_HARD_LINKS
599 if (tmp_dev != -1) {
600 if (protocol_version >= 30) {
601 struct ht_int64_node *np = idev_find(tmp_dev, tmp_ino);
602 first_hlink_ndx = (int32)(long)np->data; /* is -1 when new */
603 if (first_hlink_ndx < 0) {
604 np->data = (void*)(long)(first_ndx + ndx);
605 xflags |= XMIT_HLINK_FIRST;
606 }
607 if (DEBUG_GTE(HLINK, 1)) {
608 if (first_hlink_ndx >= 0) {
609 rprintf(FINFO, "[%s] #%d hard-links #%d (%sabbrev)\n",
610 who_am_i(), first_ndx + ndx, first_hlink_ndx,
611 first_hlink_ndx >= first_ndx ? "" : "un");
612 } else if (DEBUG_GTE(HLINK, 3)) {
613 rprintf(FINFO, "[%s] dev:inode for #%d is %s:%s\n",
614 who_am_i(), first_ndx + ndx,
615 big_num(tmp_dev), big_num(tmp_ino));
616 }
617 }
618 } else {
619 if (tmp_dev == dev) {
620 if (protocol_version >= 28)
621 xflags |= XMIT_SAME_DEV_pre30;
622 } else
623 dev = tmp_dev;
624 }
625 xflags |= XMIT_HLINKED;
626 }
627 #endif
628
629 for (l1 = 0;
630 lastname[l1] && (fname[l1] == lastname[l1]) && (l1 < 255);
631 l1++) {}
632 l2 = strlen(fname+l1);
633
634 if (l1 > 0)
635 xflags |= XMIT_SAME_NAME;
636 if (l2 > 255)
637 xflags |= XMIT_LONG_NAME;
638
639 /* We must avoid sending a flag value of 0 (or an initial byte of
640 * 0 for the older xflags protocol) or it will signal the end of
641 * the list. Note that the use of XMIT_TOP_DIR on a non-dir has
642 * no meaning, so it's a harmless way to add a bit to the first
643 * flag byte. */
644 if (xfer_flags_as_varint)
645 write_varint(f, xflags ? xflags : XMIT_EXTENDED_FLAGS);
646 else if (protocol_version >= 28) {
647 if (!xflags && !S_ISDIR(mode))
648 xflags |= XMIT_TOP_DIR;
649 if ((xflags & 0xFF00) || !xflags) {
650 xflags |= XMIT_EXTENDED_FLAGS;
651 write_shortint(f, xflags);
652 } else
653 write_byte(f, xflags);
654 } else {
655 if (!(xflags & 0xFF))
656 xflags |= S_ISDIR(mode) ? XMIT_LONG_NAME : XMIT_TOP_DIR;
657 write_byte(f, xflags);
658 }
659 if (xflags & XMIT_SAME_NAME)
660 write_byte(f, l1);
661 if (xflags & XMIT_LONG_NAME)
662 write_varint30(f, l2);
663 else
664 write_byte(f, l2);
665 write_buf(f, fname + l1, l2);
666
667 #ifdef SUPPORT_HARD_LINKS
668 if (first_hlink_ndx >= 0) {
669 write_varint(f, first_hlink_ndx);
670 if (first_hlink_ndx >= first_ndx)
671 goto the_end;
672 }
673 #endif
674
675 write_varlong30(f, F_LENGTH(file), 3);
676 if (!(xflags & XMIT_SAME_TIME)) {
677 if (protocol_version >= 30)
678 write_varlong(f, modtime, 4);
679 else
680 write_int(f, modtime);
681 }
682 if (xflags & XMIT_MOD_NSEC)
683 write_varint(f, F_MOD_NSEC(file));
684 #ifdef SUPPORT_CRTIMES
685 if (crtimes_ndx && !(xflags & XMIT_CRTIME_EQ_MTIME))
686 write_varlong(f, crtime, 4);
687 #endif
688 if (!(xflags & XMIT_SAME_MODE))
689 write_int(f, to_wire_mode(mode));
690 if (atimes_ndx && !S_ISDIR(mode) && !(xflags & XMIT_SAME_ATIME))
691 write_varlong(f, atime, 4);
692 if (preserve_uid && !(xflags & XMIT_SAME_UID)) {
693 if (protocol_version < 30)
694 write_int(f, uid);
695 else {
696 write_varint(f, uid);
697 if (xflags & XMIT_USER_NAME_FOLLOWS) {
698 int len = strlen(user_name);
699 write_byte(f, len);
700 write_buf(f, user_name, len);
701 }
702 }
703 }
704 if (preserve_gid && !(xflags & XMIT_SAME_GID)) {
705 if (protocol_version < 30)
706 write_int(f, gid);
707 else {
708 write_varint(f, gid);
709 if (xflags & XMIT_GROUP_NAME_FOLLOWS) {
710 int len = strlen(group_name);
711 write_byte(f, len);
712 write_buf(f, group_name, len);
713 }
714 }
715 }
716 if ((preserve_devices && IS_DEVICE(mode))
717 || (preserve_specials && IS_SPECIAL(mode) && protocol_version < 31)) {
718 if (protocol_version < 28) {
719 if (!(xflags & XMIT_SAME_RDEV_pre28))
720 write_int(f, (int)rdev);
721 } else {
722 if (!(xflags & XMIT_SAME_RDEV_MAJOR))
723 write_varint30(f, major(rdev));
724 if (protocol_version >= 30)
725 write_varint(f, minor(rdev));
726 else if (xflags & XMIT_RDEV_MINOR_8_pre30)
727 write_byte(f, minor(rdev));
728 else
729 write_int(f, minor(rdev));
730 }
731 }
732
733 #ifdef SUPPORT_LINKS
734 if (symlink_len) {
735 write_varint30(f, symlink_len);
736 write_buf(f, symlink_name, symlink_len);
737 }
738 #endif
739
740 #ifdef SUPPORT_HARD_LINKS
741 if (tmp_dev != -1 && protocol_version < 30) {
742 /* Older protocols expect the dev number to be transmitted
743 * 1-incremented so that it is never zero. */
744 if (protocol_version < 26) {
745 /* 32-bit dev_t and ino_t */
746 write_int(f, (int32)(dev+1));
747 write_int(f, (int32)tmp_ino);
748 } else {
749 /* 64-bit dev_t and ino_t */
750 if (!(xflags & XMIT_SAME_DEV_pre30))
751 write_longint(f, dev+1);
752 write_longint(f, tmp_ino);
753 }
754 }
755 #endif
756
757 if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
758 const char *sum;
759 if (S_ISREG(mode))
760 sum = tmp_sum;
761 else {
762 /* Prior to 28, we sent a useless set of nulls. */
763 sum = empty_sum;
764 }
765 write_buf(f, sum, flist_csum_len);
766 }
767
768 #ifdef SUPPORT_HARD_LINKS
769 the_end:
770 #endif
771 strlcpy(lastname, fname, MAXPATHLEN);
772
773 if (S_ISREG(mode) || S_ISLNK(mode))
774 stats.total_size += F_LENGTH(file);
775 }
776
777 static struct file_struct *recv_file_entry(int f, struct file_list *flist, int xflags)
778 {
779 static int64 modtime, atime;
780 #ifdef SUPPORT_CRTIMES
781 static time_t crtime;
782 #endif
783 static mode_t mode;
784 #ifdef SUPPORT_HARD_LINKS
785 static int64 dev;
786 #endif
787 static dev_t rdev;
788 static uint32 rdev_major;
789 static uid_t uid;
790 static gid_t gid;
791 static uint16 gid_flags;
792 static char lastname[MAXPATHLEN], *lastdir;
793 static int lastdir_depth, lastdir_len = -1;
794 static unsigned int del_hier_name_len = 0;
795 static int in_del_hier = 0;
796 char thisname[MAXPATHLEN];
797 unsigned int l1 = 0, l2 = 0;
798 int alloc_len, basename_len, linkname_len;
799 int extra_len = file_extra_cnt * EXTRA_LEN;
800 int first_hlink_ndx = -1;
801 char real_ISREG_entry;
802 int64 file_length;
803 #ifdef CAN_SET_NSEC
804 uint32 modtime_nsec;
805 #endif
806 const char *basename;
807 struct file_struct *file;
808 alloc_pool_t *pool;
809 char *bp;
810
811 if (xflags & XMIT_SAME_NAME)
812 l1 = read_byte(f);
813
814 if (xflags & XMIT_LONG_NAME)
815 l2 = read_varint30(f);
816 else
817 l2 = read_byte(f);
818
819 if (l2 >= MAXPATHLEN - l1) {
820 rprintf(FERROR,
821 "overflow: xflags=0x%x l1=%d l2=%d lastname=%s [%s]\n",
822 xflags, l1, l2, lastname, who_am_i());
823 overflow_exit("recv_file_entry");
824 }
825
826 strlcpy(thisname, lastname, l1 + 1);
827 read_sbuf(f, &thisname[l1], l2);
828 thisname[l1 + l2] = 0;
829
830 /* Abuse basename_len for a moment... */
831 basename_len = strlcpy(lastname, thisname, MAXPATHLEN);
832
833 #ifdef ICONV_OPTION
834 if (ic_recv != (iconv_t)-1) {
835 xbuf outbuf, inbuf;
836
837 INIT_CONST_XBUF(outbuf, thisname);
838 INIT_XBUF(inbuf, lastname, basename_len, (size_t)-1);
839
840 if (iconvbufs(ic_recv, &inbuf, &outbuf, ICB_INIT) < 0) {
841 io_error |= IOERR_GENERAL;
842 rprintf(FERROR_UTF8,
843 "[%s] cannot convert filename: %s (%s)\n",
844 who_am_i(), lastname, strerror(errno));
845 outbuf.len = 0;
846 }
847 thisname[outbuf.len] = '\0';
848 }
849 #endif
850
851 if (*thisname
852 && (clean_fname(thisname, CFN_REFUSE_DOT_DOT_DIRS) < 0 || (!relative_paths && *thisname == '/'))) {
853 rprintf(FERROR, "ABORTING due to unsafe pathname from sender: %s\n", thisname);
854 exit_cleanup(RERR_UNSUPPORTED);
855 }
856
857 if (sanitize_paths)
858 sanitize_path(thisname, thisname, "", 0, SP_DEFAULT);
859
860 if ((basename = strrchr(thisname, '/')) != NULL) {
861 int len = basename++ - thisname;
862 if (len != lastdir_len || !lastdir || memcmp(thisname, lastdir, len) != 0) {
863 lastdir = new_array(char, len + 1);
864 memcpy(lastdir, thisname, len);
865 lastdir[len] = '\0';
866 lastdir_len = len;
867 lastdir_depth = count_dir_elements(lastdir);
868 }
869 } else
870 basename = thisname;
871 basename_len = strlen(basename) + 1; /* count the '\0' */
872
873 #ifdef SUPPORT_HARD_LINKS
874 if (protocol_version >= 30
875 && BITS_SETnUNSET(xflags, XMIT_HLINKED, XMIT_HLINK_FIRST)) {
876 first_hlink_ndx = read_varint(f);
877 if (first_hlink_ndx < 0 || first_hlink_ndx >= flist->ndx_start + flist->used) {
878 rprintf(FERROR,
879 "hard-link reference out of range: %d (%d)\n",
880 first_hlink_ndx, flist->ndx_start + flist->used);
881 exit_cleanup(RERR_PROTOCOL);
882 }
883 if (DEBUG_GTE(HLINK, 1)) {
884 rprintf(FINFO, "[%s] #%d hard-links #%d (%sabbrev)\n",
885 who_am_i(), flist->used+flist->ndx_start, first_hlink_ndx,
886 first_hlink_ndx >= flist->ndx_start ? "" : "un");
887 }
888 if (first_hlink_ndx >= flist->ndx_start) {
889 struct file_struct *first = flist->files[first_hlink_ndx - flist->ndx_start];
890 file_length = F_LENGTH(first);
891 modtime = first->modtime;
892 #ifdef CAN_SET_NSEC
893 modtime_nsec = F_MOD_NSEC_or_0(first);
894 #endif
895 mode = first->mode;
896 if (atimes_ndx && !S_ISDIR(mode))
897 atime = F_ATIME(first);
898 #ifdef SUPPORT_CRTIMES
899 if (crtimes_ndx)
900 crtime = F_CRTIME(first);
901 #endif
902 if (preserve_uid)
903 uid = F_OWNER(first);
904 if (preserve_gid)
905 gid = F_GROUP(first);
906 if (preserve_devices && IS_DEVICE(mode)) {
907 uint32 *devp = F_RDEV_P(first);
908 rdev_major = DEV_MAJOR(devp);
909 rdev = MAKEDEV(rdev_major, DEV_MINOR(devp));
910 extra_len += DEV_EXTRA_CNT * EXTRA_LEN;
911 } else if (IS_DEVICE(mode)) {
912 /* Abbrev-branch counterpart to the !preserve_devices
913 * stub-alloc below: zeroed F_RDEV_P slots. */
914 extra_len += DEV_EXTRA_CNT * EXTRA_LEN;
915 }
916 if (preserve_links && S_ISLNK(mode))
917 linkname_len = strlen(F_SYMLINK(first)) + 1;
918 else if (S_ISLNK(mode))
919 /* Abbrev-branch counterpart to the !preserve_links
920 * stub-alloc below: empty linkname. */
921 linkname_len = 1;
922 else
923 linkname_len = 0;
924 real_ISREG_entry = S_ISREG(mode) ? 1 : 0;
925 goto create_object;
926 }
927 }
928 #endif
929
930 file_length = read_varlong30(f, 3);
931 if (!(xflags & XMIT_SAME_TIME)) {
932 if (protocol_version >= 30) {
933 modtime = read_varlong(f, 4);
934 #if SIZEOF_TIME_T < SIZEOF_INT64
935 if (!am_generator && (int64)(time_t)modtime != modtime) {
936 rprintf(FERROR_XFER,
937 "Time value of %s truncated on receiver.\n",
938 lastname);
939 }
940 #endif
941 } else
942 modtime = read_uint(f);
943 }
944 if (xflags & XMIT_MOD_NSEC)
945 #ifndef CAN_SET_NSEC
946 (void)read_varint_bounded(f, 0, MAX_WIRE_NSEC, "modtime_nsec");
947 #else
948 modtime_nsec = read_varint_bounded(f, 0, MAX_WIRE_NSEC, "modtime_nsec");
949 else
950 modtime_nsec = 0;
951 #endif
952 #ifdef SUPPORT_CRTIMES
953 if (crtimes_ndx) {
954 if (xflags & XMIT_CRTIME_EQ_MTIME)
955 crtime = modtime;
956 else
957 crtime = read_varlong(f, 4);
958 #if SIZEOF_TIME_T < SIZEOF_INT64
959 if (!am_generator && (int64)(time_t)crtime != crtime) {
960 rprintf(FERROR_XFER,
961 "Create time value of %s truncated on receiver.\n",
962 lastname);
963 }
964 #endif
965 }
966 #endif
967 if (!(xflags & XMIT_SAME_MODE)) {
968 mode = from_wire_mode(read_int(f));
969 /* Reject modes whose type bits are not one of the standard
970 * file types; otherwise garbage mode values propagate through
971 * the file-type checks below unpredictably. mode 0 is the one
972 * legitimate exception: --delete-missing-args (missing_args==2)
973 * sends a missing arg as a mode-0 entry (IS_MISSING_FILE), the
974 * generator's delete signal (#910). */
975 if (mode != 0 || missing_args != 2) {
976 if (!S_ISREG(mode) && !S_ISDIR(mode) && !S_ISLNK(mode)
977 && !S_ISCHR(mode) && !S_ISBLK(mode)
978 && !S_ISFIFO(mode) && !S_ISSOCK(mode)) {
979 rprintf(FERROR, "invalid file mode 0%o for %s [%s]\n",
980 (unsigned)mode, lastname, who_am_i());
981 exit_cleanup(RERR_PROTOCOL);
982 }
983 }
984 }
985 if (atimes_ndx && !S_ISDIR(mode) && !(xflags & XMIT_SAME_ATIME)) {
986 atime = read_varlong(f, 4);
987 #if SIZEOF_TIME_T < SIZEOF_INT64
988 if (!am_generator && (int64)(time_t)atime != atime) {
989 rprintf(FERROR_XFER,
990 "Access time value of %s truncated on receiver.\n",
991 lastname);
992 }
993 #endif
994 }
995
996 if (chmod_modes && !S_ISLNK(mode) && mode)
997 mode = tweak_mode(mode, chmod_modes);
998
999 if (preserve_uid && !(xflags & XMIT_SAME_UID)) {
1000 if (protocol_version < 30)
1001 uid = (uid_t)read_int(f);
1002 else {
1003 uid = (uid_t)read_varint(f);
1004 if (xflags & XMIT_USER_NAME_FOLLOWS)
1005 uid = recv_user_name(f, uid);
1006 else if (inc_recurse && am_root && (!numeric_ids || usermap))
1007 uid = match_uid(uid);
1008 }
1009 }
1010 if (preserve_gid && !(xflags & XMIT_SAME_GID)) {
1011 if (protocol_version < 30)
1012 gid = (gid_t)read_int(f);
1013 else {
1014 gid = (gid_t)read_varint(f);
1015 gid_flags = 0;
1016 if (xflags & XMIT_GROUP_NAME_FOLLOWS)
1017 gid = recv_group_name(f, gid, &gid_flags);
1018 else if (inc_recurse && (!am_root || !numeric_ids || groupmap))
1019 gid = match_gid(gid, &gid_flags);
1020 }
1021 }
1022
1023 if ((preserve_devices && IS_DEVICE(mode))
1024 || (preserve_specials && IS_SPECIAL(mode) && protocol_version < 31)) {
1025 if (protocol_version < 28) {
1026 if (!(xflags & XMIT_SAME_RDEV_pre28))
1027 rdev = (dev_t)read_int(f);
1028 } else {
1029 uint32 rdev_minor;
1030 if (!(xflags & XMIT_SAME_RDEV_MAJOR))
1031 rdev_major = read_varint30(f);
1032 if (protocol_version >= 30)
1033 rdev_minor = read_varint(f);
1034 else if (xflags & XMIT_RDEV_MINOR_8_pre30)
1035 rdev_minor = read_byte(f);
1036 else
1037 rdev_minor = read_int(f);
1038 rdev = MAKEDEV(rdev_major, rdev_minor);
1039 }
1040 if (IS_DEVICE(mode))
1041 extra_len += DEV_EXTRA_CNT * EXTRA_LEN;
1042 file_length = 0;
1043 } else if (IS_DEVICE(mode)) {
1044 /* Peer/batch sent an S_IFCHR/S_IFBLK entry but we are not
1045 * preserving devices. A cooperating sender wouldn't do this;
1046 * a crafted batch can. Allocate (and zero, via the memset
1047 * below) the DEV_EXTRA_CNT slots so F_RDEV_P() callers
1048 * (set_stat_xattr under --fake-super, generator IS_DEVICE
1049 * paths) read {0,0} instead of the previous pool slot. */
1050 extra_len += DEV_EXTRA_CNT * EXTRA_LEN;
1051 file_length = 0;
1052 } else if (protocol_version < 28)
1053 rdev = MAKEDEV(0, 0);
1054
1055 #ifdef SUPPORT_LINKS
1056 if (preserve_links && S_ISLNK(mode)) {
1057 linkname_len = read_varint30(f) + 1; /* count the '\0' */
1058 if (linkname_len <= 0 || linkname_len > MAXPATHLEN) {
1059 rprintf(FERROR, "overflow: linkname_len=%d\n",
1060 linkname_len - 1);
1061 overflow_exit("recv_file_entry");
1062 }
1063 #ifdef ICONV_OPTION
1064 /* We don't know how much extra room we need to convert
1065 * the as-yet-unread symlink data, so let's hope that a
1066 * double-size buffer is plenty. */
1067 if (sender_symlink_iconv)
1068 linkname_len *= 2;
1069 #endif
1070 if (munge_symlinks)
1071 linkname_len += SYMLINK_PREFIX_LEN;
1072 } else if (S_ISLNK(mode)) {
1073 /* Peer/batch sent an S_IFLNK entry but we are not preserving
1074 * links (no -l, and the batch stream-flags didn't set it). A
1075 * cooperating sender wouldn't do this; a crafted batch can.
1076 * Allocate one byte for an empty linkname so F_SYMLINK()
1077 * callers (log.c %L, generator.c) read a valid "" instead of
1078 * the next pool slot's redzone. */
1079 linkname_len = 1;
1080 }
1081 else
1082 #endif
1083 linkname_len = 0;
1084
1085 if (copy_devices && IS_DEVICE(mode)) {
1086 /* This is impossible in the official release, but some pre-release patches
1087 * didn't convert the device into a file before sending, so we'll do it here
1088 * (even though the length is typically 0 and any checksum data is zeros). */
1089 mode = S_IFREG | (mode & ACCESSPERMS);
1090 modtime = time(NULL); /* The mtime on the device is not up-to-date, so set it to "now". */
1091 real_ISREG_entry = 0;
1092 } else
1093 real_ISREG_entry = S_ISREG(mode) ? 1 : 0;
1094
1095 #ifdef SUPPORT_HARD_LINKS
1096 create_object:
1097 if (preserve_hard_links) {
1098 if (protocol_version < 28 && real_ISREG_entry)
1099 xflags |= XMIT_HLINKED;
1100 if (xflags & XMIT_HLINKED)
1101 extra_len += (inc_recurse+1) * EXTRA_LEN;
1102 }
1103 #endif
1104
1105 #ifdef SUPPORT_ACLS
1106 /* Directories need an extra int32 for the default ACL. */
1107 if (preserve_acls && S_ISDIR(mode))
1108 extra_len += EXTRA_LEN;
1109 #endif
1110
1111 if (always_checksum && S_ISREG(mode))
1112 extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
1113
1114 #if SIZEOF_INT64 >= 8
1115 if (file_length > 0xFFFFFFFFu && S_ISREG(mode))
1116 extra_len += EXTRA_LEN;
1117 #endif
1118 #ifdef CAN_SET_NSEC
1119 if (modtime_nsec)
1120 extra_len += EXTRA_LEN;
1121 #endif
1122 if (file_length < 0) {
1123 rprintf(FERROR, "Offset underflow: file-length is negative\n");
1124 exit_cleanup(RERR_UNSUPPORTED);
1125 }
1126
1127 /* "." is the synthetic transfer root. Reinterpreting it as a file lets
1128 * --force recursively remove the real destination directory before the
1129 * receiver creates that file. */
1130 if ((!strcmp(thisname, ".") || !strcmp(thisname, "/.")) && !S_ISDIR(mode)) {
1131 rprintf(FERROR, "ERROR: rejecting non-directory transfer-root entry: %s\n",
1132 thisname);
1133 exit_cleanup(RERR_PROTOCOL);
1134 }
1135
1136 if (*thisname == '/' ? thisname[1] != '.' || thisname[2] != '\0' : *thisname != '.' || thisname[1] != '\0') {
1137 int filt_flags = S_ISDIR(mode) ? NAME_IS_DIR : NAME_IS_FILE;
1138 if (!trust_sender_filter /* a per-dir filter rule means we must trust the sender's filtering */
1139 && filter_list.head && check_server_filter(&filter_list, FINFO, thisname, filt_flags) < 0) {
1140 rprintf(FERROR, "ERROR: rejecting excluded file-list name: %s\n", thisname);
1141 exit_cleanup(RERR_UNSUPPORTED);
1142 }
1143 if (implied_filter_list.head && check_filter(&implied_filter_list, FINFO, thisname, filt_flags) <= 0) {
1144 rprintf(FERROR, "ERROR: rejecting unrequested file-list name: %s\n", thisname);
1145 exit_cleanup(RERR_UNSUPPORTED);
1146 }
1147 }
1148
1149 if (inc_recurse && S_ISDIR(mode)) {
1150 if (one_file_system) {
1151 /* Room to save the dir's device for -x */
1152 extra_len += DEV_EXTRA_CNT * EXTRA_LEN;
1153 }
1154 pool = dir_flist->file_pool;
1155 } else
1156 pool = flist->file_pool;
1157
1158 #if EXTRA_ROUNDING > 0
1159 if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
1160 extra_len = (extra_len | (EXTRA_ROUNDING * EXTRA_LEN)) + EXTRA_LEN;
1161 #endif
1162
1163 alloc_len = FILE_STRUCT_LEN + extra_len + basename_len
1164 + linkname_len;
1165 bp = pool_alloc(pool, alloc_len, "recv_file_entry");
1166
1167 memset(bp, 0, extra_len + FILE_STRUCT_LEN);
1168 bp += extra_len;
1169 file = (struct file_struct *)bp;
1170 bp += FILE_STRUCT_LEN;
1171
1172 memcpy(bp, basename, basename_len);
1173
1174 #ifdef SUPPORT_HARD_LINKS
1175 if (preserve_hard_links && xflags & XMIT_HLINKED
1176 && !S_ISDIR(mode)
1177 #ifndef CAN_HARDLINK_SYMLINK
1178 && !S_ISLNK(mode)
1179 #endif
1180 #ifndef CAN_HARDLINK_SPECIAL
1181 && !IS_SPECIAL(mode) && !IS_DEVICE(mode)
1182 #endif
1183 )
1184 file->flags |= FLAG_HLINKED;
1185 #endif
1186 file->modtime = (time_t)modtime;
1187 #ifdef CAN_SET_NSEC
1188 if (modtime_nsec) {
1189 file->flags |= FLAG_MOD_NSEC;
1190 F_MOD_NSEC(file) = modtime_nsec;
1191 }
1192 #endif
1193 file->len32 = (uint32)file_length;
1194 #if SIZEOF_INT64 >= 8
1195 if (file_length > 0xFFFFFFFFu && S_ISREG(mode)) {
1196 #if SIZEOF_CAPITAL_OFF_T < 8
1197 rprintf(FERROR, "Offset overflow: attempted 64-bit file-length\n");
1198 exit_cleanup(RERR_UNSUPPORTED);
1199 #else
1200 file->flags |= FLAG_LENGTH64;
1201 F_HIGH_LEN(file) = (uint32)(file_length >> 32);
1202 #endif
1203 }
1204 #endif
1205 file->mode = mode;
1206 if (preserve_uid)
1207 F_OWNER(file) = uid;
1208 if (preserve_gid) {
1209 F_GROUP(file) = gid;
1210 file->flags |= gid_flags;
1211 }
1212 if (atimes_ndx && !S_ISDIR(mode))
1213 F_ATIME(file) = atime;
1214 #ifdef SUPPORT_CRTIMES
1215 if (crtimes_ndx)
1216 F_CRTIME(file) = crtime;
1217 #endif
1218 if (unsort_ndx)
1219 F_NDX(file) = flist->used + flist->ndx_start;
1220
1221 if (basename != thisname) {
1222 file->dirname = lastdir;
1223 F_DEPTH(file) = lastdir_depth + 1;
1224 } else
1225 F_DEPTH(file) = 1;
1226
1227 if (S_ISDIR(mode)) {
1228 if (basename_len == 1+1 && *basename == '.') /* +1 for '\0' */
1229 F_DEPTH(file)--;
1230 if (protocol_version >= 30) {
1231 /* Stop a malicious sender expanding --delete scope by flagging
1232 * an implied parent as a content dir: if we only allowed this
1233 * entry as a parent of the requested leaf, force the flags back
1234 * to the honest implied-parent encoding (XMIT_TOP_DIR |
1235 * XMIT_NO_CONTENT_DIR) so it lands in FLAG_IMPLIED_DIR, not
1236 * FLAG_CONTENT_DIR, and delete_in_dir() can't sweep siblings.
1237 * Not gated on trust_sender_filter: implied_filter_list is
1238 * receiver-owned state, so a per-dir filter must not be able to
1239 * downgrade this defense. */
1240 if (implied_filter_list.head
1241 && is_implied_parent_dir(thisname)
1242 && (!(xflags & XMIT_NO_CONTENT_DIR) || !(xflags & XMIT_TOP_DIR))) {
1243 if (DEBUG_GTE(FILTER, 1)) {
1244 rprintf(FINFO,
1245 "[%s] receiver downgraded implied-parent dir %s "
1246 "to non-content (sender xflags=0x%x)\n",
1247 who_am_i(), thisname, xflags);
1248 }
1249 xflags |= XMIT_NO_CONTENT_DIR | XMIT_TOP_DIR;
1250 }
1251 if (!(xflags & XMIT_NO_CONTENT_DIR)) {
1252 if (xflags & XMIT_TOP_DIR)
1253 file->flags |= FLAG_TOP_DIR;
1254 file->flags |= FLAG_CONTENT_DIR;
1255 } else if (xflags & XMIT_TOP_DIR)
1256 file->flags |= FLAG_IMPLIED_DIR;
1257 } else if (xflags & XMIT_TOP_DIR) {
1258 if (implied_filter_list.head && is_implied_parent_dir(thisname))
1259 file->flags |= FLAG_IMPLIED_DIR;
1260 else {
1261 in_del_hier = recurse;
1262 del_hier_name_len = F_DEPTH(file) == 0 ? 0 : l1 + l2;
1263 if (relative_paths && del_hier_name_len > 2
1264 && lastname[del_hier_name_len-1] == '.'
1265 && lastname[del_hier_name_len-2] == '/')
1266 del_hier_name_len -= 2;
1267 file->flags |= FLAG_TOP_DIR | FLAG_CONTENT_DIR;
1268 }
1269 } else if (in_del_hier) {
1270 if (!relative_paths || !del_hier_name_len
1271 || (l1 >= del_hier_name_len
1272 && lastname[del_hier_name_len] == '/'))
1273 file->flags |= FLAG_CONTENT_DIR;
1274 else
1275 in_del_hier = 0;
1276 }
1277 }
1278
1279 if (preserve_devices && IS_DEVICE(mode)) {
1280 uint32 *devp = F_RDEV_P(file);
1281 DEV_MAJOR(devp) = major(rdev);
1282 DEV_MINOR(devp) = minor(rdev);
1283 }
1284
1285 #ifdef SUPPORT_LINKS
1286 if (linkname_len) {
1287 bp += basename_len;
1288 if (!preserve_links) {
1289 /* The empty-linkname case allocated above; nothing on
1290 * the wire to read. Just terminate it. */
1291 *bp = '\0';
1292 } else if (first_hlink_ndx >= flist->ndx_start) {
1293 struct file_struct *first = flist->files[first_hlink_ndx - flist->ndx_start];
1294 memcpy(bp, F_SYMLINK(first), linkname_len);
1295 } else {
1296 if (munge_symlinks) {
1297 strlcpy(bp, SYMLINK_PREFIX, linkname_len);
1298 bp += SYMLINK_PREFIX_LEN;
1299 linkname_len -= SYMLINK_PREFIX_LEN;
1300 }
1301 #ifdef ICONV_OPTION
1302 if (sender_symlink_iconv) {
1303 xbuf outbuf, inbuf;
1304
1305 alloc_len = linkname_len;
1306 linkname_len /= 2;
1307
1308 /* Read the symlink data into the end of our double-sized
1309 * buffer and then convert it into the right spot. */
1310 INIT_XBUF(inbuf, bp + alloc_len - linkname_len,
1311 linkname_len - 1, (size_t)-1);
1312 read_sbuf(f, inbuf.buf, inbuf.len);
1313 INIT_XBUF(outbuf, bp, 0, alloc_len);
1314
1315 if (iconvbufs(ic_recv, &inbuf, &outbuf, ICB_INIT) < 0) {
1316 io_error |= IOERR_GENERAL;
1317 rprintf(FERROR_XFER,
1318 "[%s] cannot convert symlink data for: %s (%s)\n",
1319 who_am_i(), full_fname(thisname), strerror(errno));
1320 bp = (char*)file->basename;
1321 *bp++ = '\0';
1322 outbuf.len = 0;
1323 }
1324 bp[outbuf.len] = '\0';
1325 } else
1326 #endif
1327 read_sbuf(f, bp, linkname_len - 1);
1328 if (sanitize_paths && !munge_symlinks && *bp)
1329 sanitize_path(bp, bp, "", lastdir_depth, SP_DEFAULT);
1330 }
1331 }
1332 #endif
1333
1334 #ifdef SUPPORT_HARD_LINKS
1335 if (preserve_hard_links && xflags & XMIT_HLINKED) {
1336 if (protocol_version >= 30) {
1337 if (xflags & XMIT_HLINK_FIRST) {
1338 F_HL_GNUM(file) = flist->ndx_start + flist->used;
1339 } else
1340 F_HL_GNUM(file) = first_hlink_ndx;
1341 } else {
1342 static int32 cnt = 0;
1343 struct ht_int64_node *np;
1344 int64 ino;
1345 int32 ndx;
1346 if (protocol_version < 26) {
1347 dev = read_int(f);
1348 ino = read_int(f);
1349 } else {
1350 if (!(xflags & XMIT_SAME_DEV_pre30))
1351 dev = read_longint(f);
1352 ino = read_longint(f);
1353 }
1354 np = idev_find(dev, ino);
1355 ndx = (int32)(long)np->data; /* is -1 when new */
1356 if (ndx < 0) {
1357 np->data = (void*)(long)cnt;
1358 ndx = cnt++;
1359 }
1360 F_HL_GNUM(file) = ndx;
1361 }
1362 }
1363 #endif
1364
1365 if (always_checksum && (real_ISREG_entry || protocol_version < 28)) {
1366 if (real_ISREG_entry)
1367 bp = F_SUM(file);
1368 else {
1369 /* Prior to 28, we get a useless set of nulls. */
1370 bp = tmp_sum;
1371 }
1372 if (first_hlink_ndx >= flist->ndx_start) {
1373 struct file_struct *first = flist->files[first_hlink_ndx - flist->ndx_start];
1374 memcpy(bp, F_SUM(first), flist_csum_len);
1375 } else
1376 read_buf(f, bp, flist_csum_len);
1377 }
1378
1379 #ifdef SUPPORT_ACLS
1380 if (preserve_acls && !S_ISLNK(mode))
1381 receive_acl(f, file);
1382 #endif
1383 #ifdef SUPPORT_XATTRS
1384 if (preserve_xattrs)
1385 receive_xattr(f, file);
1386 #endif
1387
1388 if (S_ISREG(mode) || S_ISLNK(mode))
1389 stats.total_size += file_length;
1390
1391 return file;
1392 }
1393
1394 /* Create a file_struct for a named file by reading its stat() information
1395 * and performing extensive checks against global options.
1396 *
1397 * Returns a pointer to the new file struct, or NULL if there was an error
1398 * or this file should be excluded.
1399 *
1400 * Note: Any error (here or in send_file_name) that results in the omission of
1401 * an existent source file from the file list should set
1402 * "io_error |= IOERR_GENERAL" to avoid deletion of the file from the
1403 * destination if --delete is on. */
1404 struct file_struct *make_file(const char *fname, struct file_list *flist,
1405 STRUCT_STAT *stp, int flags, int filter_level)
1406 {
1407 static char *lastdir;
1408 static int lastdir_len = -1;
1409 struct file_struct *file;
1410 char thisname[MAXPATHLEN];
1411 char linkname[MAXPATHLEN];
1412 int alloc_len, basename_len, linkname_len;
1413 int extra_len = file_extra_cnt * EXTRA_LEN;
1414 const char *basename;
1415 alloc_pool_t *pool;
1416 STRUCT_STAT st = {0};
1417 char *bp;
1418
1419 if (strlcpy(thisname, fname, sizeof thisname) >= sizeof thisname) {
1420 io_error |= IOERR_GENERAL;
1421 rprintf(FERROR_XFER, "skipping overly long name: %s\n", fname);
1422 return NULL;
1423 }
1424 clean_fname(thisname, 0);
1425 if (sanitize_paths)
1426 sanitize_path(thisname, thisname, "", 0, SP_DEFAULT);
1427
1428 if (stp && (S_ISDIR(stp->st_mode) || IS_MISSING_FILE(*stp))) {
1429 /* This is needed to handle a "symlink/." with a --relative
1430 * dir, or a request to delete a specific file. */
1431 st = *stp;
1432 *linkname = '\0'; /* make IBM code checker happy */
1433 } else if (readlink_stat(thisname, &st, linkname) != 0) {
1434 int save_errno = errno;
1435 /* See if file is excluded before reporting an error. */
1436 if (filter_level != NO_FILTERS
1437 && (is_excluded(thisname, 0, filter_level)
1438 || is_excluded(thisname, 1, filter_level))) {
1439 if (ignore_perishable && save_errno != ENOENT)
1440 non_perishable_cnt++;
1441 return NULL;
1442 }
1443 if (save_errno == ENOENT) {
1444 #ifdef SUPPORT_LINKS
1445 /* When our options tell us to follow a symlink that
1446 * points nowhere, tell the user about the symlink
1447 * instead of giving a "vanished" message. We only
1448 * dereference a symlink if one of the --copy*links
1449 * options was specified, so there's no need for the
1450 * extra lstat() if one of these options isn't on. */
1451 if ((copy_links || copy_unsafe_links || copy_dirlinks)
1452 && x_lstat(thisname, &st, NULL) == 0
1453 && S_ISLNK(st.st_mode)) {
1454 io_error |= IOERR_GENERAL;
1455 rprintf(FERROR_XFER, "symlink has no referent: %s\n",
1456 full_fname(thisname));
1457 } else
1458 #endif
1459 {
1460 enum logcode c = am_daemon && protocol_version < 28
1461 ? FERROR : FWARNING;
1462 io_error |= IOERR_VANISHED;
1463 rprintf(c, "file has vanished: %s\n",
1464 full_fname(thisname));
1465 }
1466 } else {
1467 io_error |= IOERR_GENERAL;
1468 rsyserr(FERROR_XFER, save_errno, "readlink_stat(%s) failed",
1469 full_fname(thisname));
1470 }
1471 return NULL;
1472 } else if (IS_MISSING_FILE(st)) {
1473 io_error |= IOERR_GENERAL;
1474 rprintf(FINFO, "skipping file with bogus (zero) st_mode: %s\n",
1475 full_fname(thisname));
1476 return NULL;
1477 }
1478
1479 if (filter_level == NO_FILTERS)
1480 goto skip_filters;
1481
1482 if (S_ISDIR(st.st_mode)) {
1483 if (!xfer_dirs) {
1484 rprintf(FINFO, "skipping directory %s\n", thisname);
1485 return NULL;
1486 }
1487 /* -x only affects dirs because we need to avoid recursing
1488 * into a mount-point directory, not to avoid copying a
1489 * symlinked file if -L (or similar) was specified. */
1490 if (one_file_system && st.st_dev != filesystem_dev
1491 && BITS_SETnUNSET(flags, FLAG_CONTENT_DIR, FLAG_TOP_DIR)) {
1492 if (one_file_system > 1) {
1493 if (INFO_GTE(MOUNT, 1)) {
1494 rprintf(FINFO,
1495 "[%s] skipping mount-point dir %s\n",
1496 who_am_i(), thisname);
1497 }
1498 return NULL;
1499 }
1500 flags |= FLAG_MOUNT_DIR;
1501 flags &= ~FLAG_CONTENT_DIR;
1502 }
1503 } else
1504 flags &= ~FLAG_CONTENT_DIR;
1505
1506 if (is_excluded(thisname, S_ISDIR(st.st_mode) != 0, filter_level)) {
1507 if (ignore_perishable)
1508 non_perishable_cnt++;
1509 return NULL;
1510 }
1511
1512 if (lp_ignore_nonreadable(module_id)) {
1513 #ifdef SUPPORT_LINKS
1514 if (!S_ISLNK(st.st_mode))
1515 #endif
1516 if (access(thisname, R_OK) != 0)
1517 return NULL;
1518 }
1519
1520 skip_filters:
1521
1522 /* Only divert a directory in the main transfer. */
1523 if (flist) {
1524 if (flist->prev && S_ISDIR(st.st_mode)
1525 && flags & FLAG_DIVERT_DIRS) {
1526 /* Room for parent/sibling/next-child info. */
1527 extra_len += DIRNODE_EXTRA_CNT * EXTRA_LEN;
1528 if (relative_paths)
1529 extra_len += PTR_EXTRA_CNT * EXTRA_LEN;
1530 pool = dir_flist->file_pool;
1531 } else
1532 pool = flist->file_pool;
1533 } else {
1534 #ifdef SUPPORT_ACLS
1535 /* Directories need an extra int32 for the default ACL. */
1536 if (preserve_acls && S_ISDIR(st.st_mode))
1537 extra_len += EXTRA_LEN;
1538 #endif
1539 pool = NULL;
1540 }
1541
1542 if (DEBUG_GTE(FLIST, 2)) {
1543 rprintf(FINFO, "[%s] make_file(%s,*,%d)\n",
1544 who_am_i(), thisname, filter_level);
1545 }
1546
1547 if ((basename = strrchr(thisname, '/')) != NULL) {
1548 int len = basename++ - thisname;
1549 if (len != lastdir_len || !lastdir || memcmp(thisname, lastdir, len) != 0) {
1550 lastdir = new_array(char, len + 1);
1551 memcpy(lastdir, thisname, len);
1552 lastdir[len] = '\0';
1553 lastdir_len = len;
1554 }
1555 } else
1556 basename = thisname;
1557 basename_len = strlen(basename) + 1; /* count the '\0' */
1558
1559 #ifdef SUPPORT_LINKS
1560 linkname_len = S_ISLNK(st.st_mode) ? strlen(linkname) + 1 : 0;
1561 #else
1562 linkname_len = 0;
1563 #endif
1564
1565 if (copy_devices && am_sender && IS_DEVICE(st.st_mode)) {
1566 if (st.st_size == 0) {
1567 int fd = do_open_checklinks(fname);
1568 if (fd >= 0) {
1569 st.st_size = get_device_size(fd, fname);
1570 close(fd);
1571 }
1572 }
1573 st.st_mode = S_IFREG | (st.st_mode & ACCESSPERMS);
1574 st.st_mtime = time(NULL); /* The mtime on the device is not up-to-date, so set it to "now". */
1575 }
1576
1577 #ifdef ST_MTIME_NSEC
1578 {
1579 uint32 nsec = wire_mtime_nsec_from_stat(&st);
1580
1581 if (nsec && protocol_version >= 31)
1582 extra_len += EXTRA_LEN;
1583 }
1584 #endif
1585 #if SIZEOF_CAPITAL_OFF_T >= 8
1586 if (st.st_size > 0xFFFFFFFFu && S_ISREG(st.st_mode))
1587 extra_len += EXTRA_LEN;
1588 #endif
1589
1590 if (always_checksum && am_sender && S_ISREG(st.st_mode)) {
1591 file_checksum(thisname, &st, tmp_sum);
1592 if (sender_keeps_checksum)
1593 extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
1594 }
1595
1596 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1597 /* The sender path historically passes rdev via the tmp_rdev static
1598 * (read by send_file_entry()), so make_file() never reserved
1599 * DEV_EXTRA_CNT in the file_struct itself. But receiver-side callers
1600 * (recv_generator's --inplace --backup back_file, backup.c make_backup)
1601 * hand this struct to set_file_attrs() -> set_stat_xattr(), which reads
1602 * F_RDEV_P(file) under --fake-super. Reserve and populate the slots
1603 * so the struct is self-contained, matching recv_file_entry(). */
1604 if (IS_DEVICE(st.st_mode))
1605 extra_len += DEV_EXTRA_CNT * EXTRA_LEN;
1606 #endif
1607
1608 #if EXTRA_ROUNDING > 0
1609 if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
1610 extra_len = (extra_len | (EXTRA_ROUNDING * EXTRA_LEN)) + EXTRA_LEN;
1611 #endif
1612
1613 alloc_len = FILE_STRUCT_LEN + extra_len + basename_len
1614 + linkname_len;
1615 if (pool)
1616 bp = pool_alloc(pool, alloc_len, "make_file");
1617 else
1618 bp = new_array(char, alloc_len);
1619
1620 memset(bp, 0, extra_len + FILE_STRUCT_LEN);
1621 bp += extra_len;
1622 file = (struct file_struct *)bp;
1623 bp += FILE_STRUCT_LEN;
1624
1625 memcpy(bp, basename, basename_len);
1626
1627 #ifdef SUPPORT_HARD_LINKS
1628 if (preserve_hard_links && flist && flist->prev) {
1629 if (protocol_version >= 28
1630 ? (!S_ISDIR(st.st_mode) && st.st_nlink > 1)
1631 : S_ISREG(st.st_mode)) {
1632 tmp_dev = (int64)st.st_dev;
1633 tmp_ino = (int64)st.st_ino;
1634 } else
1635 tmp_dev = -1;
1636 }
1637 #endif
1638
1639 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1640 if (IS_DEVICE(st.st_mode)) {
1641 uint32 *devp = F_RDEV_P(file);
1642 tmp_rdev = st.st_rdev;
1643 DEV_MAJOR(devp) = major(st.st_rdev);
1644 DEV_MINOR(devp) = minor(st.st_rdev);
1645 st.st_size = 0;
1646 } else if (IS_SPECIAL(st.st_mode))
1647 st.st_size = 0;
1648 #endif
1649
1650 file->flags = flags;
1651 file->modtime = st.st_mtime;
1652 #ifdef ST_MTIME_NSEC
1653 {
1654 uint32 nsec = wire_mtime_nsec_from_stat(&st);
1655
1656 if (nsec && protocol_version >= 31) {
1657 file->flags |= FLAG_MOD_NSEC;
1658 F_MOD_NSEC(file) = nsec;
1659 }
1660 }
1661 #endif
1662 file->len32 = (uint32)st.st_size;
1663 #if SIZEOF_CAPITAL_OFF_T >= 8
1664 if (st.st_size > 0xFFFFFFFFu && S_ISREG(st.st_mode)) {
1665 file->flags |= FLAG_LENGTH64;
1666 F_HIGH_LEN(file) = (uint32)(st.st_size >> 32);
1667 }
1668 #endif
1669 file->mode = st.st_mode;
1670 if (preserve_uid)
1671 F_OWNER(file) = st.st_uid;
1672 if (preserve_gid)
1673 F_GROUP(file) = st.st_gid;
1674 if (am_generator && st.st_uid == our_uid)
1675 file->flags |= FLAG_OWNED_BY_US;
1676 if (atimes_ndx && !S_ISDIR(file->mode))
1677 F_ATIME(file) = st.st_atime;
1678 #ifdef SUPPORT_CRTIMES
1679 if (crtimes_ndx)
1680 F_CRTIME(file) = get_create_time(fname, &st);
1681 #endif
1682
1683 if (basename != thisname)
1684 file->dirname = lastdir;
1685
1686 #ifdef SUPPORT_LINKS
1687 if (linkname_len)
1688 memcpy(bp + basename_len, linkname, linkname_len);
1689 #endif
1690
1691 if (am_sender)
1692 F_PATHNAME(file) = pathname;
1693 else if (!pool)
1694 F_DEPTH(file) = extra_len / EXTRA_LEN;
1695
1696 if (basename_len == 0+1) {
1697 if (!pool)
1698 unmake_file(file);
1699 return NULL;
1700 }
1701
1702 if (sender_keeps_checksum && S_ISREG(st.st_mode))
1703 memcpy(F_SUM(file), tmp_sum, flist_csum_len);
1704
1705 if (unsort_ndx)
1706 F_NDX(file) = stats.num_dirs;
1707
1708 return file;
1709 }
1710
1711 OFF_T get_device_size(int fd, const char *fname)
1712 {
1713 OFF_T off = lseek(fd, 0, SEEK_END);
1714
1715 if (off == (OFF_T) -1) {
1716 rsyserr(FERROR, errno, "failed to get device size via seek: %s", fname);
1717 return 0;
1718 }
1719 if (lseek(fd, 0, SEEK_SET) != 0)
1720 rsyserr(FERROR, errno, "failed to seek device back to start: %s", fname);
1721
1722 return off;
1723 }
1724
1725 /* Only called for temporary file_struct entries created by make_file(). */
1726 void unmake_file(struct file_struct *file)
1727 {
1728 free(REQ_EXTRA(file, F_DEPTH(file)));
1729 }
1730
1731 static struct file_struct *send_file_name(int f, struct file_list *flist,
1732 const char *fname, STRUCT_STAT *stp,
1733 int flags, int filter_level)
1734 {
1735 struct file_struct *file;
1736
1737 file = make_file(fname, flist, stp, flags, filter_level);
1738 if (!file)
1739 return NULL;
1740
1741 if (chmod_modes && !S_ISLNK(file->mode) && file->mode)
1742 file->mode = tweak_mode(file->mode, chmod_modes);
1743
1744 if (f >= 0) {
1745 char fbuf[MAXPATHLEN];
1746 #ifdef SUPPORT_LINKS
1747 const char *symlink_name;
1748 int symlink_len;
1749 #ifdef ICONV_OPTION
1750 char symlink_buf[MAXPATHLEN];
1751 #endif
1752 #endif
1753 #if defined SUPPORT_ACLS || defined SUPPORT_XATTRS
1754 stat_x sx;
1755 init_stat_x(&sx);
1756 #endif
1757
1758 #ifdef SUPPORT_LINKS
1759 if (preserve_links && S_ISLNK(file->mode)) {
1760 symlink_name = F_SYMLINK(file);
1761 symlink_len = strlen(symlink_name);
1762 if (symlink_len == 0) {
1763 io_error |= IOERR_GENERAL;
1764 f_name(file, fbuf);
1765 rprintf(FERROR_XFER,
1766 "skipping symlink with 0-length value: %s\n",
1767 full_fname(fbuf));
1768 return NULL;
1769 }
1770 } else {
1771 symlink_name = NULL;
1772 symlink_len = 0;
1773 }
1774 #endif
1775
1776 #ifdef ICONV_OPTION
1777 if (ic_send != (iconv_t)-1) {
1778 xbuf outbuf, inbuf;
1779
1780 INIT_CONST_XBUF(outbuf, fbuf);
1781
1782 if (file->dirname) {
1783 INIT_XBUF_STRLEN(inbuf, (char*)file->dirname);
1784 outbuf.size -= 2; /* Reserve room for '/' & 1 more char. */
1785 if (iconvbufs(ic_send, &inbuf, &outbuf, ICB_INIT) < 0)
1786 goto convert_error;
1787 outbuf.size += 2;
1788 fbuf[outbuf.len++] = '/';
1789 }
1790
1791 INIT_XBUF_STRLEN(inbuf, (char*)file->basename);
1792 if (iconvbufs(ic_send, &inbuf, &outbuf, ICB_INIT) < 0) {
1793 convert_error:
1794 io_error |= IOERR_GENERAL;
1795 rprintf(FERROR_XFER,
1796 "[%s] cannot convert filename: %s (%s)\n",
1797 who_am_i(), f_name(file, fbuf), strerror(errno));
1798 return NULL;
1799 }
1800 fbuf[outbuf.len] = '\0';
1801
1802 #ifdef SUPPORT_LINKS
1803 if (symlink_len && sender_symlink_iconv) {
1804 INIT_XBUF(inbuf, (char*)symlink_name, symlink_len, (size_t)-1);
1805 INIT_CONST_XBUF(outbuf, symlink_buf);
1806 if (iconvbufs(ic_send, &inbuf, &outbuf, ICB_INIT) < 0) {
1807 io_error |= IOERR_GENERAL;
1808 f_name(file, fbuf);
1809 rprintf(FERROR_XFER,
1810 "[%s] cannot convert symlink data for: %s (%s)\n",
1811 who_am_i(), full_fname(fbuf), strerror(errno));
1812 return NULL;
1813 }
1814 symlink_buf[outbuf.len] = '\0';
1815
1816 symlink_name = symlink_buf;
1817 symlink_len = outbuf.len;
1818 }
1819 #endif
1820 } else
1821 #endif
1822 f_name(file, fbuf);
1823
1824 #ifdef SUPPORT_ACLS
1825 if (preserve_acls && !S_ISLNK(file->mode)) {
1826 sx.st.st_mode = file->mode;
1827 if (get_acl(fname, &sx) < 0) {
1828 io_error |= IOERR_GENERAL;
1829 free_acl(&sx);
1830 return NULL;
1831 }
1832 }
1833 #endif
1834 #ifdef SUPPORT_XATTRS
1835 if (preserve_xattrs) {
1836 sx.st.st_mode = file->mode;
1837 if (get_xattr(fname, -1, &sx) < 0) {
1838 io_error |= IOERR_GENERAL;
1839 #ifdef SUPPORT_ACLS
1840 free_acl(&sx); /* get_acl() above may have loaded one */
1841 #endif
1842 return NULL;
1843 }
1844 }
1845 #endif
1846
1847 send_file_entry(f, fbuf, file,
1848 #ifdef SUPPORT_LINKS
1849 symlink_name, symlink_len,
1850 #endif
1851 flist->used, flist->ndx_start);
1852
1853 #ifdef SUPPORT_ACLS
1854 if (preserve_acls && !S_ISLNK(file->mode)) {
1855 send_acl(f, &sx);
1856 free_acl(&sx);
1857 }
1858 #endif
1859 #ifdef SUPPORT_XATTRS
1860 if (preserve_xattrs) {
1861 F_XATTR(file) = send_xattr(f, &sx);
1862 free_xattr(&sx);
1863 }
1864 #endif
1865 }
1866
1867 maybe_emit_filelist_progress(flist->used + flist_count_offset);
1868
1869 flist_expand(flist, 1);
1870 flist->files[flist->used++] = file;
1871
1872 return file;
1873 }
1874
1875 static void send_if_directory(int f, struct file_list *flist,
1876 struct file_struct *file,
1877 char *fbuf, unsigned int ol,
1878 int flags)
1879 {
1880 char is_dot_dir = fbuf[ol-1] == '.' && (ol == 1 || fbuf[ol-2] == '/');
1881
1882 if (S_ISDIR(file->mode)
1883 && !(file->flags & FLAG_MOUNT_DIR) && f_name(file, fbuf)) {
1884 void *save_filters;
1885 unsigned int len = strlen(fbuf);
1886 if (len > 1 && fbuf[len-1] == '/')
1887 fbuf[--len] = '\0';
1888 save_filters = push_local_filters(fbuf, len);
1889 send_directory(f, flist, fbuf, len, flags);
1890 pop_local_filters(save_filters);
1891 fbuf[ol] = '\0';
1892 if (is_dot_dir)
1893 fbuf[ol-1] = '.';
1894 }
1895 }
1896
1897 static int file_compare(const void *file1, const void *file2)
1898 {
1899 return f_name_cmp(*(struct file_struct **)file1,
1900 *(struct file_struct **)file2);
1901 }
1902
1903 /* The guts of a merge-sort algorithm. This was derived from the glibc
1904 * version, but I (Wayne) changed the merge code to do less copying and
1905 * to require only half the amount of temporary memory. */
1906 static void fsort_tmp(struct file_struct **fp, size_t num,
1907 struct file_struct **tmp)
1908 {
1909 struct file_struct **f1, **f2, **t;
1910 size_t n1, n2;
1911
1912 n1 = num / 2;
1913 n2 = num - n1;
1914 f1 = fp;
1915 f2 = fp + n1;
1916
1917 if (n1 > 1)
1918 fsort_tmp(f1, n1, tmp);
1919 if (n2 > 1)
1920 fsort_tmp(f2, n2, tmp);
1921
1922 while (f_name_cmp(*f1, *f2) <= 0) {
1923 if (!--n1)
1924 return;
1925 f1++;
1926 }
1927
1928 t = tmp;
1929 memcpy(t, f1, n1 * PTR_SIZE);
1930
1931 *f1++ = *f2++, n2--;
1932
1933 while (n1 > 0 && n2 > 0) {
1934 if (f_name_cmp(*t, *f2) <= 0)
1935 *f1++ = *t++, n1--;
1936 else
1937 *f1++ = *f2++, n2--;
1938 }
1939
1940 if (n1 > 0)
1941 memcpy(f1, t, n1 * PTR_SIZE);
1942 }
1943
1944 /* This file-struct sorting routine makes sure that any identical names in
1945 * the file list stay in the same order as they were in the original list.
1946 * This is particularly vital in inc_recurse mode where we expect a sort
1947 * on the flist to match the exact order of a sort on the dir_flist. */
1948 static void fsort(struct file_struct **fp, size_t num)
1949 {
1950 if (num <= 1)
1951 return;
1952
1953 if (use_qsort)
1954 qsort(fp, num, PTR_SIZE, file_compare);
1955 else {
1956 struct file_struct **tmp = new_array(struct file_struct *, (num+1) / 2);
1957 fsort_tmp(fp, num, tmp);
1958 free(tmp);
1959 }
1960 }
1961
1962 /* We take an entire set of sibling dirs from the sorted flist and link them
1963 * into the tree, setting the appropriate parent/child/sibling pointers. */
1964 static void add_dirs_to_tree(int parent_ndx, struct file_list *from_flist,
1965 int dir_cnt)
1966 {
1967 int i;
1968 int32 *dp = NULL;
1969 int32 *parent_dp = parent_ndx < 0 ? NULL
1970 : F_DIR_NODE_P(dir_flist->sorted[parent_ndx]);
1971
1972 /* The sending side is adding entries to dir_flist in sorted order, so sorted & files are the same. */
1973 flist_expand(dir_flist, dir_cnt);
1974 dir_flist->sorted = dir_flist->files;
1975
1976 for (i = 0; dir_cnt; i++) {
1977 struct file_struct *file = from_flist->sorted[i];
1978
1979 if (!S_ISDIR(file->mode))
1980 continue;
1981
1982 dir_flist->files[dir_flist->used++] = file;
1983 dir_cnt--;
1984
1985 if (file->basename[0] == '.' && file->basename[1] == '\0')
1986 continue;
1987
1988 if (dp)
1989 DIR_NEXT_SIBLING(dp) = dir_flist->used - 1;
1990 else if (parent_dp)
1991 DIR_FIRST_CHILD(parent_dp) = dir_flist->used - 1;
1992 else
1993 send_dir_ndx = dir_flist->used - 1;
1994
1995 dp = F_DIR_NODE_P(file);
1996 DIR_PARENT(dp) = parent_ndx;
1997 DIR_FIRST_CHILD(dp) = -1;
1998 }
1999 if (dp)
2000 DIR_NEXT_SIBLING(dp) = -1;
2001 }
2002
2003 static void interpret_stat_error(const char *fname, int is_dir)
2004 {
2005 if (errno == ENOENT) {
2006 io_error |= IOERR_VANISHED;
2007 rprintf(FWARNING, "%s has vanished: %s\n",
2008 is_dir ? "directory" : "file", full_fname(fname));
2009 } else {
2010 io_error |= IOERR_GENERAL;
2011 rsyserr(FERROR_XFER, errno, "link_stat %s failed",
2012 full_fname(fname));
2013 }
2014 }
2015
2016 #if defined HAVE_FDOPENDIR && defined HAVE_DIRFD
2017 /* Open a source directory for scanning confined beneath the transfer root.
2018 * secure_relative_open() does a per-component O_NOFOLLOW walk that refuses a
2019 * parent component raced into a symlink pointing out of the tree; fdopendir()
2020 * then turns the held fd into the DIR* the scan reads. This mirrors the
2021 * sender's confined content open (sender.c): the directory enumeration must be
2022 * confined the same way, or a parent-symlink race (or, for a daemon following
2023 * mode, an in-module symlink to outside) lets the scan enumerate an out-of-tree
2024 * directory and leak its names/metadata/symlink targets. O_DIRECTORY without
2025 * O_NOFOLLOW makes secure_relative_open() follow in-tree directory symlinks
2026 * beneath the anchor and refuse escapes, so this serves both the default
2027 * no-follow scan and a daemon's symlink-following scan (see the caller).
2028 * Returns NULL with errno set on failure, like opendir(). */
2029 static DIR *secure_opendir(const char *fbuf)
2030 {
2031 int dfd, fl;
2032 DIR *d;
2033
2034 if (am_daemon && (!am_chrooted || module_dirlen)
2035 && module_dir && module_dir[0] == '/' && *fbuf != '/' && module_dirfd >= 0
2036 && curr_dir_len >= module_dirlen
2037 && strncmp(curr_dir, module_dir, module_dirlen) == 0
2038 && (curr_dir[module_dirlen] == '\0' || curr_dir[module_dirlen] == '/')) {
2039 /* Daemon: anchor the confined scan at the module root pinned by identity
2040 * at module setup (module_dirfd, opened while the daemon was positioned
2041 * there and still privileged), and walk the module-relative path of the
2042 * scan target beneath it. This re-follows the same in-module path -- so a
2043 * legitimate in-module ".." climb (sub/climb -> ../sibling) or an in-module
2044 * directory symlink is followed, and an escape refused -- without
2045 * re-walking the absolute module path as the dropped uid (the privilege-
2046 * drop EACCES), and without assuming the lexical curr_dir depth matches the
2047 * real cwd (a followed in-module symlink can desync them; anchoring at the
2048 * pinned module root and walking down the logical path is correct either
2049 * way). */
2050 const char *p = curr_dir + module_dirlen;
2051 char modrel[MAXPATHLEN];
2052 while (*p == '/')
2053 p++;
2054 if ((size_t)snprintf(modrel, sizeof modrel, "%s%s%s",
2055 p, *p ? "/" : "", fbuf) >= sizeof modrel) {
2056 errno = ENAMETOOLONG;
2057 return NULL;
2058 }
2059 dfd = secure_relative_open_at(module_dirfd, *modrel ? modrel : ".",
2060 O_RDONLY | O_DIRECTORY, 0);
2061 } else if (*fbuf == '/') {
2062 /* An absolute scan path (an absolute --relative / --files-from name, or a
2063 * "/" transfer root): anchor at "/" -- operator-named, trusted. */
2064 const char *relp = fbuf;
2065 while (*relp == '/')
2066 relp++;
2067 dfd = secure_relative_open("/", relp, O_RDONLY | O_DIRECTORY, 0);
2068 } else {
2069 /* Non-daemon (or chrooted) sender: confine beneath the cwd the sender
2070 * chdir'd into (the transfer root). */
2071 dfd = secure_relative_open(NULL, fbuf, O_RDONLY | O_DIRECTORY, 0);
2072 }
2073
2074 if (dfd < 0)
2075 return NULL;
2076 if ((fl = fcntl(dfd, F_GETFD)) >= 0)
2077 fcntl(dfd, F_SETFD, fl | FD_CLOEXEC);
2078 if (!(d = fdopendir(dfd))) {
2079 int save = errno;
2080 close(dfd);
2081 errno = save;
2082 }
2083 return d;
2084 }
2085 #endif
2086
2087 /* This function is normally called by the sender, but the receiving side also
2088 * calls it from get_dirlist() with f set to -1 so that we just construct the
2089 * file list in memory without sending it over the wire. Also, get_dirlist()
2090 * might call this with f set to -2, which also indicates that local filter
2091 * rules should be ignored. */
2092 static void send_directory(int f, struct file_list *flist, char *fbuf, int len,
2093 int flags)
2094 {
2095 struct dirent *di;
2096 unsigned remainder;
2097 char *p;
2098 DIR *d;
2099 int divert_dirs = (flags & FLAG_DIVERT_DIRS) != 0;
2100 int start = flist->used;
2101 int filter_level = f == -2 ? SERVER_FILTERS : ALL_FILTERS;
2102
2103 assert(flist != NULL);
2104
2105 #if defined HAVE_FDOPENDIR && defined HAVE_DIRFD
2106 /* Confine the enumeration beneath the transfer root. secure_opendir()
2107 * follows in-tree directory symlinks (RESOLVE_BENEATH) and refuses one that
2108 * escapes, so it serves both modes:
2109 * - a daemon/hardened sender (secure_relpath_active()) is confined to the
2110 * module in EVERY mode -- including -L/--copy-dirlinks/--copy-unsafe-
2111 * links, matching the content open (sender_open_copylinks_confined) --
2112 * so a following mode cannot be lured to enumerate outside the module;
2113 * - a non-daemon sender is confined in the default no-follow mode; its
2114 * symlink-following modes intentionally dereference out of the
2115 * operator's own tree, so they keep the legacy opendir().
2116 * f >= 0 is the sender's outgoing scan; get_dirlist() passes f < 0 and keeps
2117 * the legacy opendir(). A module opted out of confinement ("insecure links =
2118 * yes", admin-only) -- or a non-daemon --insecure-links -- uses the legacy
2119 * opendir() too, restoring the pre-hardening enumeration (re-opening the
2120 * escape; documented). */
2121 if (f >= 0 && !symlink_optout_allowed() && (secure_relpath_active()
2122 || !(copy_links || copy_unsafe_links || copy_dirlinks || insecure_links)))
2123 d = secure_opendir(fbuf);
2124 else
2125 d = opendir(fbuf);
2126 #else
2127 d = opendir(fbuf);
2128 #endif
2129 if (!d) {
2130 if (errno == ENOENT) {
2131 if (am_sender) /* Can abuse this for vanished error w/ENOENT: */
2132 interpret_stat_error(fbuf, True);
2133 return;
2134 }
2135 if (errno == ENOTDIR && (flags & FLAG_PERHAPS_DIR))
2136 return;
2137 io_error |= IOERR_GENERAL;
2138 rsyserr(FERROR_XFER, errno, "opendir %s failed", full_fname(fbuf));
2139 return;
2140 }
2141
2142 p = fbuf + len;
2143 if (len == 1 && *fbuf == '/')
2144 remainder = MAXPATHLEN - 1;
2145 else if (len < MAXPATHLEN-1) {
2146 *p++ = '/';
2147 *p = '\0';
2148 remainder = MAXPATHLEN - (len + 1);
2149 } else
2150 remainder = 0;
2151
2152 #ifdef HAVE_DIRFD
2153 /* Let the per-entry stat (readlink_stat -> scan_link_stat) go through the
2154 * already-open directory fd instead of re-resolving fbuf for each name. */
2155 scan_dirfd = dirfd(d);
2156 scan_dir_prefix = fbuf;
2157 scan_dir_prefix_len = len;
2158 #endif
2159
2160 for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
2161 unsigned name_len;
2162 char *dname = d_name(di);
2163 if (dname[0] == '.' && (dname[1] == '\0'
2164 || (dname[1] == '.' && dname[2] == '\0')))
2165 continue;
2166 name_len = strlcpy(p, dname, remainder);
2167 if (name_len >= remainder) {
2168 char save = fbuf[len];
2169 fbuf[len] = '\0';
2170 io_error |= IOERR_GENERAL;
2171 rprintf(FERROR_XFER,
2172 "filename overflows max-path len by %u: %s/%s\n",
2173 name_len - remainder + 1, fbuf, dname);
2174 fbuf[len] = save;
2175 continue;
2176 }
2177 if (dname[0] == '\0') {
2178 io_error |= IOERR_GENERAL;
2179 rprintf(FERROR_XFER,
2180 "cannot send file with empty name in %s\n",
2181 full_fname(fbuf));
2182 continue;
2183 }
2184
2185 send_file_name(f, flist, fbuf, NULL, flags, filter_level);
2186 }
2187
2188 scan_dirfd = -1; /* fbuf is about to be reused / d closed */
2189 scan_dir_prefix = NULL; /* and don't leave the global pointing into fbuf */
2190 scan_dir_prefix_len = 0;
2191 fbuf[len] = '\0';
2192
2193 if (errno) {
2194 io_error |= IOERR_GENERAL;
2195 rsyserr(FERROR_XFER, errno, "readdir(%s)", full_fname(fbuf));
2196 }
2197
2198 closedir(d);
2199
2200 if (f >= 0 && recurse && !divert_dirs) {
2201 int i, end = flist->used - 1;
2202 /* send_if_directory() bumps flist->used, so use "end". */
2203 for (i = start; i <= end; i++)
2204 send_if_directory(f, flist, flist->files[i], fbuf, len, flags);
2205 }
2206 }
2207
2208 static void send_implied_dirs(int f, struct file_list *flist, char *fname,
2209 char *start, char *limit, int flags, char name_type)
2210 {
2211 static char lastpath[MAXPATHLEN] = "";
2212 static int lastpath_len = 0;
2213 static struct file_struct *lastpath_struct = NULL;
2214 struct file_struct *file;
2215 item_list *relname_list;
2216 relnamecache **rnpp;
2217 int len, need_new_dir, depth = 0;
2218 filter_rule_list save_filter_list = filter_list;
2219
2220 flags = (flags | FLAG_IMPLIED_DIR) & ~(FLAG_TOP_DIR | FLAG_CONTENT_DIR);
2221 filter_list.head = filter_list.tail = NULL; /* Don't filter implied dirs. */
2222
2223 if (inc_recurse) {
2224 if (lastpath_struct && F_PATHNAME(lastpath_struct) == pathname
2225 && lastpath_len == limit - fname
2226 && strncmp(lastpath, fname, lastpath_len) == 0)
2227 need_new_dir = 0;
2228 else
2229 need_new_dir = 1;
2230 } else {
2231 char *tp = fname, *lp = lastpath;
2232 /* Skip any initial directories in our path that we
2233 * have in common with lastpath. */
2234 assert(start == fname);
2235 for ( ; ; tp++, lp++) {
2236 if (tp == limit) {
2237 if (*lp == '/' || *lp == '\0')
2238 goto done;
2239 break;
2240 }
2241 if (*lp != *tp)
2242 break;
2243 if (*tp == '/') {
2244 start = tp;
2245 depth++;
2246 }
2247 }
2248 need_new_dir = 1;
2249 }
2250
2251 if (need_new_dir) {
2252 int save_copy_links = copy_links;
2253 int save_xfer_dirs = xfer_dirs;
2254 char *slash;
2255
2256 copy_links = xfer_dirs = 1;
2257
2258 *limit = '\0';
2259
2260 for (slash = start; (slash = strchr(slash+1, '/')) != NULL; ) {
2261 *slash = '\0';
2262 file = send_file_name(f, flist, fname, NULL, flags, ALL_FILTERS);
2263 depth++;
2264 if (!inc_recurse && file && S_ISDIR(file->mode))
2265 change_local_filter_dir(fname, strlen(fname), depth);
2266 *slash = '/';
2267 }
2268
2269 file = send_file_name(f, flist, fname, NULL, flags, ALL_FILTERS);
2270 if (inc_recurse) {
2271 if (file && !S_ISDIR(file->mode))
2272 file = NULL;
2273 lastpath_struct = file;
2274 } else if (file && S_ISDIR(file->mode))
2275 change_local_filter_dir(fname, strlen(fname), ++depth);
2276
2277 strlcpy(lastpath, fname, sizeof lastpath);
2278 lastpath_len = limit - fname;
2279
2280 *limit = '/';
2281
2282 copy_links = save_copy_links;
2283 xfer_dirs = save_xfer_dirs;
2284
2285 if (!inc_recurse)
2286 goto done;
2287 }
2288
2289 if (!lastpath_struct)
2290 goto done; /* dir must have vanished */
2291
2292 len = strlen(limit+1);
2293 memcpy(&relname_list, F_DIR_RELNAMES_P(lastpath_struct), sizeof relname_list);
2294 if (!relname_list) {
2295 relname_list = new0(item_list);
2296 memcpy(F_DIR_RELNAMES_P(lastpath_struct), &relname_list, sizeof relname_list);
2297 }
2298 rnpp = EXPAND_ITEM_LIST(relname_list, relnamecache *, 32);
2299 *rnpp = (relnamecache*)new_array(char, RELNAMECACHE_LEN + len + 1);
2300 (*rnpp)->name_type = name_type;
2301 strlcpy((*rnpp)->fname, limit+1, len + 1);
2302
2303 done:
2304 filter_list = save_filter_list;
2305 }
2306
2307 static NORETURN void fatal_unsafe_io_error(void)
2308 {
2309 /* This (sadly) can only happen when pushing data because
2310 * the sender does not know about what kind of delete
2311 * is in effect on the receiving side when pulling. */
2312 rprintf(FERROR_XFER, "FATAL I/O ERROR: dying to avoid a --delete-%s issue with a pre-3.0.7 receiver.\n",
2313 delete_during == 2 ? "delay" : "during");
2314 exit_cleanup(RERR_UNSUPPORTED);
2315 }
2316
2317 static void send1extra(int f, struct file_struct *file, struct file_list *flist)
2318 {
2319 char fbuf[MAXPATHLEN];
2320 item_list *relname_list;
2321 int len, dlen, flags = FLAG_DIVERT_DIRS | FLAG_CONTENT_DIR;
2322 size_t j;
2323
2324 if (!f_name(file, fbuf))
2325 return;
2326 dlen = strlen(fbuf);
2327
2328 if (!change_pathname(file, NULL, 0))
2329 exit_cleanup(RERR_FILESELECT);
2330
2331 change_local_filter_dir(fbuf, dlen, send_dir_depth);
2332
2333 if (file->flags & FLAG_CONTENT_DIR) {
2334 if (one_file_system) {
2335 STRUCT_STAT st;
2336 if (link_stat(fbuf, &st, copy_dirlinks) != 0) {
2337 interpret_stat_error(fbuf, True);
2338 return;
2339 }
2340 filesystem_dev = st.st_dev;
2341 }
2342 send_directory(f, flist, fbuf, dlen, flags);
2343 }
2344
2345 if (!relative_paths)
2346 return;
2347
2348 memcpy(&relname_list, F_DIR_RELNAMES_P(file), sizeof relname_list);
2349 if (!relname_list)
2350 return;
2351
2352 for (j = 0; j < relname_list->count; j++) {
2353 char *slash;
2354 relnamecache *rnp = ((relnamecache**)relname_list->items)[j];
2355 char name_type = rnp->name_type;
2356
2357 fbuf[dlen] = '/';
2358 len = strlcpy(fbuf + dlen + 1, rnp->fname, sizeof fbuf - dlen - 1);
2359 free(rnp);
2360 if (len >= (int)sizeof fbuf)
2361 continue; /* Impossible... */
2362
2363 slash = strchr(fbuf+dlen+1, '/');
2364 if (slash) {
2365 send_implied_dirs(f, flist, fbuf, fbuf+dlen+1, slash, flags, name_type);
2366 continue;
2367 }
2368
2369 if (name_type != NORMAL_NAME) {
2370 STRUCT_STAT st = {0};
2371
2372 if (name_type != MISSING_NAME && link_stat(fbuf, &st, 1) != 0) {
2373 interpret_stat_error(fbuf, True);
2374 continue;
2375 }
2376 send_file_name(f, flist, fbuf, &st, FLAG_TOP_DIR | flags, ALL_FILTERS);
2377 } else
2378 send_file_name(f, flist, fbuf, NULL, FLAG_TOP_DIR | flags, ALL_FILTERS);
2379 }
2380
2381 free(relname_list);
2382 }
2383
2384 static void write_end_of_flist(int f, int send_io_error)
2385 {
2386 if (xfer_flags_as_varint) {
2387 write_varint(f, 0);
2388 write_varint(f, send_io_error ? io_error : 0);
2389 } else if (send_io_error) {
2390 write_shortint(f, XMIT_EXTENDED_FLAGS|XMIT_IO_ERROR_ENDLIST);
2391 write_varint(f, io_error);
2392 } else
2393 write_byte(f, 0);
2394 }
2395
2396 void send_extra_file_list(int f, int at_least)
2397 {
2398 struct file_list *flist;
2399 int64 start_write;
2400 uint16 prev_flags;
2401 int save_io_error = io_error;
2402
2403 if (flist_eof)
2404 return;
2405
2406 if (at_least < 0)
2407 at_least = file_total - file_old_total + 1;
2408
2409 /* Keep sending data until we have the requested number of
2410 * files in the upcoming file-lists. */
2411 while (file_total - file_old_total < at_least) {
2412 struct file_struct *file = dir_flist->sorted[send_dir_ndx];
2413 int dir_ndx, dstart = stats.num_dirs;
2414 const char *pathname = F_PATHNAME(file);
2415 int32 *dp;
2416
2417 flist = flist_new(0, "send_extra_file_list");
2418 start_write = stats.total_written;
2419
2420 if (unsort_ndx)
2421 dir_ndx = F_NDX(file);
2422 else
2423 dir_ndx = send_dir_ndx;
2424 write_ndx(f, NDX_FLIST_OFFSET - dir_ndx);
2425 flist->parent_ndx = send_dir_ndx; /* the sending side must remember the sorted ndx value */
2426
2427 send1extra(f, file, flist);
2428 prev_flags = file->flags;
2429 dp = F_DIR_NODE_P(file);
2430
2431 /* If there are any duplicate directory names that follow, we
2432 * send all the dirs together in one file-list. The dir_flist
2433 * tree links all the child subdirs onto the last dup dir. */
2434 while ((dir_ndx = DIR_NEXT_SIBLING(dp)) >= 0
2435 && dir_flist->sorted[dir_ndx]->flags & FLAG_DUPLICATE) {
2436 send_dir_ndx = dir_ndx;
2437 file = dir_flist->sorted[dir_ndx];
2438 /* Try to avoid some duplicate scanning of identical dirs. */
2439 if (F_PATHNAME(file) == pathname && prev_flags & FLAG_CONTENT_DIR)
2440 file->flags &= ~FLAG_CONTENT_DIR;
2441 send1extra(f, file, flist);
2442 prev_flags = file->flags;
2443 dp = F_DIR_NODE_P(file);
2444 }
2445
2446 if (io_error == save_io_error || ignore_errors)
2447 write_end_of_flist(f, 0);
2448 else if (use_safe_inc_flist)
2449 write_end_of_flist(f, 1);
2450 else {
2451 if (delete_during)
2452 fatal_unsafe_io_error();
2453 write_end_of_flist(f, 0);
2454 }
2455
2456 if (need_unsorted_flist) {
2457 flist->sorted = new_array(struct file_struct *, flist->used);
2458 memcpy(flist->sorted, flist->files, flist->used * PTR_SIZE);
2459 } else
2460 flist->sorted = flist->files;
2461
2462 flist_sort_and_clean(flist, 0);
2463
2464 add_dirs_to_tree(send_dir_ndx, flist, stats.num_dirs - dstart);
2465 flist_done_allocating(flist);
2466
2467 file_total += flist->used;
2468 stats.flist_size += stats.total_written - start_write;
2469 stats.num_files += flist->used;
2470 if (DEBUG_GTE(FLIST, 3))
2471 output_flist(flist);
2472
2473 if (DIR_FIRST_CHILD(dp) >= 0) {
2474 send_dir_ndx = DIR_FIRST_CHILD(dp);
2475 send_dir_depth++;
2476 } else {
2477 while (DIR_NEXT_SIBLING(dp) < 0) {
2478 if ((send_dir_ndx = DIR_PARENT(dp)) < 0) {
2479 write_ndx(f, NDX_FLIST_EOF);
2480 flist_eof = 1;
2481 if (DEBUG_GTE(FLIST, 3))
2482 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
2483 change_local_filter_dir(NULL, 0, 0);
2484 goto finish;
2485 }
2486 send_dir_depth--;
2487 file = dir_flist->sorted[send_dir_ndx];
2488 dp = F_DIR_NODE_P(file);
2489 }
2490 send_dir_ndx = DIR_NEXT_SIBLING(dp);
2491 }
2492 }
2493
2494 finish:
2495 if (io_error != save_io_error && protocol_version == 30 && !ignore_errors)
2496 send_msg_int(MSG_IO_ERROR, io_error);
2497 }
2498
2499 struct file_list *send_file_list(int f, int argc, char *argv[])
2500 {
2501 static const char *lastdir;
2502 static int lastdir_len = -1;
2503 int len, dirlen;
2504 STRUCT_STAT st = {0};
2505 char *p, *dir;
2506 struct file_list *flist;
2507 struct timeval start_tv, end_tv;
2508 int64 start_write;
2509 int use_ff_fd = 0;
2510 int disable_buffering, reenable_multiplex = -1;
2511 int flags = recurse ? FLAG_CONTENT_DIR : 0;
2512 int reading_remotely = filesfrom_host != NULL;
2513 int rl_flags = (reading_remotely ? 0 : RL_DUMP_COMMENTS)
2514 #ifdef ICONV_OPTION
2515 | (filesfrom_convert ? RL_CONVERT : 0)
2516 #endif
2517 | (eol_nulls || reading_remotely ? RL_EOL_NULLS : 0);
2518 int implied_dot_dir = 0;
2519
2520 rprintf(FLOG, "building file list\n");
2521 if (show_filelist_progress)
2522 start_filelist_progress("building file list");
2523 else if (inc_recurse && INFO_GTE(FLIST, 1) && !am_server)
2524 rprintf(FCLIENT, "sending incremental file list\n");
2525
2526 start_write = stats.total_written;
2527 gettimeofday(&start_tv, NULL);
2528
2529 if (relative_paths && protocol_version >= 30)
2530 implied_dirs = 1; /* We send flagged implied dirs */
2531
2532 #ifdef SUPPORT_HARD_LINKS
2533 if (preserve_hard_links && protocol_version >= 30 && !cur_flist)
2534 init_hard_links();
2535 #endif
2536
2537 flist = cur_flist = flist_new(0, "send_file_list");
2538 flist_expand(flist, FLIST_START_LARGE);
2539 if (inc_recurse) {
2540 dir_flist = flist_new(FLIST_TEMP, "send_file_list");
2541 flist_expand(dir_flist, FLIST_START_LARGE);
2542 flags |= FLAG_DIVERT_DIRS;
2543 } else
2544 dir_flist = cur_flist;
2545
2546 disable_buffering = io_start_buffering_out(f);
2547 if (filesfrom_fd >= 0) {
2548 if (argv[0] && !change_dir(argv[0], CD_NORMAL)) {
2549 rsyserr(FERROR_XFER, errno, "change_dir %s failed",
2550 full_fname(argv[0]));
2551 exit_cleanup(RERR_FILESELECT);
2552 }
2553 if (protocol_version < 31) {
2554 /* Older protocols send the files-from data w/o packaging
2555 * it in multiplexed I/O packets, so temporarily switch
2556 * to buffered I/O to match this behavior. */
2557 reenable_multiplex = io_end_multiplex_in(MPLX_TO_BUFFERED);
2558 }
2559 use_ff_fd = 1;
2560 }
2561
2562 if (!orig_dir)
2563 orig_dir = strdup(curr_dir);
2564
2565 while (1) {
2566 char fbuf[MAXPATHLEN], *fn, name_type;
2567
2568 if (use_ff_fd) {
2569 if (read_line(filesfrom_fd, fbuf, sizeof fbuf, rl_flags) == 0)
2570 break;
2571 sanitize_path(fbuf, fbuf, "", 0, SP_KEEP_DOT_DIRS);
2572 } else {
2573 if (argc-- == 0)
2574 break;
2575 strlcpy(fbuf, *argv++, MAXPATHLEN);
2576 if (sanitize_paths)
2577 sanitize_path(fbuf, fbuf, "", 0, SP_KEEP_DOT_DIRS);
2578 }
2579
2580 len = strlen(fbuf);
2581 if (relative_paths) {
2582 /* We clean up fbuf below. */
2583 name_type = NORMAL_NAME;
2584 } else if (!len || fbuf[len - 1] == '/') {
2585 if (len == 2 && fbuf[0] == '.') {
2586 /* Turn "./" into just "." rather than "./." */
2587 fbuf[--len] = '\0';
2588 } else {
2589 if (len + 1 >= MAXPATHLEN)
2590 overflow_exit("send_file_list");
2591 fbuf[len++] = '.';
2592 fbuf[len] = '\0';
2593 }
2594 name_type = DOTDIR_NAME;
2595 } else if (len > 1 && fbuf[len-1] == '.' && fbuf[len-2] == '.'
2596 && (len == 2 || fbuf[len-3] == '/')) {
2597 if (len + 2 >= MAXPATHLEN)
2598 overflow_exit("send_file_list");
2599 fbuf[len++] = '/';
2600 fbuf[len++] = '.';
2601 fbuf[len] = '\0';
2602 name_type = DOTDIR_NAME;
2603 } else if (fbuf[len-1] == '.' && (len == 1 || fbuf[len-2] == '/'))
2604 name_type = DOTDIR_NAME;
2605 else
2606 name_type = NORMAL_NAME;
2607
2608 dir = NULL;
2609
2610 if (!relative_paths) {
2611 p = strrchr(fbuf, '/');
2612 if (p) {
2613 *p = '\0';
2614 if (p == fbuf)
2615 dir = "/";
2616 else
2617 dir = fbuf;
2618 len -= p - fbuf + 1;
2619 fn = p + 1;
2620 } else
2621 fn = fbuf;
2622 } else {
2623 if ((p = strstr(fbuf, "/./")) != NULL) {
2624 *p = '\0';
2625 if (p == fbuf)
2626 dir = "/";
2627 else {
2628 dir = fbuf;
2629 clean_fname(dir, 0);
2630 }
2631 fn = p + 3;
2632 while (*fn == '/')
2633 fn++;
2634 if (!*fn)
2635 *--fn = '\0'; /* ensure room for '.' */
2636 } else
2637 fn = fbuf;
2638 /* A leading ./ can be used in relative mode to affect
2639 * the dest dir without its name being in the path. */
2640 if (*fn == '.' && fn[1] == '/' && fn[2] && !implied_dot_dir)
2641 implied_dot_dir = -1;
2642 len = clean_fname(fn, CFN_KEEP_TRAILING_SLASH
2643 | CFN_DROP_TRAILING_DOT_DIR);
2644 if (len == 1) {
2645 if (fn[0] == '/') {
2646 fn = "/.";
2647 len = 2;
2648 name_type = DOTDIR_NAME;
2649 } else if (fn[0] == '.')
2650 name_type = DOTDIR_NAME;
2651 } else if (fn[len-1] == '/') {
2652 fn[--len] = '\0';
2653 if (len == 1 && *fn == '.')
2654 name_type = DOTDIR_NAME;
2655 else
2656 name_type = SLASH_ENDING_NAME;
2657 }
2658 /* Reject a ".." dir in the active part of the path. */
2659 for (p = fn; (p = strstr(p, "..")) != NULL; p += 2) {
2660 if ((p[2] == '/' || p[2] == '\0')
2661 && (p == fn || p[-1] == '/')) {
2662 rprintf(FERROR,
2663 "found \"..\" dir in relative path: %s\n",
2664 fn);
2665 exit_cleanup(RERR_SYNTAX);
2666 }
2667 }
2668 }
2669
2670 if (!*fn) {
2671 len = 1;
2672 fn = ".";
2673 name_type = DOTDIR_NAME;
2674 }
2675
2676 dirlen = dir ? strlen(dir) : 0;
2677 if (dirlen != lastdir_len || (dirlen && memcmp(lastdir, dir, dirlen) != 0)) {
2678 if (!change_pathname(NULL, dir, -dirlen))
2679 goto bad_path;
2680 lastdir = pathname;
2681 lastdir_len = pathname_len;
2682 } else if (!change_pathname(NULL, lastdir, lastdir_len)) {
2683 bad_path:
2684 if (implied_dot_dir < 0)
2685 implied_dot_dir = 0;
2686 continue;
2687 }
2688
2689 if (implied_dot_dir < 0) {
2690 implied_dot_dir = 1;
2691 send_file_name(f, flist, ".", NULL, (flags | FLAG_IMPLIED_DIR) & ~FLAG_CONTENT_DIR, ALL_FILTERS);
2692 }
2693
2694 if (fn != fbuf)
2695 memmove(fbuf, fn, len + 1);
2696
2697 if (link_stat(fbuf, &st, copy_dirlinks || name_type != NORMAL_NAME) != 0
2698 || (name_type != DOTDIR_NAME && is_excluded(fbuf, S_ISDIR(st.st_mode) != 0, SERVER_FILTERS))
2699 || (relative_paths && path_is_daemon_excluded(fbuf, 1))) {
2700 if (errno != ENOENT || missing_args == 0) {
2701 /* This is a transfer error, but inhibit deletion
2702 * only if we might be omitting an existing file. */
2703 if (errno != ENOENT)
2704 io_error |= IOERR_GENERAL;
2705 rsyserr(FERROR_XFER, errno, "link_stat %s failed",
2706 full_fname(fbuf));
2707 continue;
2708 } else if (missing_args == 1) {
2709 /* Just ignore the arg. */
2710 continue;
2711 } else /* (missing_args == 2) */ {
2712 /* Send the arg as a "missing" entry with
2713 * mode 0, which tells the generator to delete it. */
2714 memset(&st, 0, sizeof st);
2715 }
2716 }
2717
2718 /* A dot-dir should not be excluded! */
2719 if (name_type != DOTDIR_NAME && st.st_mode != 0
2720 && is_excluded(fbuf, S_ISDIR(st.st_mode) != 0, ALL_FILTERS))
2721 continue;
2722
2723 if (S_ISDIR(st.st_mode) && !xfer_dirs) {
2724 rprintf(FINFO, "skipping directory %s\n", fbuf);
2725 continue;
2726 }
2727
2728 if (inc_recurse && relative_paths && *fbuf) {
2729 if ((p = strchr(fbuf+1, '/')) != NULL) {
2730 if (p - fbuf == 1 && *fbuf == '.') {
2731 if ((fn = strchr(p+1, '/')) != NULL)
2732 p = fn;
2733 } else
2734 fn = p;
2735 send_implied_dirs(f, flist, fbuf, fbuf, p, flags,
2736 IS_MISSING_FILE(st) ? MISSING_NAME : name_type);
2737 if (fn == p)
2738 continue;
2739 }
2740 } else if (implied_dirs && (p=strrchr(fbuf,'/')) && p != fbuf) {
2741 /* Send the implied directories at the start of the
2742 * source spec, so we get their permissions right. */
2743 send_implied_dirs(f, flist, fbuf, fbuf, p, flags, 0);
2744 }
2745
2746 if (one_file_system)
2747 filesystem_dev = st.st_dev;
2748
2749 if (recurse || (xfer_dirs && name_type != NORMAL_NAME)) {
2750 struct file_struct *file;
2751 file = send_file_name(f, flist, fbuf, &st,
2752 FLAG_TOP_DIR | FLAG_CONTENT_DIR | flags,
2753 NO_FILTERS);
2754 if (!file)
2755 continue;
2756 if (inc_recurse) {
2757 if (name_type == DOTDIR_NAME) {
2758 if (send_dir_depth < 0) {
2759 send_dir_depth = 0;
2760 change_local_filter_dir(fbuf, len, send_dir_depth);
2761 }
2762 send_directory(f, flist, fbuf, len, flags);
2763 }
2764 } else
2765 send_if_directory(f, flist, file, fbuf, len, flags);
2766 } else
2767 send_file_name(f, flist, fbuf, &st, flags, NO_FILTERS);
2768 }
2769
2770 if (reenable_multiplex >= 0)
2771 io_start_multiplex_in(reenable_multiplex);
2772
2773 gettimeofday(&end_tv, NULL);
2774 stats.flist_buildtime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
2775 + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
2776 if (stats.flist_buildtime == 0)
2777 stats.flist_buildtime = 1;
2778 start_tv = end_tv;
2779
2780 /* Indicate end of file list */
2781 if (io_error == 0 || ignore_errors)
2782 write_end_of_flist(f, 0);
2783 else if (use_safe_inc_flist)
2784 write_end_of_flist(f, 1);
2785 else {
2786 if (delete_during && inc_recurse)
2787 fatal_unsafe_io_error();
2788 write_end_of_flist(f, 0);
2789 }
2790
2791 #ifdef SUPPORT_HARD_LINKS
2792 if (preserve_hard_links && protocol_version >= 30 && !inc_recurse)
2793 idev_destroy();
2794 #endif
2795
2796 if (show_filelist_progress)
2797 finish_filelist_progress(flist);
2798
2799 gettimeofday(&end_tv, NULL);
2800 stats.flist_xfertime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
2801 + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
2802
2803 /* When converting names, both sides keep an unsorted file-list array
2804 * because the names will differ on the sending and receiving sides
2805 * (both sides will use the unsorted index number for each item). */
2806
2807 /* Sort the list without removing any duplicates. This allows the
2808 * receiving side to ask for whatever name it kept. For incremental
2809 * recursion mode, the sender marks duplicate dirs so that it can
2810 * send them together in a single file-list. */
2811 if (need_unsorted_flist) {
2812 flist->sorted = new_array(struct file_struct *, flist->used);
2813 memcpy(flist->sorted, flist->files, flist->used * PTR_SIZE);
2814 } else
2815 flist->sorted = flist->files;
2816 flist_sort_and_clean(flist, 0);
2817 file_total += flist->used;
2818 file_old_total += flist->used;
2819
2820 if (numeric_ids <= 0 && !inc_recurse)
2821 send_id_lists(f);
2822
2823 /* send the io_error flag */
2824 if (protocol_version < 30)
2825 write_int(f, ignore_errors ? 0 : io_error);
2826 else if (!use_safe_inc_flist && io_error && !ignore_errors)
2827 send_msg_int(MSG_IO_ERROR, io_error);
2828
2829 if (disable_buffering)
2830 io_end_buffering_out(IOBUF_FREE_BUFS);
2831
2832 stats.flist_size = stats.total_written - start_write;
2833 stats.num_files = flist->used;
2834
2835 if (DEBUG_GTE(FLIST, 3))
2836 output_flist(flist);
2837
2838 if (DEBUG_GTE(FLIST, 2))
2839 rprintf(FINFO, "send_file_list done\n");
2840
2841 if (inc_recurse) {
2842 send_dir_depth = 1;
2843 add_dirs_to_tree(-1, flist, stats.num_dirs);
2844 if (!file_total || strcmp(flist->sorted[flist->low]->basename, ".") != 0)
2845 flist->parent_ndx = -1;
2846 flist_done_allocating(flist);
2847 if (send_dir_ndx < 0) {
2848 write_ndx(f, NDX_FLIST_EOF);
2849 flist_eof = 1;
2850 if (DEBUG_GTE(FLIST, 3))
2851 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
2852 }
2853 else if (file_total == 1) {
2854 /* If we're creating incremental file-lists and there
2855 * was just 1 item in the first file-list, send 1 more
2856 * file-list to check if this is a 1-file xfer. */
2857 send_extra_file_list(f, 1);
2858 }
2859 } else {
2860 flist_eof = 1;
2861 if (DEBUG_GTE(FLIST, 3))
2862 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
2863 }
2864
2865 return flist;
2866 }
2867
2868 struct file_list *recv_file_list(int f, int dir_ndx)
2869 {
2870 const char *good_dirname = NULL;
2871 struct file_list *flist;
2872 int dstart, flags;
2873 int64 start_read;
2874
2875 if (!first_flist) {
2876 if (show_filelist_progress)
2877 start_filelist_progress("receiving file list");
2878 else if (inc_recurse && INFO_GTE(FLIST, 1) && !am_server)
2879 rprintf(FCLIENT, "receiving incremental file list\n");
2880 rprintf(FLOG, "receiving file list\n");
2881 if (usermap)
2882 parse_name_map(usermap, True);
2883 if (groupmap)
2884 parse_name_map(groupmap, False);
2885 }
2886
2887 start_read = stats.total_read;
2888
2889 #ifdef SUPPORT_HARD_LINKS
2890 if (preserve_hard_links && !first_flist)
2891 init_hard_links();
2892 #endif
2893
2894 if (inc_recurse && dir_ndx >= 0) {
2895 if (!first_flist) {
2896 /* All flists have already been freed via the NDX_DONE
2897 * chain, so dir_flist is stale: its files[] entries
2898 * point into a destroyed pool. A sub-flist marker now
2899 * is a protocol violation (and would otherwise UAF the
2900 * stale dir entry below, then deref an uninitialised
2901 * slot in the freshly reset dir_flist further down). */
2902 rprintf(FERROR_XFER,
2903 "rsync: refusing sub-flist after final flist was freed\n");
2904 exit_cleanup(RERR_PROTOCOL);
2905 }
2906 if (dir_ndx >= dir_flist->used) {
2907 rprintf(FERROR_XFER, "rsync: refusing invalid dir_ndx %u >= %u\n", dir_ndx, dir_flist->used);
2908 exit_cleanup(RERR_PROTOCOL);
2909 }
2910 struct file_struct *file = dir_flist->files[dir_ndx];
2911 if (!F_IS_ACTIVE(file)) {
2912 /* flist_sort_and_clean() can clear_file() a directory
2913 * entry that was a duplicate or otherwise pruned, but
2914 * the cleared file_struct stays in dir_flist. A peer
2915 * that then sends a sub-flist for that slot would make
2916 * f_name() return NULL into the dirname strcmp() below. */
2917 rprintf(FERROR_XFER,
2918 "rsync: refusing flist for cleared dir_ndx %d\n",
2919 dir_ndx);
2920 exit_cleanup(RERR_PROTOCOL);
2921 }
2922 if (file->flags & FLAG_GOT_DIR_FLIST) {
2923 rprintf(FERROR_XFER, "rsync: refusing malicious duplicate flist for dir %d\n", dir_ndx);
2924 exit_cleanup(RERR_PROTOCOL);
2925 }
2926 file->flags |= FLAG_GOT_DIR_FLIST;
2927 }
2928
2929 flist = flist_new(0, "recv_file_list");
2930 flist_expand(flist, FLIST_START_LARGE);
2931
2932 if (inc_recurse) {
2933 if (flist->ndx_start == 1) {
2934 dir_flist = flist_new(FLIST_TEMP, "recv_file_list");
2935 flist_expand(dir_flist, FLIST_START_LARGE);
2936 }
2937 dstart = dir_flist->used;
2938 } else {
2939 dir_flist = flist;
2940 dstart = 0;
2941 }
2942
2943 while (1) {
2944 struct file_struct *file;
2945
2946 if (xfer_flags_as_varint) {
2947 if ((flags = read_varint(f)) == 0) {
2948 int err = read_varint(f);
2949 if (!ignore_errors)
2950 io_error |= err & IOERR_VALID_MASK;
2951 break;
2952 }
2953 } else {
2954 if ((flags = read_byte(f)) == 0)
2955 break;
2956
2957 if (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS))
2958 flags |= read_byte(f) << 8;
2959
2960 if (flags == (XMIT_EXTENDED_FLAGS|XMIT_IO_ERROR_ENDLIST)) {
2961 int err;
2962 if (!use_safe_inc_flist) {
2963 rprintf(FERROR, "Invalid flist flag: %x\n", flags);
2964 exit_cleanup(RERR_PROTOCOL);
2965 }
2966 err = read_varint(f);
2967 if (!ignore_errors)
2968 io_error |= err & IOERR_VALID_MASK;
2969 break;
2970 }
2971 }
2972
2973 flist_expand(flist, 1);
2974 file = recv_file_entry(f, flist, flags);
2975
2976 if (inc_recurse) {
2977 static const char empty_dir[] = "\0";
2978 const char *cur_dir = file->dirname ? file->dirname : empty_dir;
2979 if (relative_paths && *cur_dir == '/')
2980 cur_dir++;
2981 if (cur_dir != good_dirname) {
2982 const char *d = dir_ndx >= 0 ? f_name(dir_flist->files[dir_ndx], NULL) : empty_dir;
2983 if (!d || strcmp(cur_dir, d) != 0) {
2984 rprintf(FERROR,
2985 "ABORTING due to invalid path from sender: %s/%s\n",
2986 cur_dir, file->basename);
2987 exit_cleanup(RERR_UNSUPPORTED);
2988 }
2989 good_dirname = cur_dir;
2990 }
2991 }
2992
2993 if (S_ISREG(file->mode)) {
2994 /* Already counted */
2995 } else if (S_ISDIR(file->mode)) {
2996 if (inc_recurse) {
2997 flist_expand(dir_flist, 1);
2998 dir_flist->files[dir_flist->used++] = file;
2999 }
3000 stats.num_dirs++;
3001 } else if (S_ISLNK(file->mode))
3002 stats.num_symlinks++;
3003 else if (IS_DEVICE(file->mode))
3004 stats.num_devices++;
3005 else
3006 stats.num_specials++;
3007
3008 flist->files[flist->used++] = file;
3009
3010 maybe_emit_filelist_progress(flist->used);
3011
3012 if (DEBUG_GTE(FLIST, 2)) {
3013 char *name = f_name(file, NULL);
3014 rprintf(FINFO, "recv_file_name(%s)\n", NS(name));
3015 }
3016 }
3017 file_total += flist->used;
3018
3019 if (DEBUG_GTE(FLIST, 2))
3020 rprintf(FINFO, "received %d names\n", flist->used);
3021
3022 if (show_filelist_progress)
3023 finish_filelist_progress(flist);
3024
3025 if (need_unsorted_flist) {
3026 /* Create an extra array of index pointers that we can sort for
3027 * the generator's use (for wading through the files in sorted
3028 * order and for calling flist_find()). We keep the "files"
3029 * list unsorted for our exchange of index numbers with the
3030 * other side (since their names may not sort the same). */
3031 flist->sorted = new_array(struct file_struct *, flist->used);
3032 memcpy(flist->sorted, flist->files, flist->used * PTR_SIZE);
3033 if (inc_recurse && dir_flist->used > dstart) {
3034 static int dir_flist_malloced = 0;
3035 if (dir_flist_malloced < dir_flist->malloced) {
3036 dir_flist->sorted = realloc_array(dir_flist->sorted,
3037 struct file_struct *,
3038 dir_flist->malloced);
3039 dir_flist_malloced = dir_flist->malloced;
3040 }
3041 memcpy(dir_flist->sorted + dstart, dir_flist->files + dstart,
3042 (dir_flist->used - dstart) * PTR_SIZE);
3043 fsort(dir_flist->sorted + dstart, dir_flist->used - dstart);
3044 }
3045 } else {
3046 flist->sorted = flist->files;
3047 if (inc_recurse && dir_flist->used > dstart) {
3048 dir_flist->sorted = dir_flist->files;
3049 fsort(dir_flist->sorted + dstart, dir_flist->used - dstart);
3050 }
3051 }
3052
3053 if (inc_recurse)
3054 flist_done_allocating(flist);
3055 else if (f >= 0) {
3056 recv_id_list(f, flist);
3057 flist_eof = 1;
3058 if (DEBUG_GTE(FLIST, 3))
3059 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
3060 }
3061
3062 /* The --relative option sends paths with a leading slash, so we need
3063 * to specify the strip_root option here. We rejected leading slashes
3064 * for a non-relative transfer in recv_file_entry(). */
3065 flist_sort_and_clean(flist, relative_paths);
3066
3067 if (protocol_version < 30) {
3068 /* Recv the io_error flag */
3069 int err = read_int(f);
3070 if (!ignore_errors)
3071 io_error |= err & IOERR_VALID_MASK;
3072 } else if (inc_recurse && flist->ndx_start == 1) {
3073 /* The first inc_recurse flist has no parent in dir_flist; a
3074 * malicious peer can send a "." entry whose mode is not a
3075 * directory, so it never lands in dir_flist (used stays 0) yet
3076 * the basename test below still passes. That left parent_ndx at
3077 * its default 0 and the consumers dereferenced dir_flist->files[0]
3078 * = uninitialised heap. Require dir_flist to actually hold an
3079 * entry before trusting index 0. */
3080 if (!file_total || !dir_flist->used
3081 || strcmp(flist->sorted[flist->low]->basename, ".") != 0)
3082 flist->parent_ndx = -1;
3083 }
3084
3085 if (DEBUG_GTE(FLIST, 3))
3086 output_flist(flist);
3087
3088 if (DEBUG_GTE(FLIST, 2))
3089 rprintf(FINFO, "recv_file_list done\n");
3090
3091 stats.flist_size += stats.total_read - start_read;
3092 stats.num_files += flist->used;
3093
3094 return flist;
3095 }
3096
3097 /* This is only used once by the receiver if the very first file-list
3098 * has exactly one item in it. */
3099 void recv_additional_file_list(int f)
3100 {
3101 struct file_list *flist;
3102 int ndx = read_ndx(f);
3103 if (ndx == NDX_FLIST_EOF) {
3104 flist_eof = 1;
3105 if (DEBUG_GTE(FLIST, 3))
3106 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
3107 change_local_filter_dir(NULL, 0, 0);
3108 } else {
3109 ndx = NDX_FLIST_OFFSET - ndx;
3110 if (ndx < 0 || ndx >= dir_flist->used) {
3111 ndx = NDX_FLIST_OFFSET - ndx;
3112 rprintf(FERROR,
3113 "[%s] Invalid dir index: %d (%d - %d)\n",
3114 who_am_i(), ndx, NDX_FLIST_OFFSET,
3115 NDX_FLIST_OFFSET - dir_flist->used + 1);
3116 exit_cleanup(RERR_PROTOCOL);
3117 }
3118 if (DEBUG_GTE(FLIST, 3)) {
3119 rprintf(FINFO, "[%s] receiving flist for dir %d\n",
3120 who_am_i(), ndx);
3121 }
3122 flist = recv_file_list(f, ndx);
3123 flist->parent_ndx = ndx;
3124 }
3125 }
3126
3127 /* Search for an identically-named item in the file list. Note that the
3128 * items must agree in their directory-ness, or no match is returned. */
3129 int flist_find(struct file_list *flist, struct file_struct *f)
3130 {
3131 int low = flist->low, high = flist->high;
3132 int diff, mid, mid_up;
3133
3134 while (low <= high) {
3135 mid = (low + high) / 2;
3136 if (F_IS_ACTIVE(flist->sorted[mid]))
3137 mid_up = mid;
3138 else {
3139 /* Scan for the next non-empty entry using the cached
3140 * distance values. If the value isn't fully up-to-
3141 * date, update it. */
3142 mid_up = mid + F_DEPTH(flist->sorted[mid]);
3143 if (!F_IS_ACTIVE(flist->sorted[mid_up])) {
3144 do {
3145 mid_up += F_DEPTH(flist->sorted[mid_up]);
3146 } while (!F_IS_ACTIVE(flist->sorted[mid_up]));
3147 F_DEPTH(flist->sorted[mid]) = mid_up - mid;
3148 }
3149 if (mid_up > high) {
3150 /* If there's nothing left above us, set high to
3151 * a non-empty entry below us and continue. */
3152 high = mid - (int)flist->sorted[mid]->len32;
3153 if (!F_IS_ACTIVE(flist->sorted[high])) {
3154 do {
3155 high -= (int)flist->sorted[high]->len32;
3156 } while (!F_IS_ACTIVE(flist->sorted[high]));
3157 flist->sorted[mid]->len32 = mid - high;
3158 }
3159 continue;
3160 }
3161 }
3162 diff = f_name_cmp(flist->sorted[mid_up], f);
3163 if (diff == 0) {
3164 if (protocol_version < 29
3165 && S_ISDIR(flist->sorted[mid_up]->mode)
3166 != S_ISDIR(f->mode))
3167 return -1;
3168 return mid_up;
3169 }
3170 if (diff < 0)
3171 low = mid_up + 1;
3172 else
3173 high = mid - 1;
3174 }
3175 return -1;
3176 }
3177
3178 /* Search for a name in the file list. You must specify want_dir_match as:
3179 * 1=match directories, 0=match non-directories, or -1=match either. */
3180 int flist_find_name(struct file_list *flist, const char *fname, int want_dir_match)
3181 {
3182 static struct file_struct *f;
3183 char fbuf[MAXPATHLEN];
3184 const char *slash = strrchr(fname, '/');
3185 const char *basename = slash ? slash+1 : fname;
3186
3187 if (!f)
3188 f = (struct file_struct*)new_array(char, FILE_STRUCT_LEN + MAXPATHLEN + 1);
3189
3190 memset(f, 0, FILE_STRUCT_LEN);
3191 memcpy((void*)f->basename, basename, strlen(basename)+1);
3192
3193 if (slash) {
3194 strlcpy(fbuf, fname, slash - fname + 1);
3195 f->dirname = fbuf;
3196 } else
3197 f->dirname = NULL;
3198
3199 f->mode = want_dir_match > 0 ? S_IFDIR : S_IFREG;
3200
3201 if (want_dir_match < 0)
3202 return flist_find_ignore_dirness(flist, f);
3203 return flist_find(flist, f);
3204 }
3205
3206 /* Search for an identically-named item in the file list. Differs from
3207 * flist_find in that an item that agrees with "f" in directory-ness is
3208 * preferred but one that does not is still found. */
3209 int flist_find_ignore_dirness(struct file_list *flist, struct file_struct *f)
3210 {
3211 mode_t save_mode;
3212 int ndx;
3213
3214 /* First look for an item that agrees in directory-ness. */
3215 ndx = flist_find(flist, f);
3216 if (ndx >= 0)
3217 return ndx;
3218
3219 /* Temporarily flip f->mode to look for an item of opposite
3220 * directory-ness. */
3221 save_mode = f->mode;
3222 f->mode = S_ISDIR(f->mode) ? S_IFREG : S_IFDIR;
3223 ndx = flist_find(flist, f);
3224 f->mode = save_mode;
3225 return ndx;
3226 }
3227
3228 /*
3229 * Free up any resources a file_struct has allocated
3230 * and clear the file.
3231 */
3232 void clear_file(struct file_struct *file)
3233 {
3234 /* The +1 zeros out the first char of the basename. */
3235 memset(file, 0, FILE_STRUCT_LEN + 1);
3236 /* In an empty entry, F_DEPTH() is an offset to the next non-empty
3237 * entry. Likewise for len32 in the opposite direction. We assume
3238 * that we're alone for now since flist_find() will adjust the counts
3239 * it runs into that aren't up-to-date. */
3240 file->len32 = F_DEPTH(file) = 1;
3241 }
3242
3243 /* Allocate a new file list. */
3244 static struct file_list *flist_new(int flags, const char *msg)
3245 {
3246 struct file_list *flist;
3247
3248 flist = new0(struct file_list);
3249
3250 if (flags & FLIST_TEMP) {
3251 if (!(flist->file_pool = pool_create(SMALL_EXTENT, 0, _out_of_memory, POOL_INTERN)))
3252 out_of_memory(msg);
3253 } else {
3254 /* This is a doubly linked list with prev looping back to
3255 * the end of the list, but the last next pointer is NULL. */
3256 if (!first_flist) {
3257 if (!(flist->file_pool = pool_create(NORMAL_EXTENT, 0, _out_of_memory, POOL_INTERN)))
3258 out_of_memory(msg);
3259
3260 flist->ndx_start = flist->flist_num = inc_recurse ? 1 : 0;
3261
3262 first_flist = cur_flist = flist->prev = flist;
3263 } else {
3264 struct file_list *prev = first_flist->prev;
3265
3266 flist->file_pool = first_flist->file_pool;
3267
3268 flist->ndx_start = prev->ndx_start + prev->used + 1;
3269 flist->flist_num = prev->flist_num + 1;
3270
3271 flist->prev = prev;
3272 prev->next = first_flist->prev = flist;
3273 }
3274 flist->pool_boundary = pool_boundary(flist->file_pool, 0);
3275 flist_cnt++;
3276 }
3277
3278 return flist;
3279 }
3280
3281 /* Free up all elements in a flist. */
3282 void flist_free(struct file_list *flist)
3283 {
3284 if (!flist->prev) {
3285 /* Was FLIST_TEMP dir-list. */
3286 } else if (flist == flist->prev) {
3287 first_flist = cur_flist = NULL;
3288 file_total = 0;
3289 flist_cnt = 0;
3290 } else {
3291 if (flist == cur_flist)
3292 cur_flist = flist->next;
3293 if (flist == first_flist)
3294 first_flist = first_flist->next;
3295 else {
3296 flist->prev->next = flist->next;
3297 if (!flist->next)
3298 flist->next = first_flist;
3299 }
3300 flist->next->prev = flist->prev;
3301 file_total -= flist->used;
3302 flist_cnt--;
3303 }
3304
3305 if (!flist->prev || !flist_cnt)
3306 pool_destroy(flist->file_pool);
3307 else
3308 pool_free_old(flist->file_pool, flist->pool_boundary);
3309
3310 if (flist->sorted && flist->sorted != flist->files)
3311 free(flist->sorted);
3312 free(flist->files);
3313 free(flist);
3314 }
3315
3316 /* This routine ensures we don't have any duplicate names in our file list.
3317 * duplicate names can cause corruption because of the pipelining. */
3318 static void flist_sort_and_clean(struct file_list *flist, int strip_root)
3319 {
3320 char fbuf[MAXPATHLEN];
3321 int i, prev_i;
3322
3323 if (!flist)
3324 return;
3325 if (flist->used == 0) {
3326 flist->high = -1;
3327 flist->low = 0;
3328 return;
3329 }
3330
3331 fsort(flist->sorted, flist->used);
3332
3333 if (!am_sender || inc_recurse) {
3334 for (i = prev_i = 0; i < flist->used; i++) {
3335 if (F_IS_ACTIVE(flist->sorted[i])) {
3336 prev_i = i;
3337 break;
3338 }
3339 }
3340 flist->low = prev_i;
3341 } else {
3342 i = prev_i = flist->used - 1;
3343 flist->low = 0;
3344 }
3345
3346 while (++i < flist->used) {
3347 int j;
3348 struct file_struct *file = flist->sorted[i];
3349
3350 if (!F_IS_ACTIVE(file))
3351 continue;
3352 if (f_name_cmp(file, flist->sorted[prev_i]) == 0)
3353 j = prev_i;
3354 else if (protocol_version >= 29 && S_ISDIR(file->mode)) {
3355 int save_mode = file->mode;
3356 /* Make sure that this directory doesn't duplicate a
3357 * non-directory earlier in the list. */
3358 flist->high = prev_i;
3359 file->mode = S_IFREG;
3360 j = flist_find(flist, file);
3361 file->mode = save_mode;
3362 } else
3363 j = -1;
3364 if (j >= 0) {
3365 int keep, drop;
3366 /* If one is a dir and the other is not, we want to
3367 * keep the dir because it might have contents in the
3368 * list. Otherwise keep the first one. */
3369 if (S_ISDIR(file->mode)) {
3370 struct file_struct *fp = flist->sorted[j];
3371 if (!S_ISDIR(fp->mode))
3372 keep = i, drop = j;
3373 else {
3374 if (am_sender)
3375 file->flags |= FLAG_DUPLICATE;
3376 else { /* Make sure we merge our vital flags. */
3377 fp->flags |= file->flags & (FLAG_TOP_DIR|FLAG_CONTENT_DIR);
3378 fp->flags &= file->flags | ~FLAG_IMPLIED_DIR;
3379 }
3380 keep = j, drop = i;
3381 }
3382 } else
3383 keep = j, drop = i;
3384
3385 if (!am_sender) {
3386 if (DEBUG_GTE(DUP, 1)) {
3387 rprintf(FINFO,
3388 "removing duplicate name %s from file list (%d)\n",
3389 f_name(file, fbuf), drop + flist->ndx_start);
3390 }
3391 clear_file(flist->sorted[drop]);
3392 }
3393
3394 if (keep == i) {
3395 if (flist->low == drop) {
3396 for (j = drop + 1;
3397 j < i && !F_IS_ACTIVE(flist->sorted[j]);
3398 j++) {}
3399 flist->low = j;
3400 }
3401 prev_i = i;
3402 }
3403 } else
3404 prev_i = i;
3405 }
3406 flist->high = prev_i;
3407
3408 if (strip_root) {
3409 /* We need to strip off the leading slashes for relative
3410 * paths, but this must be done _after_ the sorting phase. */
3411 for (i = flist->low; i <= flist->high; i++) {
3412 struct file_struct *file = flist->sorted[i];
3413
3414 if (!file->dirname)
3415 continue;
3416 while (*file->dirname == '/')
3417 file->dirname++;
3418 if (!*file->dirname)
3419 file->dirname = NULL;
3420 }
3421 }
3422
3423 if (prune_empty_dirs && !am_sender) {
3424 int j, prev_depth = 0;
3425
3426 prev_i = 0; /* It's OK that this isn't really true. */
3427
3428 for (i = flist->low; i <= flist->high; i++) {
3429 struct file_struct *fp, *file = flist->sorted[i];
3430
3431 /* This temporarily abuses the F_DEPTH() value for a
3432 * directory that is in a chain that might get pruned.
3433 * We restore the old value if it gets a reprieve. */
3434 if (S_ISDIR(file->mode) && F_DEPTH(file)) {
3435 /* Dump empty dirs when coming back down. */
3436 for (j = prev_depth; j >= F_DEPTH(file); j--) {
3437 fp = flist->sorted[prev_i];
3438 if (F_DEPTH(fp) >= 0)
3439 break;
3440 prev_i = -F_DEPTH(fp)-1;
3441 clear_file(fp);
3442 }
3443 prev_depth = F_DEPTH(file);
3444 if (is_excluded(f_name(file, fbuf), 1, ALL_FILTERS)) {
3445 /* Keep dirs through this dir. */
3446 for (j = prev_depth-1; ; j--) {
3447 fp = flist->sorted[prev_i];
3448 if (F_DEPTH(fp) >= 0)
3449 break;
3450 prev_i = -F_DEPTH(fp)-1;
3451 F_DEPTH(fp) = j;
3452 }
3453 } else
3454 F_DEPTH(file) = -prev_i-1;
3455 prev_i = i;
3456 } else {
3457 /* Keep dirs through this non-dir. */
3458 for (j = prev_depth; ; j--) {
3459 fp = flist->sorted[prev_i];
3460 if (F_DEPTH(fp) >= 0)
3461 break;
3462 prev_i = -F_DEPTH(fp)-1;
3463 F_DEPTH(fp) = j;
3464 }
3465 }
3466 }
3467 /* Dump all remaining empty dirs. */
3468 while (1) {
3469 struct file_struct *fp = flist->sorted[prev_i];
3470 if (F_DEPTH(fp) >= 0)
3471 break;
3472 prev_i = -F_DEPTH(fp)-1;
3473 clear_file(fp);
3474 }
3475
3476 for (i = flist->low; i <= flist->high; i++) {
3477 if (F_IS_ACTIVE(flist->sorted[i]))
3478 break;
3479 }
3480 flist->low = i;
3481 for (i = flist->high; i >= flist->low; i--) {
3482 if (F_IS_ACTIVE(flist->sorted[i]))
3483 break;
3484 }
3485 flist->high = i;
3486 }
3487 }
3488
3489 static void output_flist(struct file_list *flist)
3490 {
3491 char uidbuf[16], gidbuf[16], depthbuf[16];
3492 struct file_struct *file;
3493 const char *root, *dir, *slash, *name, *trail;
3494 const char *who = who_am_i();
3495 int i;
3496
3497 rprintf(FINFO, "[%s] flist start=%d, used=%d, low=%d, high=%d\n",
3498 who, flist->ndx_start, flist->used, flist->low, flist->high);
3499 for (i = 0; i < flist->used; i++) {
3500 file = flist->files[i];
3501 if ((am_root || am_sender) && uid_ndx) {
3502 snprintf(uidbuf, sizeof uidbuf, " uid=%u",
3503 F_OWNER(file));
3504 } else
3505 *uidbuf = '\0';
3506 if (gid_ndx) {
3507 static const char parens[] = "(\0)\0\0\0";
3508 const char *pp = parens + (file->flags & FLAG_SKIP_GROUP ? 0 : 3);
3509 snprintf(gidbuf, sizeof gidbuf, " gid=%s%u%s",
3510 pp, F_GROUP(file), pp + 2);
3511 } else
3512 *gidbuf = '\0';
3513 if (!am_sender)
3514 snprintf(depthbuf, sizeof depthbuf, "%d", F_DEPTH(file));
3515 if (F_IS_ACTIVE(file)) {
3516 root = am_sender ? NS(F_PATHNAME(file)) : depthbuf;
3517 if ((dir = file->dirname) == NULL)
3518 dir = slash = "";
3519 else
3520 slash = "/";
3521 name = file->basename;
3522 trail = S_ISDIR(file->mode) ? "/" : "";
3523 } else
3524 root = dir = slash = name = trail = "";
3525 rprintf(FINFO,
3526 "[%s] i=%d %s %s%s%s%s mode=0%o len=%s%s%s flags=%x\n",
3527 who, i + flist->ndx_start,
3528 root, dir, slash, name, trail,
3529 (int)file->mode, comma_num(F_LENGTH(file)),
3530 uidbuf, gidbuf, file->flags);
3531 }
3532 }
3533
3534 enum fnc_state { s_DIR, s_SLASH, s_BASE, s_TRAILING };
3535 enum fnc_type { t_PATH, t_ITEM };
3536
3537 static int found_prefix;
3538
3539 /* Compare the names of two file_struct entities, similar to how strcmp()
3540 * would do if it were operating on the joined strings.
3541 *
3542 * Some differences beginning with protocol_version 29: (1) directory names
3543 * are compared with an assumed trailing slash so that they compare in a
3544 * way that would cause them to sort immediately prior to any content they
3545 * may have; (2) a directory of any name compares after a non-directory of
3546 * any name at the same depth; (3) a directory with name "." compares prior
3547 * to anything else. These changes mean that a directory and a non-dir
3548 * with the same name will not compare as equal (protocol_version >= 29).
3549 *
3550 * The dirname component can be an empty string, but the basename component
3551 * cannot (and never is in the current codebase). The basename component
3552 * may be NULL (for a removed item), in which case it is considered to be
3553 * after any existing item. */
3554 int f_name_cmp(const struct file_struct *f1, const struct file_struct *f2)
3555 {
3556 int dif;
3557 const uchar *c1, *c2;
3558 enum fnc_state state1, state2;
3559 enum fnc_type type1, type2;
3560 enum fnc_type t_path = protocol_version >= 29 ? t_PATH : t_ITEM;
3561
3562 if (!f1 || !F_IS_ACTIVE(f1)) {
3563 if (!f2 || !F_IS_ACTIVE(f2))
3564 return 0;
3565 return -1;
3566 }
3567 if (!f2 || !F_IS_ACTIVE(f2))
3568 return 1;
3569
3570 c1 = (uchar*)f1->dirname;
3571 c2 = (uchar*)f2->dirname;
3572 if (c1 == c2)
3573 c1 = c2 = NULL;
3574 if (!c1) {
3575 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
3576 c1 = (const uchar*)f1->basename;
3577 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
3578 type1 = t_ITEM;
3579 state1 = s_TRAILING;
3580 c1 = (uchar*)"";
3581 } else
3582 state1 = s_BASE;
3583 } else {
3584 type1 = t_path;
3585 state1 = s_DIR;
3586 }
3587 if (!c2) {
3588 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
3589 c2 = (const uchar*)f2->basename;
3590 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
3591 type2 = t_ITEM;
3592 state2 = s_TRAILING;
3593 c2 = (uchar*)"";
3594 } else
3595 state2 = s_BASE;
3596 } else {
3597 type2 = t_path;
3598 state2 = s_DIR;
3599 }
3600
3601 if (type1 != type2)
3602 return type1 == t_PATH ? 1 : -1;
3603
3604 do {
3605 if (!*c1) {
3606 switch (state1) {
3607 case s_DIR:
3608 state1 = s_SLASH;
3609 c1 = (uchar*)"/";
3610 break;
3611 case s_SLASH:
3612 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
3613 c1 = (const uchar*)f1->basename;
3614 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
3615 type1 = t_ITEM;
3616 state1 = s_TRAILING;
3617 c1 = (uchar*)"";
3618 } else
3619 state1 = s_BASE;
3620 break;
3621 case s_BASE:
3622 state1 = s_TRAILING;
3623 if (type1 == t_PATH) {
3624 c1 = (uchar*)"/";
3625 break;
3626 }
3627 /* FALL THROUGH */
3628 case s_TRAILING:
3629 type1 = t_ITEM;
3630 break;
3631 }
3632 if (*c2 && type1 != type2)
3633 return type1 == t_PATH ? 1 : -1;
3634 }
3635 if (!*c2) {
3636 switch (state2) {
3637 case s_DIR:
3638 state2 = s_SLASH;
3639 c2 = (uchar*)"/";
3640 break;
3641 case s_SLASH:
3642 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
3643 c2 = (const uchar*)f2->basename;
3644 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
3645 type2 = t_ITEM;
3646 state2 = s_TRAILING;
3647 c2 = (uchar*)"";
3648 } else
3649 state2 = s_BASE;
3650 break;
3651 case s_BASE:
3652 state2 = s_TRAILING;
3653 if (type2 == t_PATH) {
3654 c2 = (uchar*)"/";
3655 break;
3656 }
3657 /* FALL THROUGH */
3658 case s_TRAILING:
3659 found_prefix = 1;
3660 if (!*c1)
3661 return 0;
3662 type2 = t_ITEM;
3663 break;
3664 }
3665 if (type1 != type2)
3666 return type1 == t_PATH ? 1 : -1;
3667 }
3668 } while ((dif = (int)*c1++ - (int)*c2++) == 0);
3669
3670 return dif;
3671 }
3672
3673 /* Returns 1 if f1's filename has all of f2's filename as a prefix. This does
3674 * not match if f2's basename is not an exact match of a path element in f1.
3675 * E.g. /path/foo is not a prefix of /path/foobar/baz, but /path/foobar is. */
3676 int f_name_has_prefix(const struct file_struct *f1, const struct file_struct *f2)
3677 {
3678 found_prefix = 0;
3679 f_name_cmp(f1, f2);
3680 return found_prefix;
3681 }
3682
3683 char *f_name_buf(void)
3684 {
3685 static char names[5][MAXPATHLEN];
3686 static unsigned int n;
3687
3688 n = (n + 1) % (sizeof names / sizeof names[0]);
3689
3690 return names[n];
3691 }
3692
3693 /* Return a copy of the full filename of a flist entry, using the indicated
3694 * buffer or one of 5 static buffers if fbuf is NULL. No size-checking is
3695 * done because we checked the size when creating the file_struct entry.
3696 */
3697 char *f_name(const struct file_struct *f, char *fbuf)
3698 {
3699 if (!f || !F_IS_ACTIVE(f))
3700 return NULL;
3701
3702 if (!fbuf)
3703 fbuf = f_name_buf();
3704
3705 if (f->dirname) {
3706 int len = strlen(f->dirname);
3707 memcpy(fbuf, f->dirname, len);
3708 fbuf[len] = '/';
3709 strlcpy(fbuf + len + 1, f->basename, MAXPATHLEN - (len + 1));
3710 } else
3711 strlcpy(fbuf, f->basename, MAXPATHLEN);
3712
3713 return fbuf;
3714 }
3715
3716 /* Do a non-recursive scan of the named directory, possibly ignoring all
3717 * exclude rules except for the daemon's. If "dlen" is >=0, it is the length
3718 * of the dirname string, and also indicates that "dirname" is a MAXPATHLEN
3719 * buffer (the functions we call will append names onto the end, but the old
3720 * dir value will be restored on exit). */
3721 struct file_list *get_dirlist(char *dirname, int dlen, int flags)
3722 {
3723 struct file_list *dirlist;
3724 char dirbuf[MAXPATHLEN];
3725 int save_recurse = recurse;
3726 int save_xfer_dirs = xfer_dirs;
3727 int save_prune_empty_dirs = prune_empty_dirs;
3728 int senddir_fd = flags & GDL_IGNORE_FILTER_RULES ? -2 : -1;
3729 int senddir_flags = FLAG_CONTENT_DIR;
3730
3731 if (dlen < 0) {
3732 dlen = strlcpy(dirbuf, dirname, MAXPATHLEN);
3733 if (dlen >= MAXPATHLEN)
3734 return NULL;
3735 dirname = dirbuf;
3736 }
3737
3738 dirlist = flist_new(FLIST_TEMP, "get_dirlist");
3739
3740 if (flags & GDL_PERHAPS_DIR)
3741 senddir_flags |= FLAG_PERHAPS_DIR;
3742
3743 recurse = 0;
3744 xfer_dirs = 1;
3745 send_directory(senddir_fd, dirlist, dirname, dlen, senddir_flags);
3746 xfer_dirs = save_xfer_dirs;
3747 recurse = save_recurse;
3748 if (INFO_GTE(PROGRESS, 1))
3749 flist_count_offset += dirlist->used;
3750
3751 prune_empty_dirs = 0;
3752 dirlist->sorted = dirlist->files;
3753 flist_sort_and_clean(dirlist, 0);
3754 prune_empty_dirs = save_prune_empty_dirs;
3755
3756 if (DEBUG_GTE(FLIST, 3))
3757 output_flist(dirlist);
3758
3759 return dirlist;
3760 }