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