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