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