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