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