The calls into the exclude system changed a little for the new --filter
[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 exclude_list_struct exclude_list;
74 extern struct exclude_list_struct server_exclude_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
82 static void clean_flist(struct file_list *flist, int strip_root, int no_dups);
83 static void output_flist(struct file_list *flist, const char *whose_list);
84
85 void init_flist(void)
86 {
87         struct file_struct f;
88
89         /* Figure out how big the file_struct is without trailing padding */
90         file_struct_len = offsetof(struct file_struct, flags) + sizeof f.flags;
91 }
92
93
94 static int show_filelist_p(void)
95 {
96         return verbose && xfer_dirs && !am_server;
97 }
98
99 static void start_filelist_progress(char *kind)
100 {
101         rprintf(FINFO, "%s ... ", kind);
102         if (verbose > 1 || do_progress)
103                 rprintf(FINFO, "\n");
104         rflush(FINFO);
105 }
106
107
108 static void emit_filelist_progress(const struct file_list *flist)
109 {
110         rprintf(FINFO, " %d files...\r", flist->count);
111 }
112
113
114 static void maybe_emit_filelist_progress(const struct file_list *flist)
115 {
116         if (do_progress && show_filelist_p() && (flist->count % 100) == 0)
117                 emit_filelist_progress(flist);
118 }
119
120
121 static void finish_filelist_progress(const struct file_list *flist)
122 {
123         if (do_progress) {
124                 /* This overwrites the progress line */
125                 rprintf(FINFO, "%d file%sto consider\n",
126                         flist->count, flist->count == 1 ? " " : "s ");
127         } else
128                 rprintf(FINFO, "done\n");
129 }
130
131 void show_flist_stats(void)
132 {
133         /* Nothing yet */
134 }
135
136
137 static void list_file_entry(struct file_struct *f)
138 {
139         char perms[11];
140
141         if (!f->basename) {
142                 /* this can happen if duplicate names were removed */
143                 return;
144         }
145
146         permstring(perms, f->mode);
147
148 #if SUPPORT_LINKS
149         if (preserve_links && S_ISLNK(f->mode)) {
150                 rprintf(FINFO, "%s %11.0f %s %s -> %s\n",
151                         perms,
152                         (double)f->length, timestring(f->modtime),
153                         f_name(f), f->u.link);
154         } else
155 #endif
156         {
157                 rprintf(FINFO, "%s %11.0f %s %s\n",
158                         perms,
159                         (double)f->length, timestring(f->modtime),
160                         f_name(f));
161         }
162 }
163
164
165 /**
166  * Stat either a symlink or its referent, depending on the settings of
167  * copy_links, copy_unsafe_links, etc.
168  *
169  * @retval -1 on error
170  *
171  * @retval 0 for success
172  *
173  * @post If @p path is a symlink, then @p linkbuf (of size @c
174  * MAXPATHLEN) contains the symlink target.
175  *
176  * @post @p buffer contains information about the link or the
177  * referrent as appropriate, if they exist.
178  **/
179 static int readlink_stat(const char *path, STRUCT_STAT *buffer, char *linkbuf)
180 {
181 #if SUPPORT_LINKS
182         if (copy_links)
183                 return do_stat(path, buffer);
184         if (link_stat(path, buffer, 0) < 0)
185                 return -1;
186         if (S_ISLNK(buffer->st_mode)) {
187                 int l = readlink((char *)path, linkbuf, MAXPATHLEN - 1);
188                 if (l == -1)
189                         return -1;
190                 linkbuf[l] = 0;
191                 if (copy_unsafe_links && unsafe_symlink(linkbuf, path)) {
192                         if (verbose > 1) {
193                                 rprintf(FINFO,"copying unsafe symlink \"%s\" -> \"%s\"\n",
194                                         path, linkbuf);
195                         }
196                         return do_stat(path, buffer);
197                 }
198         }
199         return 0;
200 #else
201         return do_stat(path, buffer);
202 #endif
203 }
204
205 int link_stat(const char *path, STRUCT_STAT *buffer, int follow_dirlinks)
206 {
207 #if SUPPORT_LINKS
208         if (copy_links)
209                 return do_stat(path, buffer);
210         if (do_lstat(path, buffer) < 0)
211                 return -1;
212         if (follow_dirlinks && S_ISLNK(buffer->st_mode)) {
213                 STRUCT_STAT st;
214                 if (do_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
215                         *buffer = st;
216         }
217         return 0;
218 #else
219         return do_stat(path, buffer);
220 #endif
221 }
222
223 /*
224  * This function is used to check if a file should be included/excluded
225  * from the list of files based on its name and type etc.  The value of
226  * exclude_level is set to either SERVER_EXCLUDES or ALL_EXCLUDES.
227  */
228 static int check_exclude_file(char *fname, int is_dir, int exclude_level)
229 {
230 #if 0 /* This currently never happens, so avoid a useless compare. */
231         if (exclude_level == NO_EXCLUDES)
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_exclude_list.head
246             && check_exclude(&server_exclude_list, fname, is_dir) < 0)
247                 return 1;
248         if (exclude_level != ALL_EXCLUDES)
249                 return 0;
250         if (exclude_list.head
251             && check_exclude(&exclude_list, fname, is_dir) < 0)
252                 return 1;
253         return 0;
254 }
255
256 /* used by the one_file_system code */
257 static dev_t filesystem_dev;
258
259 static void set_filesystem(char *fname)
260 {
261         STRUCT_STAT st;
262         if (do_stat(fname, &st) != 0)
263                 return;
264         filesystem_dev = st.st_dev;
265 }
266
267
268 static int to_wire_mode(mode_t mode)
269 {
270 #if SUPPORT_LINKS
271         if (S_ISLNK(mode) && (_S_IFLNK != 0120000))
272                 return (mode & ~(_S_IFMT)) | 0120000;
273 #endif
274         return (int)mode;
275 }
276
277 static mode_t from_wire_mode(int mode)
278 {
279         if ((mode & (_S_IFMT)) == 0120000 && (_S_IFLNK != 0120000))
280                 return (mode & ~(_S_IFMT)) | _S_IFLNK;
281         return (mode_t)mode;
282 }
283
284
285 static void send_directory(int f, struct file_list *flist, char *dir);
286
287 static char *flist_dir;
288 static int flist_dir_len;
289
290
291 /**
292  * Make sure @p flist is big enough to hold at least @p flist->count
293  * entries.
294  **/
295 void flist_expand(struct file_list *flist)
296 {
297         struct file_struct **new_ptr;
298
299         if (flist->count < flist->malloced)
300                 return;
301
302         if (flist->malloced < FLIST_START)
303                 flist->malloced = FLIST_START;
304         else if (flist->malloced >= FLIST_LINEAR)
305                 flist->malloced += FLIST_LINEAR;
306         else
307                 flist->malloced *= 2;
308
309         /*
310          * In case count jumped or we are starting the list
311          * with a known size just set it.
312          */
313         if (flist->malloced < flist->count)
314                 flist->malloced = flist->count;
315
316         new_ptr = realloc_array(flist->files, struct file_struct *,
317                                 flist->malloced);
318
319         if (verbose >= 2 && flist->malloced != FLIST_START) {
320                 rprintf(FINFO, "[%s] expand file_list to %.0f bytes, did%s move\n",
321                     who_am_i(),
322                     (double)sizeof flist->files[0] * flist->malloced,
323                     (new_ptr == flist->files) ? " not" : "");
324         }
325
326         flist->files = new_ptr;
327
328         if (!flist->files)
329                 out_of_memory("flist_expand");
330 }
331
332 void send_file_entry(struct file_struct *file, int f, unsigned short base_flags)
333 {
334         unsigned short flags;
335         static time_t modtime;
336         static mode_t mode;
337         static int64 dev;
338         static dev_t rdev;
339         static uint32 rdev_major;
340         static uid_t uid;
341         static gid_t gid;
342         static char lastname[MAXPATHLEN];
343         char fname[MAXPATHLEN];
344         int l1, l2;
345
346         if (f == -1)
347                 return;
348
349         if (!file) {
350                 write_byte(f, 0);
351                 modtime = 0, mode = 0;
352                 dev = 0, rdev = makedev(0, 0);
353                 rdev_major = 0;
354                 uid = 0, gid = 0;
355                 *lastname = '\0';
356                 return;
357         }
358
359         io_write_phase = "send_file_entry";
360
361         f_name_to(file, fname);
362
363         flags = base_flags;
364
365         if (file->mode == mode)
366                 flags |= XMIT_SAME_MODE;
367         else
368                 mode = file->mode;
369         if (preserve_devices) {
370                 if (protocol_version < 28) {
371                         if (IS_DEVICE(mode)) {
372                                 if (file->u.rdev == rdev)
373                                         flags |= XMIT_SAME_RDEV_pre28;
374                                 else
375                                         rdev = file->u.rdev;
376                         } else
377                                 rdev = makedev(0, 0);
378                 } else if (IS_DEVICE(mode)) {
379                         rdev = file->u.rdev;
380                         if ((uint32)major(rdev) == rdev_major)
381                                 flags |= XMIT_SAME_RDEV_MAJOR;
382                         else
383                                 rdev_major = major(rdev);
384                         if ((uint32)minor(rdev) <= 0xFFu)
385                                 flags |= XMIT_RDEV_MINOR_IS_SMALL;
386                 }
387         }
388         if (file->uid == uid)
389                 flags |= XMIT_SAME_UID;
390         else
391                 uid = file->uid;
392         if (file->gid == gid)
393                 flags |= XMIT_SAME_GID;
394         else
395                 gid = file->gid;
396         if (file->modtime == modtime)
397                 flags |= XMIT_SAME_TIME;
398         else
399                 modtime = file->modtime;
400
401 #if SUPPORT_HARD_LINKS
402         if (file->link_u.idev) {
403                 if (file->F_DEV == dev) {
404                         if (protocol_version >= 28)
405                                 flags |= XMIT_SAME_DEV;
406                 } else
407                         dev = file->F_DEV;
408                 flags |= XMIT_HAS_IDEV_DATA;
409         }
410 #endif
411
412         for (l1 = 0;
413             lastname[l1] && (fname[l1] == lastname[l1]) && (l1 < 255);
414             l1++) {}
415         l2 = strlen(fname+l1);
416
417         if (l1 > 0)
418                 flags |= XMIT_SAME_NAME;
419         if (l2 > 255)
420                 flags |= XMIT_LONG_NAME;
421
422         /* We must make sure we don't send a zero flag byte or the
423          * other end will terminate the flist transfer.  Note that
424          * the use of XMIT_DEL_START on a non-dir has no meaning, so
425          * it's harmless way to add a bit to the first flag byte. */
426         if (protocol_version >= 28) {
427                 if (!flags && !S_ISDIR(mode))
428                         flags |= XMIT_DEL_START;
429                 if ((flags & 0xFF00) || !flags) {
430                         flags |= XMIT_EXTENDED_FLAGS;
431                         write_byte(f, flags);
432                         write_byte(f, flags >> 8);
433                 } else
434                         write_byte(f, flags);
435         } else {
436                 if (!(flags & 0xFF) && !S_ISDIR(mode))
437                         flags |= XMIT_DEL_START;
438                 if (!(flags & 0xFF))
439                         flags |= XMIT_LONG_NAME;
440                 write_byte(f, flags);
441         }
442         if (flags & XMIT_SAME_NAME)
443                 write_byte(f, l1);
444         if (flags & XMIT_LONG_NAME)
445                 write_int(f, l2);
446         else
447                 write_byte(f, l2);
448         write_buf(f, fname + l1, l2);
449
450         write_longint(f, file->length);
451         if (!(flags & XMIT_SAME_TIME))
452                 write_int(f, modtime);
453         if (!(flags & XMIT_SAME_MODE))
454                 write_int(f, to_wire_mode(mode));
455         if (preserve_uid && !(flags & XMIT_SAME_UID)) {
456                 if (!numeric_ids)
457                         add_uid(uid);
458                 write_int(f, uid);
459         }
460         if (preserve_gid && !(flags & XMIT_SAME_GID)) {
461                 if (!numeric_ids)
462                         add_gid(gid);
463                 write_int(f, gid);
464         }
465         if (preserve_devices && IS_DEVICE(mode)) {
466                 if (protocol_version < 28) {
467                         if (!(flags & XMIT_SAME_RDEV_pre28))
468                                 write_int(f, (int)rdev);
469                 } else {
470                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
471                                 write_int(f, major(rdev));
472                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
473                                 write_byte(f, minor(rdev));
474                         else
475                                 write_int(f, minor(rdev));
476                 }
477         }
478
479 #if SUPPORT_LINKS
480         if (preserve_links && S_ISLNK(mode)) {
481                 int len = strlen(file->u.link);
482                 write_int(f, len);
483                 write_buf(f, file->u.link, len);
484         }
485 #endif
486
487 #if SUPPORT_HARD_LINKS
488         if (flags & XMIT_HAS_IDEV_DATA) {
489                 if (protocol_version < 26) {
490                         /* 32-bit dev_t and ino_t */
491                         write_int(f, dev);
492                         write_int(f, file->F_INODE);
493                 } else {
494                         /* 64-bit dev_t and ino_t */
495                         if (!(flags & XMIT_SAME_DEV))
496                                 write_longint(f, dev);
497                         write_longint(f, file->F_INODE);
498                 }
499         }
500 #endif
501
502         if (always_checksum) {
503                 char *sum;
504                 if (S_ISREG(mode))
505                         sum = file->u.sum;
506                 else if (protocol_version < 28) {
507                         /* Prior to 28, we sent a useless set of nulls. */
508                         sum = empty_sum;
509                 } else
510                         sum = NULL;
511                 if (sum) {
512                         write_buf(f, sum,
513                             protocol_version < 21 ? 2 : MD4_SUM_LENGTH);
514                 }
515         }
516
517         strlcpy(lastname, fname, MAXPATHLEN);
518
519         io_write_phase = "unknown";
520 }
521
522
523
524 void receive_file_entry(struct file_struct **fptr, unsigned short flags,
525                         struct file_list *flist, int f)
526 {
527         static time_t modtime;
528         static mode_t mode;
529         static int64 dev;
530         static dev_t rdev;
531         static uint32 rdev_major;
532         static uid_t uid;
533         static gid_t gid;
534         static char lastname[MAXPATHLEN], *lastdir;
535         static int lastdir_depth, lastdir_len = -1;
536         static unsigned int del_heir_name_len = -1;
537         static int in_del_hier = 0;
538         char thisname[MAXPATHLEN];
539         unsigned int l1 = 0, l2 = 0;
540         int alloc_len, basename_len, dirname_len, linkname_len, sum_len;
541         OFF_T file_length;
542         char *basename, *dirname, *bp;
543         struct file_struct *file;
544
545         if (!fptr) {
546                 modtime = 0, mode = 0;
547                 dev = 0, rdev = makedev(0, 0);
548                 rdev_major = 0;
549                 uid = 0, gid = 0;
550                 *lastname = '\0';
551                 del_heir_name_len = lastdir_len = -1;
552                 in_del_hier = 0;
553                 return;
554         }
555
556         if (flags & XMIT_SAME_NAME)
557                 l1 = read_byte(f);
558
559         if (flags & XMIT_LONG_NAME)
560                 l2 = read_int(f);
561         else
562                 l2 = read_byte(f);
563
564         if (l2 >= MAXPATHLEN - l1) {
565                 rprintf(FERROR,
566                         "overflow: flags=0x%x l1=%d l2=%d lastname=%s\n",
567                         flags, l1, l2, lastname);
568                 overflow("receive_file_entry");
569         }
570
571         strlcpy(thisname, lastname, l1 + 1);
572         read_sbuf(f, &thisname[l1], l2);
573         thisname[l1 + l2] = 0;
574
575         strlcpy(lastname, thisname, MAXPATHLEN);
576
577         clean_fname(thisname, 0);
578
579         if (sanitize_paths)
580                 sanitize_path(thisname, thisname, "", 0);
581
582         if ((basename = strrchr(thisname, '/')) != NULL) {
583                 dirname_len = ++basename - thisname; /* counts future '\0' */
584                 if (lastdir_len == dirname_len - 1
585                     && strncmp(thisname, lastdir, lastdir_len) == 0) {
586                         dirname = lastdir;
587                         dirname_len = 0; /* indicates no copy is needed */
588                 } else
589                         dirname = thisname;
590         } else {
591                 basename = thisname;
592                 dirname = NULL;
593                 dirname_len = 0;
594         }
595         basename_len = strlen(basename) + 1; /* count the '\0' */
596
597         file_length = read_longint(f);
598         if (!(flags & XMIT_SAME_TIME))
599                 modtime = (time_t)read_int(f);
600         if (!(flags & XMIT_SAME_MODE))
601                 mode = from_wire_mode(read_int(f));
602
603         if (preserve_uid && !(flags & XMIT_SAME_UID))
604                 uid = (uid_t)read_int(f);
605         if (preserve_gid && !(flags & XMIT_SAME_GID))
606                 gid = (gid_t)read_int(f);
607
608         if (preserve_devices) {
609                 if (protocol_version < 28) {
610                         if (IS_DEVICE(mode)) {
611                                 if (!(flags & XMIT_SAME_RDEV_pre28))
612                                         rdev = (dev_t)read_int(f);
613                         } else
614                                 rdev = makedev(0, 0);
615                 } else if (IS_DEVICE(mode)) {
616                         uint32 rdev_minor;
617                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
618                                 rdev_major = read_int(f);
619                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
620                                 rdev_minor = read_byte(f);
621                         else
622                                 rdev_minor = read_int(f);
623                         rdev = makedev(rdev_major, rdev_minor);
624                 }
625         }
626
627 #if SUPPORT_LINKS
628         if (preserve_links && S_ISLNK(mode)) {
629                 linkname_len = read_int(f) + 1; /* count the '\0' */
630                 if (linkname_len <= 0 || linkname_len > MAXPATHLEN) {
631                         rprintf(FERROR, "overflow: linkname_len=%d\n",
632                                 linkname_len - 1);
633                         overflow("receive_file_entry");
634                 }
635         }
636         else
637 #endif
638                 linkname_len = 0;
639
640         sum_len = always_checksum && S_ISREG(mode) ? MD4_SUM_LENGTH : 0;
641
642         alloc_len = file_struct_len + dirname_len + basename_len
643                   + linkname_len + sum_len;
644         bp = pool_alloc(flist->file_pool, alloc_len, "receive_file_entry");
645
646         file = *fptr = (struct file_struct *)bp;
647         memset(bp, 0, file_struct_len);
648         bp += file_struct_len;
649
650         file->flags = 0;
651         file->modtime = modtime;
652         file->length = file_length;
653         file->mode = mode;
654         file->uid = uid;
655         file->gid = gid;
656
657         if (S_ISDIR(mode)) {
658                 if (flags & XMIT_DEL_START) {
659                         in_del_hier = 1;
660                         del_heir_name_len = l1 + l2;
661                         file->flags |= FLAG_DEL_START;
662                 } else if (delete_during && in_del_hier) {
663                         if (!relative_paths || (l1 >= del_heir_name_len
664                             && thisname[del_heir_name_len] == '/'))
665                                 file->flags |= FLAG_DEL_START;
666                         else
667                                 in_del_hier = 0;
668                 }
669         }
670
671         if (dirname_len) {
672                 file->dirname = lastdir = bp;
673                 lastdir_len = dirname_len - 1;
674                 memcpy(bp, dirname, dirname_len - 1);
675                 bp += dirname_len;
676                 bp[-1] = '\0';
677                 if (sanitize_paths)
678                         lastdir_depth = count_dir_elements(lastdir);
679         } else if (dirname)
680                 file->dirname = dirname;
681
682         file->basename = bp;
683         memcpy(bp, basename, basename_len);
684         bp += basename_len;
685
686         if (preserve_devices && IS_DEVICE(mode))
687                 file->u.rdev = rdev;
688
689 #if SUPPORT_LINKS
690         if (linkname_len) {
691                 file->u.link = bp;
692                 read_sbuf(f, bp, linkname_len - 1);
693                 if (sanitize_paths)
694                         sanitize_path(bp, bp, "", lastdir_depth);
695                 bp += linkname_len;
696         }
697 #endif
698
699 #if SUPPORT_HARD_LINKS
700         if (preserve_hard_links && protocol_version < 28 && S_ISREG(mode))
701                 flags |= XMIT_HAS_IDEV_DATA;
702         if (flags & XMIT_HAS_IDEV_DATA) {
703                 int64 inode;
704                 if (protocol_version < 26) {
705                         dev = read_int(f);
706                         inode = read_int(f);
707                 } else {
708                         if (!(flags & XMIT_SAME_DEV))
709                                 dev = read_longint(f);
710                         inode = read_longint(f);
711                 }
712                 if (flist->hlink_pool) {
713                         file->link_u.idev = pool_talloc(flist->hlink_pool,
714                             struct idev, 1, "inode_table");
715                         file->F_INODE = inode;
716                         file->F_DEV = dev;
717                 }
718         }
719 #endif
720
721         if (always_checksum) {
722                 char *sum;
723                 if (sum_len) {
724                         file->u.sum = sum = bp;
725                         /*bp += sum_len;*/
726                 } else if (protocol_version < 28) {
727                         /* Prior to 28, we get a useless set of nulls. */
728                         sum = empty_sum;
729                 } else
730                         sum = NULL;
731                 if (sum) {
732                         read_buf(f, sum,
733                             protocol_version < 21 ? 2 : MD4_SUM_LENGTH);
734                 }
735         }
736
737         if (!preserve_perms) {
738                 /* set an appropriate set of permissions based on original
739                  * permissions and umask. This emulates what GNU cp does */
740                 file->mode &= ~orig_umask;
741         }
742 }
743
744
745 /**
746  * Create a file_struct for a named file by reading its stat()
747  * information and performing extensive checks against global
748  * options.
749  *
750  * @return the new file, or NULL if there was an error or this file
751  * should be excluded.
752  *
753  * @todo There is a small optimization opportunity here to avoid
754  * stat()ing the file in some circumstances, which has a certain cost.
755  * We are called immediately after doing readdir(), and so we may
756  * already know the d_type of the file.  We could for example avoid
757  * statting directories if we're not recursing, but this is not a very
758  * important case.  Some systems may not have d_type.
759  **/
760 struct file_struct *make_file(char *fname, struct file_list *flist,
761                               int exclude_level)
762 {
763         static char *lastdir;
764         static int lastdir_len = -1;
765         struct file_struct *file;
766         STRUCT_STAT st;
767         char sum[SUM_LENGTH];
768         char thisname[MAXPATHLEN];
769         char linkname[MAXPATHLEN];
770         int alloc_len, basename_len, dirname_len, linkname_len, sum_len;
771         char *basename, *dirname, *bp;
772         unsigned short flags = 0;
773
774         if (!flist || !flist->count)    /* Ignore lastdir when invalid. */
775                 lastdir_len = -1;
776
777         if (strlcpy(thisname, fname, sizeof thisname)
778             >= sizeof thisname - flist_dir_len) {
779                 rprintf(FINFO, "skipping overly long name: %s\n", fname);
780                 return NULL;
781         }
782         clean_fname(thisname, 0);
783         if (sanitize_paths)
784                 sanitize_path(thisname, thisname, "", 0);
785
786         memset(sum, 0, SUM_LENGTH);
787
788         if (readlink_stat(thisname, &st, linkname) != 0) {
789                 int save_errno = errno;
790                 /* See if file is excluded before reporting an error. */
791                 if (exclude_level != NO_EXCLUDES
792                     && check_exclude_file(thisname, 0, exclude_level))
793                         return NULL;
794                 if (save_errno == ENOENT) {
795 #if SUPPORT_LINKS
796                         /* Avoid "vanished" error if symlink points nowhere. */
797                         if (copy_links && do_lstat(thisname, &st) == 0
798                             && S_ISLNK(st.st_mode)) {
799                                 io_error |= IOERR_GENERAL;
800                                 rprintf(FERROR, "symlink has no referent: %s\n",
801                                         full_fname(thisname));
802                         } else
803 #endif
804                         {
805                                 enum logcode c = am_daemon && protocol_version < 28
806                                     ? FERROR : FINFO;
807                                 io_error |= IOERR_VANISHED;
808                                 rprintf(c, "file has vanished: %s\n",
809                                         full_fname(thisname));
810                         }
811                 } else {
812                         io_error |= IOERR_GENERAL;
813                         rsyserr(FERROR, save_errno, "readlink %s failed",
814                                 full_fname(thisname));
815                 }
816                 return NULL;
817         }
818
819         /* backup.c calls us with exclude_level set to NO_EXCLUDES. */
820         if (exclude_level == NO_EXCLUDES)
821                 goto skip_excludes;
822
823         if (S_ISDIR(st.st_mode) && !xfer_dirs) {
824                 rprintf(FINFO, "skipping directory %s\n", thisname);
825                 return NULL;
826         }
827
828         /* We only care about directories because we need to avoid recursing
829          * into a mount-point directory, not to avoid copying a symlinked
830          * file if -L (or similar) was specified. */
831         if (one_file_system && st.st_dev != filesystem_dev
832             && S_ISDIR(st.st_mode))
833                 flags |= FLAG_MOUNT_POINT;
834
835         if (check_exclude_file(thisname, S_ISDIR(st.st_mode) != 0, exclude_level))
836                 return NULL;
837
838         if (lp_ignore_nonreadable(module_id)) {
839 #if SUPPORT_LINKS
840                 if (!S_ISLNK(st.st_mode))
841 #endif
842                         if (access(thisname, R_OK) != 0)
843                                 return NULL;
844         }
845
846 skip_excludes:
847
848         if (verbose > 2) {
849                 rprintf(FINFO, "[%s] make_file(%s,*,%d)\n",
850                         who_am_i(), thisname, exclude_level);
851         }
852
853         if ((basename = strrchr(thisname, '/')) != NULL) {
854                 dirname_len = ++basename - thisname; /* counts future '\0' */
855                 if (lastdir_len == dirname_len - 1
856                     && strncmp(thisname, lastdir, lastdir_len) == 0) {
857                         dirname = lastdir;
858                         dirname_len = 0; /* indicates no copy is needed */
859                 } else
860                         dirname = thisname;
861         } else {
862                 basename = thisname;
863                 dirname = NULL;
864                 dirname_len = 0;
865         }
866         basename_len = strlen(basename) + 1; /* count the '\0' */
867
868 #if SUPPORT_LINKS
869         linkname_len = S_ISLNK(st.st_mode) ? strlen(linkname) + 1 : 0;
870 #else
871         linkname_len = 0;
872 #endif
873
874         sum_len = always_checksum && S_ISREG(st.st_mode) ? MD4_SUM_LENGTH : 0;
875
876         alloc_len = file_struct_len + dirname_len + basename_len
877             + linkname_len + sum_len;
878         if (flist) {
879                 bp = pool_alloc(flist->file_pool, alloc_len,
880                     "receive_file_entry");
881         } else {
882                 if (!(bp = new_array(char, alloc_len)))
883                         out_of_memory("receive_file_entry");
884         }
885
886         file = (struct file_struct *)bp;
887         memset(bp, 0, file_struct_len);
888         bp += file_struct_len;
889
890         file->flags = flags;
891         file->modtime = st.st_mtime;
892         file->length = st.st_size;
893         file->mode = st.st_mode;
894         file->uid = st.st_uid;
895         file->gid = st.st_gid;
896
897 #if SUPPORT_HARD_LINKS
898         if (flist && flist->hlink_pool) {
899                 if (protocol_version < 28) {
900                         if (S_ISREG(st.st_mode))
901                                 file->link_u.idev = pool_talloc(
902                                     flist->hlink_pool, struct idev, 1,
903                                     "inode_table");
904                 } else {
905                         if (!S_ISDIR(st.st_mode) && st.st_nlink > 1)
906                                 file->link_u.idev = pool_talloc(
907                                     flist->hlink_pool, struct idev, 1,
908                                     "inode_table");
909                 }
910         }
911         if (file->link_u.idev) {
912                 file->F_DEV = st.st_dev;
913                 file->F_INODE = st.st_ino;
914         }
915 #endif
916
917         if (dirname_len) {
918                 file->dirname = lastdir = bp;
919                 lastdir_len = dirname_len - 1;
920                 memcpy(bp, dirname, dirname_len - 1);
921                 bp += dirname_len;
922                 bp[-1] = '\0';
923         } else if (dirname)
924                 file->dirname = dirname;
925
926         file->basename = bp;
927         memcpy(bp, basename, basename_len);
928         bp += basename_len;
929
930 #ifdef HAVE_STRUCT_STAT_ST_RDEV
931         if (preserve_devices && IS_DEVICE(st.st_mode))
932                 file->u.rdev = st.st_rdev;
933 #endif
934
935 #if SUPPORT_LINKS
936         if (linkname_len) {
937                 file->u.link = bp;
938                 memcpy(bp, linkname, linkname_len);
939                 bp += linkname_len;
940         }
941 #endif
942
943         if (sum_len) {
944                 file->u.sum = bp;
945                 file_checksum(thisname, bp, st.st_size);
946                 /*bp += sum_len;*/
947         }
948
949         file->basedir = flist_dir;
950
951         /* This code is only used by the receiver when it is building
952          * a list of files for a delete pass. */
953         if (keep_dirlinks && linkname_len && flist) {
954                 STRUCT_STAT st2;
955                 int i = flist_find(received_flist, file);
956                 if (i >= 0 && S_ISDIR(received_flist->files[i]->mode)
957                     && do_stat(thisname, &st2) == 0 && S_ISDIR(st2.st_mode)) {
958                         file->modtime = st2.st_mtime;
959                         file->length = st2.st_size;
960                         file->mode = st2.st_mode;
961                         file->uid = st2.st_uid;
962                         file->gid = st2.st_gid;
963                         file->u.link = NULL;
964                         if (file->link_u.idev) {
965                                 pool_free(flist->hlink_pool, 0, file->link_u.idev);
966                                 file->link_u.idev = NULL;
967                         }
968                 }
969         }
970
971         if (!S_ISDIR(st.st_mode))
972                 stats.total_size += st.st_size;
973
974         return file;
975 }
976
977
978 void send_file_name(int f, struct file_list *flist, char *fname,
979                     int recursive, unsigned short base_flags)
980 {
981         struct file_struct *file;
982         char fbuf[MAXPATHLEN];
983
984         /* f is set to -1 when calculating deletion file list */
985         file = make_file(fname, flist,
986             f == -1 && delete_excluded? SERVER_EXCLUDES : ALL_EXCLUDES);
987
988         if (!file)
989                 return;
990
991         maybe_emit_filelist_progress(flist);
992
993         flist_expand(flist);
994
995         if (file->basename[0]) {
996                 flist->files[flist->count++] = file;
997                 send_file_entry(file, f, base_flags);
998         }
999
1000         if (recursive && S_ISDIR(file->mode)
1001             && !(file->flags & FLAG_MOUNT_POINT)) {
1002                 send_directory(f, flist, f_name_to(file, fbuf));
1003         }
1004 }
1005
1006
1007 /* Note that the "recurse" value either contains -1, for infinite recursion,
1008  * or a number >= 0 indicating how many levels of recursion we will allow. */
1009 static void send_directory(int f, struct file_list *flist, char *dir)
1010 {
1011         DIR *d;
1012         struct dirent *di;
1013         char fname[MAXPATHLEN];
1014         unsigned int offset;
1015         void *save_excludes;
1016         char *p;
1017
1018         d = opendir(dir);
1019         if (!d) {
1020                 io_error |= IOERR_GENERAL;
1021                 rsyserr(FERROR, errno, "opendir %s failed", full_fname(dir));
1022                 return;
1023         }
1024
1025         offset = strlcpy(fname, dir, MAXPATHLEN);
1026         p = fname + offset;
1027         if (offset >= MAXPATHLEN || p[-1] != '/') {
1028                 if (offset >= MAXPATHLEN - 1) {
1029                         io_error |= IOERR_GENERAL;
1030                         rprintf(FERROR, "skipping long-named directory: %s\n",
1031                                 full_fname(fname));
1032                         closedir(d);
1033                         return;
1034                 }
1035                 *p++ = '/';
1036                 offset++;
1037         }
1038
1039         save_excludes = push_local_excludes(fname, offset);
1040
1041         for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
1042                 char *dname = d_name(di);
1043                 if (dname[0] == '.' && (dname[1] == '\0'
1044                     || (dname[1] == '.' && dname[2] == '\0')))
1045                         continue;
1046                 if (strlcpy(p, dname, MAXPATHLEN - offset) < MAXPATHLEN - offset) {
1047                         int do_subdirs = recurse >= 1 ? recurse-- : recurse;
1048                         send_file_name(f, flist, fname, do_subdirs, 0);
1049                 } else {
1050                         io_error |= IOERR_GENERAL;
1051                         rprintf(FINFO,
1052                                 "cannot send long-named file %s\n",
1053                                 full_fname(fname));
1054                 }
1055         }
1056         if (errno) {
1057                 io_error |= IOERR_GENERAL;
1058                 rsyserr(FERROR, errno, "readdir(%s)", dir);
1059         }
1060
1061         pop_local_excludes(save_excludes);
1062
1063         closedir(d);
1064 }
1065
1066
1067 /* This function is normally called by the sender, but the receiving side
1068  * also uses it to construct one or more file lists if one of the --delete
1069  * options have been specified.  The delete_in_dir() function sets f to -1
1070  * so that we just construct the file list in memory without sending it
1071  * over the wire.  It also has the side-effect of ignoring user-excludes if
1072  * delete_excluded is set (so that the delete list includes user-excluded
1073  * files) and it avoids some per-arg init code for limited recursion (since
1074  * delete_in_dir() sets recurse before calling this function). */
1075 struct file_list *send_file_list(int f, int argc, char *argv[])
1076 {
1077         int l;
1078         STRUCT_STAT st;
1079         char *p, *dir, olddir[sizeof curr_dir];
1080         char lastpath[MAXPATHLEN] = "";
1081         struct file_list *flist;
1082         BOOL need_first_push = True;
1083         int64 start_write;
1084         int use_ff_fd = 0;
1085
1086         if (show_filelist_p() && f != -1)
1087                 start_filelist_progress("building file list");
1088
1089         start_write = stats.total_written;
1090
1091         flist = flist_new(f == -1 ? WITHOUT_HLINK : WITH_HLINK,
1092                           "send_file_list");
1093
1094         if (f != -1) {
1095                 io_start_buffering_out();
1096                 if (filesfrom_fd >= 0) {
1097                         if (argv[0] && !push_dir(argv[0])) {
1098                                 rsyserr(FERROR, errno, "push_dir %s failed",
1099                                         full_fname(argv[0]));
1100                                 exit_cleanup(RERR_FILESELECT);
1101                         }
1102                         use_ff_fd = 1;
1103                         if (curr_dir_len < MAXPATHLEN - 1) {
1104                                 push_local_excludes(curr_dir, curr_dir_len);
1105                                 need_first_push = False;
1106                         }
1107                 }
1108         }
1109
1110         while (1) {
1111                 char fname2[MAXPATHLEN];
1112                 char *fname = fname2;
1113                 int do_subdirs;
1114
1115                 if (use_ff_fd) {
1116                         if (read_filesfrom_line(filesfrom_fd, fname) == 0)
1117                                 break;
1118                         sanitize_path(fname, fname, "", 0);
1119                 } else {
1120                         if (argc-- == 0)
1121                                 break;
1122                         strlcpy(fname, *argv++, MAXPATHLEN);
1123                         if (sanitize_paths)
1124                                 sanitize_path(fname, fname, "", 0);
1125                 }
1126
1127                 l = strlen(fname);
1128                 if (!l || fname[l - 1] == '/') {
1129                         if (l == 2 && fname[0] == '.') {
1130                                 /* Turn "./" into just "." rather than "./." */
1131                                 fname[1] = '\0';
1132                         } else if (l < MAXPATHLEN) {
1133                                 fname[l++] = '.';
1134                                 fname[l] = '\0';
1135                         }
1136                 }
1137                 if (f == -1)
1138                         ; /* recurse is pre-set */
1139                 else if (fname[l-1] == '.' && (l == 1 || fname[l-2] == '/')) {
1140                         if (!recurse && xfer_dirs)
1141                                 recurse = 1; /* allow one level */
1142                 } else if (recurse > 0)
1143                         recurse = 0;
1144
1145                 if (need_first_push) {
1146                         if ((p = strrchr(fname, '/')) != NULL) {
1147                                 if (*++p && strcmp(p, ".") != 0)
1148                                         push_local_excludes(fname, p - fname);
1149                         } else if (strcmp(fname, ".") != 0)
1150                                 push_local_excludes(fname, 0);
1151                         need_first_push = False;
1152                 }
1153
1154                 if (link_stat(fname, &st, keep_dirlinks) != 0) {
1155                         if (f != -1) {
1156                                 io_error |= IOERR_GENERAL;
1157                                 rsyserr(FERROR, errno, "link_stat %s failed",
1158                                         full_fname(fname));
1159                         }
1160                         continue;
1161                 }
1162
1163                 if (S_ISDIR(st.st_mode) && !xfer_dirs) {
1164                         rprintf(FINFO, "skipping directory %s\n", fname);
1165                         continue;
1166                 }
1167
1168                 dir = NULL;
1169                 olddir[0] = '\0';
1170
1171                 if (!relative_paths) {
1172                         p = strrchr(fname, '/');
1173                         if (p) {
1174                                 *p = 0;
1175                                 if (p == fname)
1176                                         dir = "/";
1177                                 else
1178                                         dir = fname;
1179                                 fname = p + 1;
1180                         }
1181                 } else if (f != -1 && implied_dirs && (p=strrchr(fname,'/')) && p != fname) {
1182                         /* this ensures we send the intermediate directories,
1183                            thus getting their permissions right */
1184                         char *lp = lastpath, *fn = fname, *slash = fname;
1185                         *p = 0;
1186                         /* Skip any initial directories in our path that we
1187                          * have in common with lastpath. */
1188                         while (*fn && *lp == *fn) {
1189                                 if (*fn == '/')
1190                                         slash = fn;
1191                                 lp++, fn++;
1192                         }
1193                         *p = '/';
1194                         if (fn != p || (*lp && *lp != '/')) {
1195                                 int save_copy_links = copy_links;
1196                                 int save_xfer_dirs = xfer_dirs;
1197                                 copy_links = copy_unsafe_links;
1198                                 xfer_dirs = 1;
1199                                 while ((slash = strchr(slash+1, '/')) != 0) {
1200                                         *slash = 0;
1201                                         send_file_name(f, flist, fname, 0, 0);
1202                                         *slash = '/';
1203                                 }
1204                                 copy_links = save_copy_links;
1205                                 xfer_dirs = save_xfer_dirs;
1206                                 *p = 0;
1207                                 strlcpy(lastpath, fname, sizeof lastpath);
1208                                 *p = '/';
1209                         }
1210                 }
1211
1212                 if (!*fname)
1213                         fname = ".";
1214
1215                 if (dir && *dir) {
1216                         static char *lastdir;
1217                         static int lastdir_len;
1218
1219                         strcpy(olddir, curr_dir); /* can't overflow */
1220
1221                         if (!push_dir(dir)) {
1222                                 io_error |= IOERR_GENERAL;
1223                                 rsyserr(FERROR, errno, "push_dir %s failed",
1224                                         full_fname(dir));
1225                                 continue;
1226                         }
1227
1228                         if (lastdir && strcmp(lastdir, dir) == 0) {
1229                                 flist_dir = lastdir;
1230                                 flist_dir_len = lastdir_len;
1231                         } else {
1232                                 flist_dir = lastdir = strdup(dir);
1233                                 flist_dir_len = lastdir_len = strlen(dir);
1234                         }
1235                 }
1236
1237                 if (one_file_system)
1238                         set_filesystem(fname);
1239
1240                 do_subdirs = recurse >= 1 ? recurse-- : recurse;
1241                 send_file_name(f, flist, fname, do_subdirs, XMIT_DEL_START);
1242
1243                 if (olddir[0]) {
1244                         flist_dir = NULL;
1245                         flist_dir_len = 0;
1246                         if (!pop_dir(olddir)) {
1247                                 rsyserr(FERROR, errno, "pop_dir %s failed",
1248                                         full_fname(dir));
1249                                 exit_cleanup(RERR_FILESELECT);
1250                         }
1251                 }
1252         }
1253
1254         if (f != -1) {
1255                 send_file_entry(NULL, f, 0);
1256
1257                 if (show_filelist_p())
1258                         finish_filelist_progress(flist);
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  */
1654 char *f_name(struct file_struct *f)
1655 {
1656         static char names[5][MAXPATHLEN];
1657         static unsigned int n;
1658
1659         n = (n + 1) % (sizeof names / sizeof names[0]);
1660
1661         return f_name_to(f, names[n]);
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 void delete_in_dir(struct file_list *flist, char *fname)
1671 {
1672         static int deletion_count = 0;
1673         struct file_list *del_flist;
1674         int save_recurse = recurse;
1675         int save_xfer_dirs = xfer_dirs;
1676         int save_implied_dirs = implied_dirs;
1677         int save_relative_paths = relative_paths;
1678         char *argv[1];
1679         int i, j, mode;
1680
1681         if (max_delete && deletion_count >= max_delete)
1682                 return;
1683
1684         if (io_error && !(lp_ignore_errors(module_id) || ignore_errors)) {
1685                 rprintf(FINFO, "IO error encountered - skipping file deletion\n");
1686                 max_delete = -1; /* avoid duplicating the above warning */
1687                 return;
1688         }
1689
1690         if (delete_during) {
1691                 recurse = 1; /* allow one level only */
1692                 xfer_dirs = 1;
1693                 implied_dirs = 0;
1694                 relative_paths = 1;
1695         }
1696
1697         argv[0] = fname;
1698         del_flist = send_file_list(-1, 1, argv);
1699
1700         relative_paths = save_relative_paths;
1701         implied_dirs = save_implied_dirs;
1702         xfer_dirs = save_xfer_dirs;
1703         recurse = save_recurse;
1704
1705         if (!del_flist)
1706                 return;
1707
1708         if (verbose > 1)
1709                 rprintf(FINFO, "deleting in %s\n", safe_fname(fname));
1710
1711         for (i = del_flist->count-1; i >= 0; i--) {
1712                 if (max_delete && deletion_count >= max_delete)
1713                         break;
1714                 if (!del_flist->files[i]->basename)
1715                         continue;
1716                 mode = del_flist->files[i]->mode;
1717                 if ((j = flist_find(flist, del_flist->files[i])) < 0
1718                     || (delete_during && S_ISDIR(mode)
1719                      && !S_ISDIR(flist->files[j]->mode))) {
1720                         char *f = f_name(del_flist->files[i]);
1721                         if (make_backups && (backup_dir || !is_backup_file(f))
1722                           && !S_ISDIR(mode)) {
1723                                 make_backup(f);
1724                                 if (verbose) {
1725                                         rprintf(FINFO, "deleting %s\n",
1726                                                 safe_fname(f));
1727                                 }
1728                         } else {
1729                                 delete_file(f, S_ISDIR(mode)
1730                                                 ? DEL_DIR | DEL_RECURSE : 0);
1731                         }
1732                         deletion_count++;
1733                 }
1734         }
1735         flist_free(del_flist);
1736 }