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