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