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