Use the new device defines: F_RDEV_P(), DEV_MAJOR(), and DEV_MINOR().
[rsync/rsync.git] / flist.c
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 <mbp@samba.org>
7  * Copyright (C) 2002, 2003, 2004, 2005, 2006 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 2 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, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
22  */
23
24 #include "rsync.h"
25
26 extern int verbose;
27 extern int list_only;
28 extern int am_root;
29 extern int am_server;
30 extern int am_daemon;
31 extern int am_sender;
32 extern int do_progress;
33 extern int always_checksum;
34 extern int module_id;
35 extern int ignore_errors;
36 extern int numeric_ids;
37 extern int recurse;
38 extern int xfer_dirs;
39 extern int filesfrom_fd;
40 extern int one_file_system;
41 extern int copy_dirlinks;
42 extern int keep_dirlinks;
43 extern int preserve_links;
44 extern int preserve_hard_links;
45 extern int preserve_devices;
46 extern int preserve_specials;
47 extern int preserve_uid;
48 extern int preserve_gid;
49 extern int relative_paths;
50 extern int implied_dirs;
51 extern int flist_extra_cnt;
52 extern int ignore_perishable;
53 extern int non_perishable_cnt;
54 extern int prune_empty_dirs;
55 extern int copy_links;
56 extern int copy_unsafe_links;
57 extern int protocol_version;
58 extern int sanitize_paths;
59 extern struct stats stats;
60 extern struct file_list *the_file_list;
61
62 extern char curr_dir[MAXPATHLEN];
63
64 extern struct chmod_mode_struct *chmod_modes;
65
66 extern struct filter_list_struct filter_list;
67 extern struct filter_list_struct server_filter_list;
68
69 int io_error;
70 int checksum_len;
71 dev_t filesystem_dev; /* used to implement -x */
72
73 /* The tmp_* vars are used as a cache area by make_file() to store data
74  * that the sender doesn't need to remember in its file list.  The data
75  * will survive just long enough to be used by send_file_entry(). */
76 static dev_t tmp_rdev;
77 static struct idev tmp_idev;
78 static char tmp_sum[MD4_SUM_LENGTH];
79
80 static char empty_sum[MD4_SUM_LENGTH];
81 static int flist_count_offset;
82
83 static void clean_flist(struct file_list *flist, int strip_root, int no_dups);
84 static void output_flist(struct file_list *flist);
85
86 void init_flist(void)
87 {
88         if (verbose > 4) {
89                 rprintf(FINFO, "FILE_STRUCT_LEN=%d, EXTRA_LEN=%d\n",
90                         FILE_STRUCT_LEN, EXTRA_LEN);
91         }
92         checksum_len = protocol_version < 21 ? 2 : MD4_SUM_LENGTH;
93 }
94
95 static int show_filelist_p(void)
96 {
97         return verbose && xfer_dirs && !am_server;
98 }
99
100 static void start_filelist_progress(char *kind)
101 {
102         rprintf(FCLIENT, "%s ... ", kind);
103         if (verbose > 1 || do_progress)
104                 rprintf(FCLIENT, "\n");
105         rflush(FINFO);
106 }
107
108 static void emit_filelist_progress(int count)
109 {
110         rprintf(FCLIENT, " %d files...\r", count);
111 }
112
113 static void maybe_emit_filelist_progress(int count)
114 {
115         if (do_progress && show_filelist_p() && (count % 100) == 0)
116                 emit_filelist_progress(count);
117 }
118
119 static void finish_filelist_progress(const struct file_list *flist)
120 {
121         if (do_progress) {
122                 /* This overwrites the progress line */
123                 rprintf(FINFO, "%d file%sto consider\n",
124                         flist->count, flist->count == 1 ? " " : "s ");
125         } else
126                 rprintf(FINFO, "done\n");
127 }
128
129 void show_flist_stats(void)
130 {
131         /* Nothing yet */
132 }
133
134 static void list_file_entry(struct file_struct *f)
135 {
136         char permbuf[PERMSTRING_SIZE];
137         double len;
138
139         if (!F_IS_ACTIVE(f)) {
140                 /* this can happen if duplicate names were removed */
141                 return;
142         }
143
144         permstring(permbuf, f->mode);
145         len = F_LENGTH(f);
146
147 #ifdef SUPPORT_LINKS
148         if (preserve_links && S_ISLNK(f->mode)) {
149                 rprintf(FINFO, "%s %11.0f %s %s -> %s\n",
150                         permbuf, len, timestring(f->modtime),
151                         f_name(f, NULL), F_SYMLINK(f));
152         } else
153 #endif
154         {
155                 rprintf(FINFO, "%s %11.0f %s %s\n",
156                         permbuf, len, timestring(f->modtime),
157                         f_name(f, NULL));
158         }
159 }
160
161 /* Stat either a symlink or its referent, depending on the settings of
162  * copy_links, copy_unsafe_links, etc.  Returns -1 on error, 0 on success.
163  *
164  * If path is the name of a symlink, then the linkbuf buffer (which must hold
165  * MAXPATHLEN chars) will be set to the symlink's target string.
166  *
167  * The stat structure pointed to by stp will contain information about the
168  * link or the referent as appropriate, if they exist. */
169 static int readlink_stat(const char *path, STRUCT_STAT *stp, char *linkbuf)
170 {
171 #ifdef SUPPORT_LINKS
172         if (link_stat(path, stp, copy_dirlinks) < 0)
173                 return -1;
174         if (S_ISLNK(stp->st_mode)) {
175                 int llen = readlink(path, linkbuf, MAXPATHLEN - 1);
176                 if (llen < 0)
177                         return -1;
178                 linkbuf[llen] = '\0';
179                 if (copy_unsafe_links && unsafe_symlink(linkbuf, path)) {
180                         if (verbose > 1) {
181                                 rprintf(FINFO,"copying unsafe symlink \"%s\" -> \"%s\"\n",
182                                         path, linkbuf);
183                         }
184                         return do_stat(path, stp);
185                 }
186         }
187         return 0;
188 #else
189         return do_stat(path, stp);
190 #endif
191 }
192
193 int link_stat(const char *path, STRUCT_STAT *stp, int follow_dirlinks)
194 {
195 #ifdef SUPPORT_LINKS
196         if (copy_links)
197                 return do_stat(path, stp);
198         if (do_lstat(path, stp) < 0)
199                 return -1;
200         if (follow_dirlinks && S_ISLNK(stp->st_mode)) {
201                 STRUCT_STAT st;
202                 if (do_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
203                         *stp = st;
204         }
205         return 0;
206 #else
207         return do_stat(path, stp);
208 #endif
209 }
210
211 /* This function is used to check if a file should be included/excluded
212  * from the list of files based on its name and type etc.  The value of
213  * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
214 static int is_excluded(char *fname, int is_dir, int filter_level)
215 {
216 #if 0 /* This currently never happens, so avoid a useless compare. */
217         if (filter_level == NO_FILTERS)
218                 return 0;
219 #endif
220         if (fname) {
221                 /* never exclude '.', even if somebody does --exclude '*' */
222                 if (fname[0] == '.' && !fname[1])
223                         return 0;
224                 /* Handle the -R version of the '.' dir. */
225                 if (fname[0] == '/') {
226                         int len = strlen(fname);
227                         if (fname[len-1] == '.' && fname[len-2] == '/')
228                                 return 0;
229                 }
230         }
231         if (server_filter_list.head
232             && check_filter(&server_filter_list, fname, is_dir) < 0)
233                 return 1;
234         if (filter_level != ALL_FILTERS)
235                 return 0;
236         if (filter_list.head
237             && check_filter(&filter_list, fname, is_dir) < 0)
238                 return 1;
239         return 0;
240 }
241
242 static int to_wire_mode(mode_t mode)
243 {
244 #ifdef SUPPORT_LINKS
245 #if _S_IFLNK != 0120000
246         if (S_ISLNK(mode))
247                 return (mode & ~(_S_IFMT)) | 0120000;
248 #endif
249 #endif
250         return mode;
251 }
252
253 static mode_t from_wire_mode(int mode)
254 {
255 #if _S_IFLNK != 0120000
256         if ((mode & (_S_IFMT)) == 0120000)
257                 return (mode & ~(_S_IFMT)) | _S_IFLNK;
258 #endif
259         return mode;
260 }
261
262 static void send_directory(int f, struct file_list *flist,
263                            char *fbuf, int len);
264
265 static const char *flist_dir;
266 static int flist_dir_len;
267
268
269 /**
270  * Make sure @p flist is big enough to hold at least @p flist->count
271  * entries.
272  **/
273 void flist_expand(struct file_list *flist)
274 {
275         struct file_struct **new_ptr;
276
277         if (flist->count < flist->malloced)
278                 return;
279
280         if (flist->malloced < FLIST_START)
281                 flist->malloced = FLIST_START;
282         else if (flist->malloced >= FLIST_LINEAR)
283                 flist->malloced += FLIST_LINEAR;
284         else
285                 flist->malloced *= 2;
286
287         /*
288          * In case count jumped or we are starting the list
289          * with a known size just set it.
290          */
291         if (flist->malloced < flist->count)
292                 flist->malloced = flist->count;
293
294         new_ptr = realloc_array(flist->files, struct file_struct *,
295                                 flist->malloced);
296
297         if (verbose >= 2 && flist->malloced != FLIST_START) {
298                 rprintf(FCLIENT, "[%s] expand file_list to %.0f bytes, did%s move\n",
299                     who_am_i(),
300                     (double)sizeof flist->files[0] * flist->malloced,
301                     (new_ptr == flist->files) ? " not" : "");
302         }
303
304         flist->files = new_ptr;
305
306         if (!flist->files)
307                 out_of_memory("flist_expand");
308 }
309
310 static void send_file_entry(struct file_struct *file, int f)
311 {
312         unsigned short flags;
313         static time_t modtime;
314         static mode_t mode;
315         static int64 dev;
316         static dev_t rdev;
317         static uint32 rdev_major;
318         static uid_t uid;
319         static gid_t gid;
320         static char lastname[MAXPATHLEN];
321         char fname[MAXPATHLEN];
322         int l1, l2;
323
324         if (f < 0)
325                 return;
326
327         if (!file) {
328                 write_byte(f, 0);
329                 modtime = 0, mode = 0;
330                 dev = 0, rdev = MAKEDEV(0, 0);
331                 rdev_major = 0;
332                 uid = 0, gid = 0;
333                 *lastname = '\0';
334                 return;
335         }
336
337         f_name(file, fname);
338
339         flags = file->flags & FLAG_TOP_DIR; /* FLAG_TOP_DIR == XMIT_TOP_DIR */
340
341         if (file->mode == mode)
342                 flags |= XMIT_SAME_MODE;
343         else
344                 mode = file->mode;
345         if ((preserve_devices && IS_DEVICE(mode))
346          || (preserve_specials && IS_SPECIAL(mode))) {
347                 if (protocol_version < 28) {
348                         if (tmp_rdev == rdev)
349                                 flags |= XMIT_SAME_RDEV_pre28;
350                         else
351                                 rdev = tmp_rdev;
352                 } else {
353                         rdev = tmp_rdev;
354                         if ((uint32)major(rdev) == rdev_major)
355                                 flags |= XMIT_SAME_RDEV_MAJOR;
356                         else
357                                 rdev_major = major(rdev);
358                         if ((uint32)minor(rdev) <= 0xFFu)
359                                 flags |= XMIT_RDEV_MINOR_IS_SMALL;
360                 }
361         } else if (protocol_version < 28)
362                 rdev = MAKEDEV(0, 0);
363         if (preserve_uid) {
364                 if (F_UID(file) == uid)
365                         flags |= XMIT_SAME_UID;
366                 else
367                         uid = F_UID(file);
368         }
369         if (preserve_gid) {
370                 if (F_GID(file) == gid)
371                         flags |= XMIT_SAME_GID;
372                 else
373                         gid = F_GID(file);
374         }
375         if (file->modtime == modtime)
376                 flags |= XMIT_SAME_TIME;
377         else
378                 modtime = file->modtime;
379
380 #ifdef SUPPORT_HARD_LINKS
381         if (tmp_idev.dev != 0) {
382                 if (tmp_idev.dev == dev) {
383                         if (protocol_version >= 28)
384                                 flags |= XMIT_SAME_DEV;
385                 } else
386                         dev = tmp_idev.dev;
387                 flags |= XMIT_HAS_IDEV_DATA;
388         }
389 #endif
390
391         for (l1 = 0;
392             lastname[l1] && (fname[l1] == lastname[l1]) && (l1 < 255);
393             l1++) {}
394         l2 = strlen(fname+l1);
395
396         if (l1 > 0)
397                 flags |= XMIT_SAME_NAME;
398         if (l2 > 255)
399                 flags |= XMIT_LONG_NAME;
400
401         /* We must make sure we don't send a zero flag byte or the
402          * other end will terminate the flist transfer.  Note that
403          * the use of XMIT_TOP_DIR on a non-dir has no meaning, so
404          * it's harmless way to add a bit to the first flag byte. */
405         if (protocol_version >= 28) {
406                 if (!flags && !S_ISDIR(mode))
407                         flags |= XMIT_TOP_DIR;
408                 if ((flags & 0xFF00) || !flags) {
409                         flags |= XMIT_EXTENDED_FLAGS;
410                         write_shortint(f, flags);
411                 } else
412                         write_byte(f, flags);
413         } else {
414                 if (!(flags & 0xFF))
415                         flags |= S_ISDIR(mode) ? XMIT_LONG_NAME : XMIT_TOP_DIR;
416                 write_byte(f, flags);
417         }
418         if (flags & XMIT_SAME_NAME)
419                 write_byte(f, l1);
420         if (flags & XMIT_LONG_NAME)
421                 write_int(f, l2);
422         else
423                 write_byte(f, l2);
424         write_buf(f, fname + l1, l2);
425
426         write_longint(f, F_LENGTH(file));
427         if (!(flags & XMIT_SAME_TIME))
428                 write_int(f, modtime);
429         if (!(flags & XMIT_SAME_MODE))
430                 write_int(f, to_wire_mode(mode));
431         if (preserve_uid && !(flags & XMIT_SAME_UID)) {
432                 if (!numeric_ids)
433                         add_uid(uid);
434                 write_int(f, uid);
435         }
436         if (preserve_gid && !(flags & XMIT_SAME_GID)) {
437                 if (!numeric_ids)
438                         add_gid(gid);
439                 write_int(f, gid);
440         }
441         if ((preserve_devices && IS_DEVICE(mode))
442          || (preserve_specials && IS_SPECIAL(mode))) {
443                 if (protocol_version < 28) {
444                         if (!(flags & XMIT_SAME_RDEV_pre28))
445                                 write_int(f, (int)rdev);
446                 } else {
447                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
448                                 write_int(f, major(rdev));
449                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
450                                 write_byte(f, minor(rdev));
451                         else
452                                 write_int(f, minor(rdev));
453                 }
454         }
455
456 #ifdef SUPPORT_LINKS
457         if (preserve_links && S_ISLNK(mode)) {
458                 const char *sl = F_SYMLINK(file);
459                 int len = strlen(sl);
460                 write_int(f, len);
461                 write_buf(f, sl, len);
462         }
463 #endif
464
465 #ifdef SUPPORT_HARD_LINKS
466         if (tmp_idev.dev != 0) {
467                 if (protocol_version < 26) {
468                         /* 32-bit dev_t and ino_t */
469                         write_int(f, (int32)dev);
470                         write_int(f, (int32)tmp_idev.ino);
471                 } else {
472                         /* 64-bit dev_t and ino_t */
473                         if (!(flags & XMIT_SAME_DEV))
474                                 write_longint(f, dev);
475                         write_longint(f, tmp_idev.ino);
476                 }
477         }
478 #endif
479
480         if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
481                 const char *sum;
482                 if (S_ISREG(mode))
483                         sum = tmp_sum;
484                 else {
485                         /* Prior to 28, we sent a useless set of nulls. */
486                         sum = empty_sum;
487                 }
488                 write_buf(f, sum, checksum_len);
489         }
490
491         strlcpy(lastname, fname, MAXPATHLEN);
492 }
493
494 static struct file_struct *recv_file_entry(struct file_list *flist,
495                                            unsigned short flags, int f)
496 {
497         static time_t modtime;
498         static mode_t mode;
499         static int64 dev;
500         static dev_t rdev;
501         static uint32 rdev_major;
502         static uid_t uid;
503         static gid_t gid;
504         static char lastname[MAXPATHLEN], *lastdir;
505         static int lastdir_depth, lastdir_len = -1;
506         static unsigned int del_hier_name_len = 0;
507         static int in_del_hier = 0;
508         char thisname[MAXPATHLEN];
509         unsigned int l1 = 0, l2 = 0;
510         int alloc_len, basename_len, dirname_len, linkname_len;
511         int extra_len = (flist_extra_cnt - 1) * EXTRA_LEN;
512         OFF_T file_length;
513         char *basename, *dirname, *bp;
514         struct file_struct *file;
515
516         if (!flist) {
517                 modtime = 0, mode = 0;
518                 dev = 0, rdev = MAKEDEV(0, 0);
519                 rdev_major = 0;
520                 uid = 0, gid = 0;
521                 *lastname = '\0';
522                 lastdir_len = -1;
523                 in_del_hier = 0;
524                 return NULL;
525         }
526
527         if (flags & XMIT_SAME_NAME)
528                 l1 = read_byte(f);
529
530         if (flags & XMIT_LONG_NAME)
531                 l2 = read_int(f);
532         else
533                 l2 = read_byte(f);
534
535         if (l2 >= MAXPATHLEN - l1) {
536                 rprintf(FERROR,
537                         "overflow: flags=0x%x l1=%d l2=%d lastname=%s [%s]\n",
538                         flags, l1, l2, lastname, who_am_i());
539                 overflow_exit("recv_file_entry");
540         }
541
542         strlcpy(thisname, lastname, l1 + 1);
543         read_sbuf(f, &thisname[l1], l2);
544         thisname[l1 + l2] = 0;
545
546         strlcpy(lastname, thisname, MAXPATHLEN);
547
548         clean_fname(thisname, 0);
549
550         if (sanitize_paths)
551                 sanitize_path(thisname, thisname, "", 0, NULL);
552
553         if ((basename = strrchr(thisname, '/')) != NULL) {
554                 dirname_len = ++basename - thisname; /* counts future '\0' */
555                 if (lastdir_len == dirname_len - 1
556                     && strncmp(thisname, lastdir, lastdir_len) == 0) {
557                         dirname = lastdir;
558                         dirname_len = 0; /* indicates no copy is needed */
559                 } else
560                         dirname = thisname;
561         } else {
562                 basename = thisname;
563                 dirname = NULL;
564                 dirname_len = 0;
565         }
566         basename_len = strlen(basename) + 1; /* count the '\0' */
567
568         file_length = read_longint(f);
569         if (!(flags & XMIT_SAME_TIME))
570                 modtime = (time_t)read_int(f);
571         if (!(flags & XMIT_SAME_MODE))
572                 mode = from_wire_mode(read_int(f));
573
574         if (chmod_modes && !S_ISLNK(mode))
575                 mode = tweak_mode(mode, chmod_modes);
576
577         if (preserve_uid && !(flags & XMIT_SAME_UID))
578                 uid = (uid_t)read_int(f);
579         if (preserve_gid && !(flags & XMIT_SAME_GID))
580                 gid = (gid_t)read_int(f);
581
582         if ((preserve_devices && IS_DEVICE(mode))
583          || (preserve_specials && IS_SPECIAL(mode))) {
584                 if (protocol_version < 28) {
585                         if (!(flags & XMIT_SAME_RDEV_pre28))
586                                 rdev = (dev_t)read_int(f);
587                 } else {
588                         uint32 rdev_minor;
589                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
590                                 rdev_major = read_int(f);
591                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
592                                 rdev_minor = read_byte(f);
593                         else
594                                 rdev_minor = read_int(f);
595                         rdev = MAKEDEV(rdev_major, rdev_minor);
596                 }
597                 extra_len += 2 * EXTRA_LEN;
598                 file_length = 0;
599         } else if (protocol_version < 28)
600                 rdev = MAKEDEV(0, 0);
601
602 #ifdef SUPPORT_LINKS
603         if (preserve_links && S_ISLNK(mode)) {
604                 linkname_len = read_int(f) + 1; /* count the '\0' */
605                 if (linkname_len <= 0 || linkname_len > MAXPATHLEN) {
606                         rprintf(FERROR, "overflow: linkname_len=%d\n",
607                                 linkname_len - 1);
608                         overflow_exit("recv_file_entry");
609                 }
610         }
611         else
612 #endif
613                 linkname_len = 0;
614
615 #ifdef SUPPORT_HARD_LINKS
616         if (preserve_hard_links && protocol_version < 28 && S_ISREG(mode))
617                 flags |= XMIT_HAS_IDEV_DATA;
618         if (flags & XMIT_HAS_IDEV_DATA) {
619                 extra_len += EXTRA_LEN;
620                 assert(flist->hlink_pool != NULL);
621         }
622 #endif
623
624         if (always_checksum && S_ISREG(mode))
625                 extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
626
627         if (file_length > 0xFFFFFFFFu && S_ISREG(mode))
628                 extra_len += EXTRA_LEN;
629
630         alloc_len = FILE_STRUCT_LEN + extra_len + basename_len + dirname_len
631                   + linkname_len;
632         bp = pool_alloc(flist->file_pool, alloc_len, "recv_file_entry");
633
634         memset(bp, 0, FILE_STRUCT_LEN + extra_len);
635         bp += extra_len;
636         file = (struct file_struct *)bp;
637         bp += FILE_STRUCT_LEN;
638
639         memcpy(bp, basename, basename_len);
640         bp += basename_len + linkname_len; /* skip space for symlink too */
641
642 #ifdef SUPPORT_HARD_LINKS
643         if (flags & XMIT_HAS_IDEV_DATA)
644                 file->flags |= FLAG_HLINKED;
645 #endif
646         file->modtime = modtime;
647         file->len32 = file_length;
648         if (file_length > 0xFFFFFFFFu && S_ISREG(mode)) {
649                 file->flags |= FLAG_LENGTH64;
650                 OPT_EXTRA(file, 0)->unum = (uint32)(file_length >> 32);
651         }
652         file->mode = mode;
653         if (preserve_uid)
654                 F_UID(file) = uid;
655         if (preserve_gid)
656                 F_GID(file) = gid;
657
658         if (dirname_len) {
659                 file->dirname = lastdir = bp;
660                 lastdir_len = dirname_len - 1;
661                 memcpy(bp, dirname, dirname_len - 1);
662                 bp += dirname_len;
663                 bp[-1] = '\0';
664                 lastdir_depth = count_dir_elements(lastdir);
665                 file->dir.depth = lastdir_depth + 1;
666         } else if (dirname) {
667                 file->dirname = dirname; /* we're reusing lastname */
668                 file->dir.depth = lastdir_depth + 1;
669         } else
670                 file->dir.depth = 1;
671
672         if (S_ISDIR(mode)) {
673                 if (basename_len == 1+1 && *basename == '.') /* +1 for '\0' */
674                         file->dir.depth--;
675                 if (flags & XMIT_TOP_DIR) {
676                         in_del_hier = recurse;
677                         del_hier_name_len = file->dir.depth == 0 ? 0 : l1 + l2;
678                         if (relative_paths && del_hier_name_len > 2
679                             && lastname[del_hier_name_len-1] == '.'
680                             && lastname[del_hier_name_len-2] == '/')
681                                 del_hier_name_len -= 2;
682                         file->flags |= FLAG_TOP_DIR | FLAG_XFER_DIR;
683                 } else if (in_del_hier) {
684                         if (!relative_paths || !del_hier_name_len
685                          || (l1 >= del_hier_name_len
686                           && lastname[del_hier_name_len] == '/'))
687                                 file->flags |= FLAG_XFER_DIR;
688                         else
689                                 in_del_hier = 0;
690                 }
691         }
692
693         if ((preserve_devices && IS_DEVICE(mode))
694          || (preserve_specials && IS_SPECIAL(mode))) {
695                 F_DMAJOR(file) = major(rdev);
696                 F_DMINOR(file) = minor(rdev);
697         }
698
699 #ifdef SUPPORT_LINKS
700         if (linkname_len) {
701                 bp = (char*)F_BASENAME(file) + basename_len;
702                 read_sbuf(f, bp, linkname_len - 1);
703                 if (sanitize_paths)
704                         sanitize_path(bp, bp, "", lastdir_depth, NULL);
705         }
706 #endif
707
708 #ifdef SUPPORT_HARD_LINKS
709         if (flags & XMIT_HAS_IDEV_DATA) {
710                 struct idev *idevp = pool_talloc(flist->hlink_pool, struct idev,
711                                                  1, "inode_table");
712                 F_IDEV(file) = idevp;
713                 if (protocol_version < 26) {
714                         idevp->dev = read_int(f);
715                         idevp->ino = read_int(f);
716                 } else {
717                         if (!(flags & XMIT_SAME_DEV))
718                                 dev = read_longint(f);
719                         idevp->dev = dev;
720                         idevp->ino = read_longint(f);
721                 }
722         }
723 #endif
724
725         if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
726                 if (S_ISREG(mode))
727                         bp = (char*)F_SUM(file);
728                 else {
729                         /* Prior to 28, we get a useless set of nulls. */
730                         bp = tmp_sum;
731                 }
732                 read_buf(f, bp, checksum_len);
733         }
734
735         return file;
736 }
737
738 /**
739  * Create a file_struct for a named file by reading its stat()
740  * information and performing extensive checks against global
741  * options.
742  *
743  * @return the new file, or NULL if there was an error or this file
744  * should be excluded.
745  *
746  * @todo There is a small optimization opportunity here to avoid
747  * stat()ing the file in some circumstances, which has a certain cost.
748  * We are called immediately after doing readdir(), and so we may
749  * already know the d_type of the file.  We could for example avoid
750  * statting directories if we're not recursing, but this is not a very
751  * important case.  Some systems may not have d_type.
752  **/
753 struct file_struct *make_file(const char *fname, struct file_list *flist,
754                               STRUCT_STAT *stp, int flags, int filter_level)
755 {
756         static char *lastdir;
757         static int lastdir_len = -1;
758         struct file_struct *file;
759         STRUCT_STAT st;
760         char thisname[MAXPATHLEN];
761         char linkname[MAXPATHLEN];
762         int alloc_len, basename_len, dirname_len, linkname_len;
763         int extra_len = (flist_extra_cnt - 1) * EXTRA_LEN;
764         char *basename, *dirname, *bp;
765
766         if (!flist || !flist->count)    /* Ignore lastdir when invalid. */
767                 lastdir_len = -1;
768
769         if (strlcpy(thisname, fname, sizeof thisname)
770             >= sizeof thisname - flist_dir_len) {
771                 rprintf(FINFO, "skipping overly long name: %s\n", fname);
772                 return NULL;
773         }
774         clean_fname(thisname, 0);
775         if (sanitize_paths)
776                 sanitize_path(thisname, thisname, "", 0, NULL);
777
778         if (stp && S_ISDIR(stp->st_mode)) {
779                 st = *stp; /* Needed for "symlink/." with --relative. */
780                 *linkname = '\0'; /* make IBM code checker happy */
781         } else if (readlink_stat(thisname, &st, linkname) != 0) {
782                 int save_errno = errno;
783                 /* See if file is excluded before reporting an error. */
784                 if (filter_level != NO_FILTERS
785                  && (is_excluded(thisname, 0, filter_level)
786                   || is_excluded(thisname, 1, filter_level))) {
787                         if (ignore_perishable && save_errno != ENOENT)
788                                 non_perishable_cnt++;
789                         return NULL;
790                 }
791                 if (save_errno == ENOENT) {
792 #ifdef SUPPORT_LINKS
793                         /* Avoid "vanished" error if symlink points nowhere. */
794                         if (copy_links && do_lstat(thisname, &st) == 0
795                             && S_ISLNK(st.st_mode)) {
796                                 io_error |= IOERR_GENERAL;
797                                 rprintf(FERROR, "symlink has no referent: %s\n",
798                                         full_fname(thisname));
799                         } else
800 #endif
801                         {
802                                 enum logcode c = am_daemon && protocol_version < 28
803                                     ? FERROR : FINFO;
804                                 io_error |= IOERR_VANISHED;
805                                 rprintf(c, "file has vanished: %s\n",
806                                         full_fname(thisname));
807                         }
808                 } else {
809                         io_error |= IOERR_GENERAL;
810                         rsyserr(FERROR, save_errno, "readlink %s failed",
811                                 full_fname(thisname));
812                 }
813                 return NULL;
814         }
815
816         /* backup.c calls us with filter_level set to NO_FILTERS. */
817         if (filter_level == NO_FILTERS)
818                 goto skip_filters;
819
820         if (S_ISDIR(st.st_mode) && !xfer_dirs) {
821                 rprintf(FINFO, "skipping directory %s\n", thisname);
822                 return NULL;
823         }
824
825         /* -x only affects directories because we need to avoid recursing
826          * into a mount-point directory, not to avoid copying a symlinked
827          * file if -L (or similar) was specified. */
828         if (one_file_system && st.st_dev != filesystem_dev
829          && S_ISDIR(st.st_mode)) {
830                 if (one_file_system > 1) {
831                         if (verbose > 2) {
832                                 rprintf(FINFO, "skipping mount-point dir %s\n",
833                                         thisname);
834                         }
835                         return NULL;
836                 }
837                 flags |= FLAG_MOUNT_DIR;
838         }
839
840         if (is_excluded(thisname, S_ISDIR(st.st_mode) != 0, filter_level)) {
841                 if (ignore_perishable)
842                         non_perishable_cnt++;
843                 return NULL;
844         }
845
846         if (lp_ignore_nonreadable(module_id)) {
847 #ifdef SUPPORT_LINKS
848                 if (!S_ISLNK(st.st_mode))
849 #endif
850                         if (access(thisname, R_OK) != 0)
851                                 return NULL;
852         }
853
854   skip_filters:
855
856         if (verbose > 2) {
857                 rprintf(FINFO, "[%s] make_file(%s,*,%d)\n",
858                         who_am_i(), thisname, filter_level);
859         }
860
861         if ((basename = strrchr(thisname, '/')) != NULL) {
862                 dirname_len = ++basename - thisname; /* counts future '\0' */
863                 if (lastdir_len == dirname_len - 1
864                     && strncmp(thisname, lastdir, lastdir_len) == 0) {
865                         dirname = lastdir;
866                         dirname_len = 0; /* indicates no copy is needed */
867                 } else
868                         dirname = thisname;
869         } else {
870                 basename = thisname;
871                 dirname = NULL;
872                 dirname_len = 0;
873         }
874         basename_len = strlen(basename) + 1; /* count the '\0' */
875
876 #ifdef SUPPORT_LINKS
877         linkname_len = S_ISLNK(st.st_mode) ? strlen(linkname) + 1 : 0;
878 #else
879         linkname_len = 0;
880 #endif
881
882         if (st.st_size > 0xFFFFFFFFu && S_ISREG(st.st_mode))
883                 extra_len += EXTRA_LEN;
884
885         alloc_len = FILE_STRUCT_LEN + extra_len + basename_len + dirname_len
886                   + linkname_len;
887         if (flist)
888                 bp = pool_alloc(flist->file_pool, alloc_len, "make_file");
889         else {
890                 if (!(bp = new_array(char, alloc_len)))
891                         out_of_memory("make_file");
892         }
893
894         memset(bp, 0, FILE_STRUCT_LEN + extra_len);
895         bp += extra_len;
896         file = (struct file_struct *)bp;
897         bp += FILE_STRUCT_LEN;
898
899         memcpy(bp, basename, basename_len);
900         bp += basename_len + linkname_len; /* skip space for symlink too */
901
902 #ifdef SUPPORT_HARD_LINKS
903         if (preserve_hard_links && flist) {
904                 if (protocol_version >= 28
905                  ? (!S_ISDIR(st.st_mode) && st.st_nlink > 1)
906                  : S_ISREG(st.st_mode)) {
907                         tmp_idev.dev = st.st_dev;
908                         tmp_idev.ino = st.st_ino;
909                 } else
910                         tmp_idev.dev = tmp_idev.ino = 0;
911         }
912 #endif
913
914 #ifdef HAVE_STRUCT_STAT_ST_RDEV
915         if (IS_DEVICE(st.st_mode) || IS_SPECIAL(st.st_mode)) {
916                 tmp_rdev = st.st_rdev;
917                 st.st_size = 0;
918         }
919 #endif
920
921         file->flags = flags;
922         file->modtime = st.st_mtime;
923         file->len32 = st.st_size;
924         if (st.st_size > 0xFFFFFFFFu && S_ISREG(st.st_mode)) {
925                 file->flags |= FLAG_LENGTH64;
926                 OPT_EXTRA(file, 0)->unum = (uint32)(st.st_size >> 32);
927         }
928         file->mode = st.st_mode;
929         if (preserve_uid)
930                 F_UID(file) = st.st_uid;
931         if (preserve_gid)
932                 F_GID(file) = st.st_gid;
933
934         if (dirname_len) {
935                 file->dirname = lastdir = bp;
936                 lastdir_len = dirname_len - 1;
937                 memcpy(bp, dirname, dirname_len - 1);
938                 bp += dirname_len;
939                 bp[-1] = '\0';
940         } else if (dirname)
941                 file->dirname = dirname;
942
943 #ifdef SUPPORT_LINKS
944         if (linkname_len) {
945                 bp = (char*)F_BASENAME(file) + basename_len;
946                 memcpy(bp, linkname, linkname_len);
947         }
948 #endif
949
950         if (always_checksum && am_sender && S_ISREG(st.st_mode))
951                 file_checksum(thisname, tmp_sum, st.st_size);
952
953         file->dir.root = flist_dir;
954
955         /* This code is only used by the receiver when it is building
956          * a list of files for a delete pass. */
957         if (keep_dirlinks && linkname_len && flist) {
958                 STRUCT_STAT st2;
959                 int save_mode = file->mode;
960                 file->mode = S_IFDIR; /* Find a directory with our name. */
961                 if (flist_find(the_file_list, file) >= 0
962                     && do_stat(thisname, &st2) == 0 && S_ISDIR(st2.st_mode)) {
963                         file->modtime = st2.st_mtime;
964                         file->len32 = 0;
965                         file->mode = st2.st_mode;
966                         if (preserve_uid)
967                                 F_UID(file) = st2.st_uid;
968                         if (preserve_gid)
969                                 F_GID(file) = st2.st_gid;
970                 } else
971                         file->mode = save_mode;
972         }
973
974         if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
975                 stats.total_size += st.st_size;
976
977         if (basename_len == 0+1)
978                 return NULL;
979
980         return file;
981 }
982
983 /* Only called for temporary file_struct entries created by make_file(). */
984 void unmake_file(struct file_struct *file)
985 {
986         int extra_cnt = flist_extra_cnt - 1 + LEN64_BUMP(file);
987         free(file->extras - extra_cnt);
988 }
989
990 static struct file_struct *send_file_name(int f, struct file_list *flist,
991                                           char *fname, STRUCT_STAT *stp,
992                                           unsigned short flags)
993 {
994         struct file_struct *file;
995
996         file = make_file(fname, flist, stp, flags,
997                          f == -2 ? SERVER_FILTERS : ALL_FILTERS);
998         if (!file)
999                 return NULL;
1000
1001         if (chmod_modes && !S_ISLNK(file->mode))
1002                 file->mode = tweak_mode(file->mode, chmod_modes);
1003
1004         maybe_emit_filelist_progress(flist->count + flist_count_offset);
1005
1006         flist_expand(flist);
1007         flist->files[flist->count++] = file;
1008         send_file_entry(file, f);
1009         return file;
1010 }
1011
1012 static void send_if_directory(int f, struct file_list *flist,
1013                               struct file_struct *file,
1014                               char *fbuf, unsigned int ol)
1015 {
1016         char is_dot_dir = fbuf[ol-1] == '.' && (ol == 1 || fbuf[ol-2] == '/');
1017
1018         if (S_ISDIR(file->mode)
1019             && !(file->flags & FLAG_MOUNT_DIR) && f_name(file, fbuf)) {
1020                 void *save_filters;
1021                 unsigned int len = strlen(fbuf);
1022                 if (len > 1 && fbuf[len-1] == '/')
1023                         fbuf[--len] = '\0';
1024                 if (len >= MAXPATHLEN - 1) {
1025                         io_error |= IOERR_GENERAL;
1026                         rprintf(FERROR, "skipping long-named directory: %s\n",
1027                                 full_fname(fbuf));
1028                         return;
1029                 }
1030                 save_filters = push_local_filters(fbuf, len);
1031                 send_directory(f, flist, fbuf, len);
1032                 pop_local_filters(save_filters);
1033                 fbuf[ol] = '\0';
1034                 if (is_dot_dir)
1035                         fbuf[ol-1] = '.';
1036         }
1037 }
1038
1039 /* This function is normally called by the sender, but the receiving side also
1040  * calls it from get_dirlist() with f set to -1 so that we just construct the
1041  * file list in memory without sending it over the wire.  Also, get_dirlist()
1042  * might call this with f set to -2, which also indicates that local filter
1043  * rules should be ignored. */
1044 static void send_directory(int f, struct file_list *flist,
1045                            char *fbuf, int len)
1046 {
1047         struct dirent *di;
1048         unsigned remainder;
1049         char *p;
1050         DIR *d;
1051         int start = flist->count;
1052
1053         if (!(d = opendir(fbuf))) {
1054                 io_error |= IOERR_GENERAL;
1055                 rsyserr(FERROR, errno, "opendir %s failed", full_fname(fbuf));
1056                 return;
1057         }
1058
1059         p = fbuf + len;
1060         if (len != 1 || *fbuf != '/')
1061                 *p++ = '/';
1062         *p = '\0';
1063         remainder = MAXPATHLEN - (p - fbuf);
1064
1065         for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
1066                 char *dname = d_name(di);
1067                 if (dname[0] == '.' && (dname[1] == '\0'
1068                     || (dname[1] == '.' && dname[2] == '\0')))
1069                         continue;
1070                 if (strlcpy(p, dname, remainder) >= remainder) {
1071                         io_error |= IOERR_GENERAL;
1072                         rprintf(FINFO,
1073                                 "cannot send long-named file %s\n",
1074                                 full_fname(fbuf));
1075                         continue;
1076                 }
1077
1078                 send_file_name(f, flist, fbuf, NULL, 0);
1079         }
1080
1081         fbuf[len] = '\0';
1082
1083         if (errno) {
1084                 io_error |= IOERR_GENERAL;
1085                 rsyserr(FERROR, errno, "readdir(%s)", full_fname(fbuf));
1086         }
1087
1088         closedir(d);
1089
1090         if (recurse) {
1091                 int i, end = flist->count - 1;
1092                 for (i = start; i <= end; i++)
1093                         send_if_directory(f, flist, flist->files[i], fbuf, len);
1094         }
1095 }
1096
1097 struct file_list *send_file_list(int f, int argc, char *argv[])
1098 {
1099         int len;
1100         STRUCT_STAT st;
1101         char *p, *dir, olddir[sizeof curr_dir];
1102         char lastpath[MAXPATHLEN] = "";
1103         struct file_list *flist;
1104         struct timeval start_tv, end_tv;
1105         int64 start_write;
1106         int use_ff_fd = 0;
1107
1108         rprintf(FLOG, "building file list\n");
1109         if (show_filelist_p())
1110                 start_filelist_progress("building file list");
1111
1112         start_write = stats.total_written;
1113         gettimeofday(&start_tv, NULL);
1114
1115         flist = flist_new(0, "send_file_list");
1116
1117         io_start_buffering_out();
1118         if (filesfrom_fd >= 0) {
1119                 if (argv[0] && !push_dir(argv[0], 0)) {
1120                         rsyserr(FERROR, errno, "push_dir %s failed",
1121                                 full_fname(argv[0]));
1122                         exit_cleanup(RERR_FILESELECT);
1123                 }
1124                 use_ff_fd = 1;
1125         }
1126
1127         while (1) {
1128                 char fbuf[MAXPATHLEN];
1129                 char *fn;
1130                 int is_dot_dir;
1131
1132                 if (use_ff_fd) {
1133                         if (read_filesfrom_line(filesfrom_fd, fbuf) == 0)
1134                                 break;
1135                         sanitize_path(fbuf, fbuf, "", 0, NULL);
1136                 } else {
1137                         if (argc-- == 0)
1138                                 break;
1139                         strlcpy(fbuf, *argv++, MAXPATHLEN);
1140                         if (sanitize_paths)
1141                                 sanitize_path(fbuf, fbuf, "", 0, NULL);
1142                 }
1143
1144                 len = strlen(fbuf);
1145                 if (relative_paths) {
1146                         /* We clean up fbuf below. */
1147                         is_dot_dir = 0;
1148                 } else if (!len || fbuf[len - 1] == '/') {
1149                         if (len == 2 && fbuf[0] == '.') {
1150                                 /* Turn "./" into just "." rather than "./." */
1151                                 fbuf[1] = '\0';
1152                         } else {
1153                                 if (len + 1 >= MAXPATHLEN)
1154                                         overflow_exit("send_file_list");
1155                                 fbuf[len++] = '.';
1156                                 fbuf[len] = '\0';
1157                         }
1158                         is_dot_dir = 1;
1159                 } else if (len > 1 && fbuf[len-1] == '.' && fbuf[len-2] == '.'
1160                     && (len == 2 || fbuf[len-3] == '/')) {
1161                         if (len + 2 >= MAXPATHLEN)
1162                                 overflow_exit("send_file_list");
1163                         fbuf[len++] = '/';
1164                         fbuf[len++] = '.';
1165                         fbuf[len] = '\0';
1166                         is_dot_dir = 1;
1167                 } else {
1168                         is_dot_dir = fbuf[len-1] == '.'
1169                                    && (len == 1 || fbuf[len-2] == '/');
1170                 }
1171
1172                 if (link_stat(fbuf, &st, copy_dirlinks) != 0) {
1173                         io_error |= IOERR_GENERAL;
1174                         rsyserr(FERROR, errno, "link_stat %s failed",
1175                                 full_fname(fbuf));
1176                         continue;
1177                 }
1178
1179                 if (S_ISDIR(st.st_mode) && !xfer_dirs) {
1180                         rprintf(FINFO, "skipping directory %s\n", fbuf);
1181                         continue;
1182                 }
1183
1184                 dir = NULL;
1185                 olddir[0] = '\0';
1186
1187                 if (!relative_paths) {
1188                         p = strrchr(fbuf, '/');
1189                         if (p) {
1190                                 *p = '\0';
1191                                 if (p == fbuf)
1192                                         dir = "/";
1193                                 else
1194                                         dir = fbuf;
1195                                 len -= p - fbuf + 1;
1196                                 fn = p + 1;
1197                         } else
1198                                 fn = fbuf;
1199                 } else {
1200                         if ((p = strstr(fbuf, "/./")) != NULL) {
1201                                 *p = '\0';
1202                                 if (p == fbuf)
1203                                         dir = "/";
1204                                 else
1205                                         dir = fbuf;
1206                                 len -= p - fbuf + 3;
1207                                 fn = p + 3;
1208                         } else
1209                                 fn = fbuf;
1210                         /* Get rid of trailing "/" and "/.". */
1211                         while (len) {
1212                                 if (fn[len - 1] == '/') {
1213                                         is_dot_dir = 1;
1214                                         if (!--len && !dir) {
1215                                                 len++;
1216                                                 break;
1217                                         }
1218                                 }
1219                                 else if (len >= 2 && fn[len - 1] == '.'
1220                                                   && fn[len - 2] == '/') {
1221                                         is_dot_dir = 1;
1222                                         if (!(len -= 2) && !dir) {
1223                                                 len++;
1224                                                 break;
1225                                         }
1226                                 } else
1227                                         break;
1228                         }
1229                         if (len == 1 && fn[0] == '/')
1230                                 fn[len++] = '.';
1231                         fn[len] = '\0';
1232                         /* Reject a ".." dir in the active part of the path. */
1233                         for (p = fn; (p = strstr(p, "..")) != NULL; p += 2) {
1234                                 if ((p[2] == '/' || p[2] == '\0')
1235                                  && (p == fn || p[-1] == '/')) {
1236                                         rprintf(FERROR,
1237                                             "found \"..\" dir in relative path: %s\n",
1238                                             fbuf);
1239                                         exit_cleanup(RERR_SYNTAX);
1240                                 }
1241                         }
1242                 }
1243
1244                 if (!*fn) {
1245                         len = 1;
1246                         fn = ".";
1247                 }
1248
1249                 if (dir && *dir) {
1250                         static const char *lastdir;
1251                         static int lastdir_len;
1252
1253                         strlcpy(olddir, curr_dir, sizeof olddir);
1254
1255                         if (!push_dir(dir, 0)) {
1256                                 io_error |= IOERR_GENERAL;
1257                                 rsyserr(FERROR, errno, "push_dir %s failed",
1258                                         full_fname(dir));
1259                                 continue;
1260                         }
1261
1262                         if (lastdir && strcmp(lastdir, dir) == 0) {
1263                                 flist_dir = lastdir;
1264                                 flist_dir_len = lastdir_len;
1265                         } else {
1266                                 flist_dir = lastdir = strdup(dir);
1267                                 flist_dir_len = lastdir_len = strlen(dir);
1268                         }
1269                 }
1270
1271                 if (fn != fbuf)
1272                         memmove(fbuf, fn, len + 1);
1273
1274                 if (implied_dirs && (p=strrchr(fbuf,'/')) && p != fbuf) {
1275                         /* Send the implied directories at the start of the
1276                          * source spec, so we get their permissions right. */
1277                         char *lp = lastpath, *slash = fbuf;
1278                         *p = '\0';
1279                         /* Skip any initial directories in our path that we
1280                          * have in common with lastpath. */
1281                         for (fn = fbuf; *fn && *lp == *fn; lp++, fn++) {
1282                                 if (*fn == '/')
1283                                         slash = fn;
1284                         }
1285                         *p = '/';
1286                         if (fn != p || (*lp && *lp != '/')) {
1287                                 int save_copy_links = copy_links;
1288                                 int save_xfer_dirs = xfer_dirs;
1289                                 copy_links |= copy_unsafe_links;
1290                                 xfer_dirs = 1;
1291                                 while ((slash = strchr(slash+1, '/')) != 0) {
1292                                         *slash = '\0';
1293                                         send_file_name(f, flist, fbuf, NULL, 0);
1294                                         *slash = '/';
1295                                 }
1296                                 copy_links = save_copy_links;
1297                                 xfer_dirs = save_xfer_dirs;
1298                                 *p = '\0';
1299                                 strlcpy(lastpath, fbuf, sizeof lastpath);
1300                                 *p = '/';
1301                         }
1302                 }
1303
1304                 if (one_file_system)
1305                         filesystem_dev = st.st_dev;
1306
1307                 if (recurse || (xfer_dirs && is_dot_dir)) {
1308                         struct file_struct *file;
1309                         file = send_file_name(f, flist, fbuf, &st, FLAG_TOP_DIR);
1310                         if (file)
1311                                 send_if_directory(f, flist, file, fbuf, len);
1312                 } else
1313                         send_file_name(f, flist, fbuf, &st, 0);
1314
1315                 if (olddir[0]) {
1316                         flist_dir = NULL;
1317                         flist_dir_len = 0;
1318                         if (!pop_dir(olddir)) {
1319                                 rsyserr(FERROR, errno, "pop_dir %s failed",
1320                                         full_fname(olddir));
1321                                 exit_cleanup(RERR_FILESELECT);
1322                         }
1323                 }
1324         }
1325
1326         gettimeofday(&end_tv, NULL);
1327         stats.flist_buildtime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1328                               + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1329         if (stats.flist_buildtime == 0)
1330                 stats.flist_buildtime = 1;
1331         start_tv = end_tv;
1332
1333         send_file_entry(NULL, f);
1334
1335         if (show_filelist_p())
1336                 finish_filelist_progress(flist);
1337
1338         gettimeofday(&end_tv, NULL);
1339         stats.flist_xfertime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1340                              + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1341
1342         /* Sort the list without removing any duplicates.  This allows the
1343          * receiving side to ask for any name they like, which gives us the
1344          * flexibility to change the way we unduplicate names in the future
1345          * without causing a compatibility problem with older versions. */
1346         clean_flist(flist, 0, 0);
1347
1348         if (!numeric_ids)
1349                 send_uid_list(f);
1350
1351         /* send the io_error flag */
1352         write_int(f, lp_ignore_errors(module_id) ? 0 : io_error);
1353
1354         io_end_buffering();
1355         stats.flist_size = stats.total_written - start_write;
1356         stats.num_files = flist->count;
1357
1358         if (verbose > 3)
1359                 output_flist(flist);
1360
1361         if (verbose > 2)
1362                 rprintf(FINFO, "send_file_list done\n");
1363
1364         return flist;
1365 }
1366
1367 struct file_list *recv_file_list(int f)
1368 {
1369         struct file_list *flist;
1370         unsigned short flags;
1371         int64 start_read;
1372
1373         rprintf(FLOG, "receiving file list\n");
1374         if (show_filelist_p())
1375                 start_filelist_progress("receiving file list");
1376
1377         start_read = stats.total_read;
1378
1379         flist = flist_new(WITH_HLINK, "recv_file_list");
1380
1381
1382         while ((flags = read_byte(f)) != 0) {
1383                 struct file_struct *file;
1384
1385                 flist_expand(flist);
1386
1387                 if (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS))
1388                         flags |= read_byte(f) << 8;
1389                 file = recv_file_entry(flist, flags, f);
1390
1391                 if (S_ISREG(file->mode) || S_ISLNK(file->mode))
1392                         stats.total_size += F_LENGTH(file);
1393
1394                 flist->files[flist->count++] = file;
1395
1396                 maybe_emit_filelist_progress(flist->count);
1397
1398                 if (verbose > 2) {
1399                         rprintf(FINFO, "recv_file_name(%s)\n",
1400                                 f_name(file, NULL));
1401                 }
1402         }
1403         recv_file_entry(NULL, 0, 0); /* Signal that we're done. */
1404
1405         if (verbose > 2)
1406                 rprintf(FINFO, "received %d names\n", flist->count);
1407
1408         if (show_filelist_p())
1409                 finish_filelist_progress(flist);
1410
1411         clean_flist(flist, relative_paths, 1);
1412
1413         if (f >= 0) {
1414                 recv_uid_list(f, flist);
1415
1416                 /* Recv the io_error flag */
1417                 if (lp_ignore_errors(module_id) || ignore_errors)
1418                         read_int(f);
1419                 else
1420                         io_error |= read_int(f);
1421         }
1422
1423         if (verbose > 3)
1424                 output_flist(flist);
1425
1426         if (list_only) {
1427                 int i;
1428                 for (i = 0; i < flist->count; i++)
1429                         list_file_entry(flist->files[i]);
1430         }
1431
1432         if (verbose > 2)
1433                 rprintf(FINFO, "recv_file_list done\n");
1434
1435         stats.flist_size = stats.total_read - start_read;
1436         stats.num_files = flist->count;
1437
1438         return flist;
1439 }
1440
1441 static int file_compare(struct file_struct **file1, struct file_struct **file2)
1442 {
1443         return f_name_cmp(*file1, *file2);
1444 }
1445
1446 /* Search for an identically-named item in the file list.  Note that the
1447  * items must agree in their directory-ness, or no match is returned. */
1448 int flist_find(struct file_list *flist, struct file_struct *f)
1449 {
1450         int low = flist->low, high = flist->high;
1451         int diff, mid, mid_up;
1452
1453         while (low <= high) {
1454                 mid = (low + high) / 2;
1455                 if (F_IS_ACTIVE(flist->files[mid]))
1456                         mid_up = mid;
1457                 else {
1458                         /* Scan for the next non-empty entry using the cached
1459                          * distance values.  If the value isn't fully up-to-
1460                          * date, update it. */
1461                         mid_up = mid + flist->files[mid]->dir.depth;
1462                         if (!F_IS_ACTIVE(flist->files[mid_up])) {
1463                                 do {
1464                                     mid_up += flist->files[mid_up]->dir.depth;
1465                                 } while (!F_IS_ACTIVE(flist->files[mid_up]));
1466                                 flist->files[mid]->dir.depth = mid_up - mid;
1467                         }
1468                         if (mid_up > high) {
1469                                 /* If there's nothing left above us, set high to
1470                                  * a non-empty entry below us and continue. */
1471                                 high = mid - (int)flist->files[mid]->len32;
1472                                 if (!F_IS_ACTIVE(flist->files[high])) {
1473                                         do {
1474                                             high -= (int)flist->files[high]->len32;
1475                                         } while (!F_IS_ACTIVE(flist->files[high]));
1476                                         flist->files[mid]->len32 = mid - high;
1477                                 }
1478                                 continue;
1479                         }
1480                 }
1481                 diff = f_name_cmp(flist->files[mid_up], f);
1482                 if (diff == 0) {
1483                         if (protocol_version < 29
1484                             && S_ISDIR(flist->files[mid_up]->mode)
1485                             != S_ISDIR(f->mode))
1486                                 return -1;
1487                         return mid_up;
1488                 }
1489                 if (diff < 0)
1490                         low = mid_up + 1;
1491                 else
1492                         high = mid - 1;
1493         }
1494         return -1;
1495 }
1496
1497 /*
1498  * Free up any resources a file_struct has allocated
1499  * and clear the file.
1500  */
1501 void clear_file(struct file_struct *file)
1502 {
1503         memset((char*)file + EXTRA_LEN, 0, FILE_STRUCT_LEN - EXTRA_LEN + 1);
1504         /* In an empty entry, dir.depth is an offset to the next non-empty
1505          * entry.  Likewise for len32 in the opposite direction.  We assume
1506          * that we're alone for now since flist_find() will adjust the counts
1507          * it runs into that aren't up-to-date. */
1508         file->len32 = file->dir.depth = 1;
1509 }
1510
1511 /*
1512  * allocate a new file list
1513  */
1514 struct file_list *flist_new(int with_hlink, char *msg)
1515 {
1516         struct file_list *flist;
1517
1518         flist = new(struct file_list);
1519         if (!flist)
1520                 out_of_memory(msg);
1521
1522         memset(flist, 0, sizeof flist[0]);
1523
1524         if (!(flist->file_pool = pool_create(FILE_EXTENT, 0, out_of_memory, POOL_INTERN)))
1525                 out_of_memory(msg);
1526
1527 #ifdef SUPPORT_HARD_LINKS
1528         if (with_hlink && preserve_hard_links) {
1529                 if (!(flist->hlink_pool = pool_create(HLINK_EXTENT,
1530                     sizeof (struct idev), out_of_memory, POOL_INTERN)))
1531                         out_of_memory(msg);
1532         }
1533 #endif
1534
1535         return flist;
1536 }
1537
1538 /*
1539  * free up all elements in a flist
1540  */
1541 void flist_free(struct file_list *flist)
1542 {
1543         pool_destroy(flist->file_pool);
1544         pool_destroy(flist->hlink_pool);
1545         free(flist->files);
1546         free(flist);
1547 }
1548
1549 /*
1550  * This routine ensures we don't have any duplicate names in our file list.
1551  * duplicate names can cause corruption because of the pipelining
1552  */
1553 static void clean_flist(struct file_list *flist, int strip_root, int no_dups)
1554 {
1555         char fbuf[MAXPATHLEN];
1556         int i, prev_i = 0;
1557
1558         if (!flist)
1559                 return;
1560         if (flist->count == 0) {
1561                 flist->high = -1;
1562                 return;
1563         }
1564
1565         qsort(flist->files, flist->count,
1566             sizeof flist->files[0], (int (*)())file_compare);
1567
1568         for (i = no_dups? 0 : flist->count; i < flist->count; i++) {
1569                 if (F_IS_ACTIVE(flist->files[i])) {
1570                         prev_i = i;
1571                         break;
1572                 }
1573         }
1574         flist->low = prev_i;
1575         while (++i < flist->count) {
1576                 int j;
1577                 struct file_struct *file = flist->files[i];
1578
1579                 if (!F_IS_ACTIVE(file))
1580                         continue;
1581                 if (f_name_cmp(file, flist->files[prev_i]) == 0)
1582                         j = prev_i;
1583                 else if (protocol_version >= 29 && S_ISDIR(file->mode)) {
1584                         int save_mode = file->mode;
1585                         /* Make sure that this directory doesn't duplicate a
1586                          * non-directory earlier in the list. */
1587                         flist->high = prev_i;
1588                         file->mode = S_IFREG;
1589                         j = flist_find(flist, file);
1590                         file->mode = save_mode;
1591                 } else
1592                         j = -1;
1593                 if (j >= 0) {
1594                         struct file_struct *fp = flist->files[j];
1595                         int keep, drop;
1596                         /* If one is a dir and the other is not, we want to
1597                          * keep the dir because it might have contents in the
1598                          * list. */
1599                         if (S_ISDIR(file->mode) != S_ISDIR(fp->mode)) {
1600                                 if (S_ISDIR(file->mode))
1601                                         keep = i, drop = j;
1602                                 else
1603                                         keep = j, drop = i;
1604                         } else
1605                                 keep = j, drop = i;
1606                         if (verbose > 1 && !am_server) {
1607                                 rprintf(FINFO,
1608                                         "removing duplicate name %s from file list (%d)\n",
1609                                         f_name(file, fbuf), drop);
1610                         }
1611                         /* Make sure we don't lose track of a user-specified
1612                          * top directory. */
1613                         flist->files[keep]->flags |= flist->files[drop]->flags
1614                                                    & (FLAG_TOP_DIR|FLAG_XFER_DIR);
1615
1616                         clear_file(flist->files[drop]);
1617
1618                         if (keep == i) {
1619                                 if (flist->low == drop) {
1620                                         for (j = drop + 1;
1621                                              j < i && !F_IS_ACTIVE(flist->files[j]);
1622                                              j++) {}
1623                                         flist->low = j;
1624                                 }
1625                                 prev_i = i;
1626                         }
1627                 } else
1628                         prev_i = i;
1629         }
1630         flist->high = no_dups ? prev_i : flist->count - 1;
1631
1632         if (strip_root) {
1633                 /* We need to strip off the leading slashes for relative
1634                  * paths, but this must be done _after_ the sorting phase. */
1635                 for (i = flist->low; i <= flist->high; i++) {
1636                         struct file_struct *file = flist->files[i];
1637
1638                         if (!file->dirname)
1639                                 continue;
1640                         while (*file->dirname == '/')
1641                                 file->dirname++;
1642                         if (!*file->dirname)
1643                                 file->dirname = NULL;
1644                 }
1645         }
1646
1647         if (prune_empty_dirs && no_dups) {
1648                 int j, prev_depth = 0;
1649
1650                 prev_i = 0; /* It's OK that this isn't really true. */
1651
1652                 for (i = flist->low; i <= flist->high; i++) {
1653                         struct file_struct *fp, *file = flist->files[i];
1654
1655                         /* This temporarily abuses the dir.depth value for a
1656                          * directory that is in a chain that might get pruned.
1657                          * We restore the old value if it gets a reprieve. */
1658                         if (S_ISDIR(file->mode) && file->dir.depth) {
1659                                 /* Dump empty dirs when coming back down. */
1660                                 for (j = prev_depth; j >= file->dir.depth; j--) {
1661                                         fp = flist->files[prev_i];
1662                                         if (fp->dir.depth >= 0)
1663                                                 break;
1664                                         prev_i = -fp->dir.depth-1;
1665                                         clear_file(fp);
1666                                 }
1667                                 prev_depth = file->dir.depth;
1668                                 if (is_excluded(f_name(file, fbuf), 1,
1669                                                        ALL_FILTERS)) {
1670                                         /* Keep dirs through this dir. */
1671                                         for (j = prev_depth-1; ; j--) {
1672                                                 fp = flist->files[prev_i];
1673                                                 if (fp->dir.depth >= 0)
1674                                                         break;
1675                                                 prev_i = -fp->dir.depth-1;
1676                                                 fp->dir.depth = j;
1677                                         }
1678                                 } else
1679                                         file->dir.depth = -prev_i-1;
1680                                 prev_i = i;
1681                         } else {
1682                                 /* Keep dirs through this non-dir. */
1683                                 for (j = prev_depth; ; j--) {
1684                                         fp = flist->files[prev_i];
1685                                         if (fp->dir.depth >= 0)
1686                                                 break;
1687                                         prev_i = -fp->dir.depth-1;
1688                                         fp->dir.depth = j;
1689                                 }
1690                         }
1691                 }
1692                 /* Dump empty all remaining empty dirs. */
1693                 while (1) {
1694                         struct file_struct *fp = flist->files[prev_i];
1695                         if (fp->dir.depth >= 0)
1696                                 break;
1697                         prev_i = -fp->dir.depth-1;
1698                         clear_file(fp);
1699                 }
1700
1701                 for (i = flist->low; i <= flist->high; i++) {
1702                         if (F_IS_ACTIVE(flist->files[i]))
1703                                 break;
1704                 }
1705                 flist->low = i;
1706                 for (i = flist->high; i >= flist->low; i--) {
1707                         if (F_IS_ACTIVE(flist->files[i]))
1708                                 break;
1709                 }
1710                 flist->high = i;
1711         }
1712 }
1713
1714 static void output_flist(struct file_list *flist)
1715 {
1716         char uidbuf[16], gidbuf[16], depthbuf[16];
1717         struct file_struct *file;
1718         const char *dir, *slash, *name, *trail;
1719         const char *who = who_am_i();
1720         int i;
1721
1722         for (i = 0; i < flist->count; i++) {
1723                 file = flist->files[i];
1724                 if ((am_root || am_sender) && preserve_uid) {
1725                         snprintf(uidbuf, sizeof uidbuf, " uid=%ld",
1726                                  (long)F_UID(file));
1727                 } else
1728                         *uidbuf = '\0';
1729                 if (preserve_gid && F_GID(file) != GID_NONE) {
1730                         snprintf(gidbuf, sizeof gidbuf, " gid=%ld",
1731                                  (long)F_GID(file));
1732                 } else
1733                         *gidbuf = '\0';
1734                 if (!am_sender)
1735                         snprintf(depthbuf, sizeof depthbuf, "%d", file->dir.depth);
1736                 if (F_IS_ACTIVE(file)) {
1737                         if ((dir = file->dirname) == NULL)
1738                                 dir = slash = "";
1739                         else
1740                                 slash = "/";
1741                         name = F_BASENAME(file);
1742                         trail = S_ISDIR(file->mode) ? "/" : "";
1743                 } else
1744                         dir = slash = name = trail = "";
1745                 rprintf(FINFO, "[%s] i=%d %s %s%s%s%s mode=0%o len=%.0f%s%s flags=%x\n",
1746                         who, i, am_sender ? NS(file->dir.root) : depthbuf,
1747                         dir, slash, name, trail, (int)file->mode,
1748                         (double)F_LENGTH(file), uidbuf, gidbuf, file->flags);
1749         }
1750 }
1751
1752 enum fnc_state { s_DIR, s_SLASH, s_BASE, s_TRAILING };
1753 enum fnc_type { t_PATH, t_ITEM };
1754
1755 /* Compare the names of two file_struct entities, similar to how strcmp()
1756  * would do if it were operating on the joined strings.
1757  *
1758  * Some differences beginning with protocol_version 29: (1) directory names
1759  * are compared with an assumed trailing slash so that they compare in a
1760  * way that would cause them to sort immediately prior to any content they
1761  * may have; (2) a directory of any name compares after a non-directory of
1762  * any name at the same depth; (3) a directory with name "." compares prior
1763  * to anything else.  These changes mean that a directory and a non-dir
1764  * with the same name will not compare as equal (protocol_version >= 29).
1765  *
1766  * The dirname component can be an empty string, but the basename component
1767  * cannot (and never is in the current codebase).  The basename component
1768  * may be NULL (for a removed item), in which case it is considered to be
1769  * after any existing item. */
1770 int f_name_cmp(struct file_struct *f1, struct file_struct *f2)
1771 {
1772         int dif;
1773         const uchar *c1, *c2;
1774         enum fnc_state state1, state2;
1775         enum fnc_type type1, type2;
1776         enum fnc_type t_path = protocol_version >= 29 ? t_PATH : t_ITEM;
1777
1778         if (!f1 || !F_IS_ACTIVE(f1)) {
1779                 if (!f2 || !F_IS_ACTIVE(f2))
1780                         return 0;
1781                 return -1;
1782         }
1783         if (!f2 || !F_IS_ACTIVE(f2))
1784                 return 1;
1785
1786         c1 = (uchar*)f1->dirname;
1787         c2 = (uchar*)f2->dirname;
1788         if (c1 == c2)
1789                 c1 = c2 = NULL;
1790         if (!c1) {
1791                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
1792                 c1 = (uchar*)F_BASENAME(f1);
1793                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
1794                         type1 = t_ITEM;
1795                         state1 = s_TRAILING;
1796                         c1 = (uchar*)"";
1797                 } else
1798                         state1 = s_BASE;
1799         } else {
1800                 type1 = t_path;
1801                 state1 = s_DIR;
1802         }
1803         if (!c2) {
1804                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
1805                 c2 = (uchar*)F_BASENAME(f2);
1806                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
1807                         type2 = t_ITEM;
1808                         state2 = s_TRAILING;
1809                         c2 = (uchar*)"";
1810                 } else
1811                         state2 = s_BASE;
1812         } else {
1813                 type2 = t_path;
1814                 state2 = s_DIR;
1815         }
1816
1817         if (type1 != type2)
1818                 return type1 == t_PATH ? 1 : -1;
1819
1820         do {
1821                 if (!*c1) {
1822                         switch (state1) {
1823                         case s_DIR:
1824                                 state1 = s_SLASH;
1825                                 c1 = (uchar*)"/";
1826                                 break;
1827                         case s_SLASH:
1828                                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
1829                                 c1 = (uchar*)F_BASENAME(f1);
1830                                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
1831                                         type1 = t_ITEM;
1832                                         state1 = s_TRAILING;
1833                                         c1 = (uchar*)"";
1834                                 } else
1835                                         state1 = s_BASE;
1836                                 break;
1837                         case s_BASE:
1838                                 state1 = s_TRAILING;
1839                                 if (type1 == t_PATH) {
1840                                         c1 = (uchar*)"/";
1841                                         break;
1842                                 }
1843                                 /* FALL THROUGH */
1844                         case s_TRAILING:
1845                                 type1 = t_ITEM;
1846                                 break;
1847                         }
1848                         if (*c2 && type1 != type2)
1849                                 return type1 == t_PATH ? 1 : -1;
1850                 }
1851                 if (!*c2) {
1852                         switch (state2) {
1853                         case s_DIR:
1854                                 state2 = s_SLASH;
1855                                 c2 = (uchar*)"/";
1856                                 break;
1857                         case s_SLASH:
1858                                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
1859                                 c2 = (uchar*)F_BASENAME(f2);
1860                                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
1861                                         type2 = t_ITEM;
1862                                         state2 = s_TRAILING;
1863                                         c2 = (uchar*)"";
1864                                 } else
1865                                         state2 = s_BASE;
1866                                 break;
1867                         case s_BASE:
1868                                 state2 = s_TRAILING;
1869                                 if (type2 == t_PATH) {
1870                                         c2 = (uchar*)"/";
1871                                         break;
1872                                 }
1873                                 /* FALL THROUGH */
1874                         case s_TRAILING:
1875                                 if (!*c1)
1876                                         return 0;
1877                                 type2 = t_ITEM;
1878                                 break;
1879                         }
1880                         if (type1 != type2)
1881                                 return type1 == t_PATH ? 1 : -1;
1882                 }
1883         } while ((dif = (int)*c1++ - (int)*c2++) == 0);
1884
1885         return dif;
1886 }
1887
1888 char *f_name_buf(void)
1889 {
1890         static char names[5][MAXPATHLEN];
1891         static unsigned int n;
1892
1893         n = (n + 1) % (sizeof names / sizeof names[0]);
1894
1895         return names[n];
1896 }
1897
1898 /* Return a copy of the full filename of a flist entry, using the indicated
1899  * buffer or one of 5 static buffers if fbuf is NULL.  No size-checking is
1900  * done because we checked the size when creating the file_struct entry.
1901  */
1902 char *f_name(struct file_struct *f, char *fbuf)
1903 {
1904         if (!f || !F_IS_ACTIVE(f))
1905                 return NULL;
1906
1907         if (!fbuf)
1908                 fbuf = f_name_buf();
1909
1910         if (f->dirname) {
1911                 int len = strlen(f->dirname);
1912                 memcpy(fbuf, f->dirname, len);
1913                 fbuf[len] = '/';
1914                 strlcpy(fbuf + len + 1, F_BASENAME(f), MAXPATHLEN - (len + 1));
1915         } else
1916                 strlcpy(fbuf, F_BASENAME(f), MAXPATHLEN);
1917
1918         return fbuf;
1919 }
1920
1921 /* Do a non-recursive scan of the named directory, possibly ignoring all
1922  * exclude rules except for the daemon's.  If "dlen" is >=0, it is the length
1923  * of the dirname string, and also indicates that "dirname" is a MAXPATHLEN
1924  * buffer (the functions we call will append names onto the end, but the old
1925  * dir value will be restored on exit). */
1926 struct file_list *get_dirlist(char *dirname, int dlen,
1927                               int ignore_filter_rules)
1928 {
1929         struct file_list *dirlist;
1930         char dirbuf[MAXPATHLEN];
1931         int save_recurse = recurse;
1932         int save_xfer_dirs = xfer_dirs;
1933
1934         if (dlen < 0) {
1935                 dlen = strlcpy(dirbuf, dirname, MAXPATHLEN);
1936                 if (dlen >= MAXPATHLEN)
1937                         return NULL;
1938                 dirname = dirbuf;
1939         }
1940
1941         dirlist = flist_new(WITHOUT_HLINK, "get_dirlist");
1942
1943         recurse = 0;
1944         xfer_dirs = 1;
1945         send_directory(ignore_filter_rules ? -2 : -1, dirlist, dirname, dlen);
1946         xfer_dirs = save_xfer_dirs;
1947         recurse = save_recurse;
1948         if (do_progress)
1949                 flist_count_offset += dirlist->count;
1950
1951         clean_flist(dirlist, 0, 0);
1952
1953         if (verbose > 3)
1954                 output_flist(dirlist);
1955
1956         return dirlist;
1957 }