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