Renamed sum_table -> hash_table.
[rsync/rsync.git] / exclude.c
1 /* -*- c-file-style: "linux" -*-
2  *
3  * Copyright (C) 1996-2001 by Andrew Tridgell <tridge@samba.org>
4  * Copyright (C) 1996 by Paul Mackerras
5  * Copyright (C) 2002 by Martin Pool
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21
22 /* a lot of this stuff was originally derived from GNU tar, although
23    it has now changed so much that it is hard to tell :) */
24
25 /* include/exclude cluestick added by Martin Pool <mbp@samba.org> */
26
27 #include "rsync.h"
28
29 extern int verbose;
30 extern int am_server;
31 extern int am_sender;
32 extern int eol_nulls;
33 extern int list_only;
34 extern int recurse;
35 extern int io_error;
36 extern int local_server;
37 extern int saw_delete_opt;
38 extern int saw_delete_excluded_opt;
39 extern int prune_empty_dirs;
40 extern int delete_mode;
41 extern int delete_excluded;
42 extern int cvs_exclude;
43 extern int sanitize_paths;
44 extern int protocol_version;
45 extern int module_id;
46
47 extern char curr_dir[];
48 extern unsigned int curr_dir_len;
49 extern unsigned int module_dirlen;
50
51 struct filter_list_struct filter_list = { 0, 0, "" };
52 struct filter_list_struct cvs_filter_list = { 0, 0, " [global CVS]" };
53 struct filter_list_struct server_filter_list = { 0, 0, " [daemon]" };
54
55 /* Need room enough for ":MODS " prefix plus some room to grow. */
56 #define MAX_RULE_PREFIX (16)
57
58 #define MODIFIERS_MERGE_FILE "-+Cenw"
59 #define MODIFIERS_INCL_EXCL "/!Crs"
60 #define MODIFIERS_HIDE_PROTECT "/!"
61
62 /* The dirbuf is set by push_local_filters() to the current subdirectory
63  * relative to curr_dir that is being processed.  The path always has a
64  * trailing slash appended, and the variable dirbuf_len contains the length
65  * of this path prefix.  The path is always absolute. */
66 static char dirbuf[MAXPATHLEN+1];
67 static unsigned int dirbuf_len = 0;
68 static int dirbuf_depth;
69
70 /* This is True when we're scanning parent dirs for per-dir merge-files. */
71 static BOOL parent_dirscan = False;
72
73 /* This array contains a list of all the currently active per-dir merge
74  * files.  This makes it easier to save the appropriate values when we
75  * "push" down into each subdirectory. */
76 static struct filter_struct **mergelist_parents;
77 static int mergelist_cnt = 0;
78 static int mergelist_size = 0;
79
80 /* Each filter_list_struct describes a singly-linked list by keeping track
81  * of both the head and tail pointers.  The list is slightly unusual in that
82  * a parent-dir's content can be appended to the end of the local list in a
83  * special way:  the last item in the local list has its "next" pointer set
84  * to point to the inherited list, but the local list's tail pointer points
85  * at the end of the local list.  Thus, if the local list is empty, the head
86  * will be pointing at the inherited content but the tail will be NULL.  To
87  * help you visualize this, here are the possible list arrangements:
88  *
89  * Completely Empty                     Local Content Only
90  * ==================================   ====================================
91  * head -> NULL                         head -> Local1 -> Local2 -> NULL
92  * tail -> NULL                         tail -------------^
93  *
94  * Inherited Content Only               Both Local and Inherited Content
95  * ==================================   ====================================
96  * head -> Parent1 -> Parent2 -> NULL   head -> L1 -> L2 -> P1 -> P2 -> NULL
97  * tail -> NULL                         tail ---------^
98  *
99  * This means that anyone wanting to traverse the whole list to use it just
100  * needs to start at the head and use the "next" pointers until it goes
101  * NULL.  To add new local content, we insert the item after the tail item
102  * and update the tail (obviously, if "tail" was NULL, we insert it at the
103  * head).  To clear the local list, WE MUST NOT FREE THE INHERITED CONTENT
104  * because it is shared between the current list and our parent list(s).
105  * The easiest way to handle this is to simply truncate the list after the
106  * tail item and then free the local list from the head.  When inheriting
107  * the list for a new local dir, we just save off the filter_list_struct
108  * values (so we can pop back to them later) and set the tail to NULL.
109  */
110
111 static void free_filter(struct filter_struct *ex)
112 {
113         if (ex->match_flags & MATCHFLG_PERDIR_MERGE) {
114                 free(ex->u.mergelist->debug_type);
115                 free(ex->u.mergelist);
116                 mergelist_cnt--;
117         }
118         free(ex->pattern);
119         free(ex);
120 }
121
122 /* Build a filter structure given a filter pattern.  The value in "pat"
123  * is not null-terminated. */
124 static void add_rule(struct filter_list_struct *listp, const char *pat,
125                      unsigned int pat_len, uint32 mflags, int xflags)
126 {
127         struct filter_struct *ret;
128         const char *cp;
129         unsigned int ex_len;
130
131         if (verbose > 2) {
132                 rprintf(FINFO, "[%s] add_rule(%s%.*s%s)%s\n",
133                         who_am_i(), get_rule_prefix(mflags, pat, 0, NULL),
134                         (int)pat_len, pat,
135                         (mflags & MATCHFLG_DIRECTORY) ? "/" : "",
136                         listp->debug_type);
137         }
138
139         /* These flags also indicate that we're reading a list that
140          * needs to be filtered now, not post-filtered later. */
141         if (xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH)) {
142                 uint32 mf = mflags & (MATCHFLG_RECEIVER_SIDE|MATCHFLG_SENDER_SIDE);
143                 if (am_sender) {
144                         if (mf == MATCHFLG_RECEIVER_SIDE)
145                                 return;
146                 } else {
147                         if (mf == MATCHFLG_SENDER_SIDE)
148                                 return;
149                 }
150         }
151
152         if (!(ret = new(struct filter_struct)))
153                 out_of_memory("add_rule");
154         memset(ret, 0, sizeof ret[0]);
155
156         if (!(mflags & (MATCHFLG_ABS_PATH | MATCHFLG_MERGE_FILE))
157          && ((xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH) && *pat == '/')
158           || (xflags & XFLG_ABS_IF_SLASH && strchr(pat, '/') != NULL))) {
159                 mflags |= MATCHFLG_ABS_PATH;
160                 if (*pat == '/')
161                         ex_len = dirbuf_len - module_dirlen - 1;
162                 else
163                         ex_len = 0;
164         } else
165                 ex_len = 0;
166         if (!(ret->pattern = new_array(char, ex_len + pat_len + 1)))
167                 out_of_memory("add_rule");
168         if (ex_len)
169                 memcpy(ret->pattern, dirbuf + module_dirlen, ex_len);
170         strlcpy(ret->pattern + ex_len, pat, pat_len + 1);
171         pat_len += ex_len;
172
173         if (strpbrk(ret->pattern, "*[?")) {
174                 mflags |= MATCHFLG_WILD;
175                 if ((cp = strstr(ret->pattern, "**")) != NULL) {
176                         mflags |= MATCHFLG_WILD2;
177                         /* If the pattern starts with **, note that. */
178                         if (cp == ret->pattern)
179                                 mflags |= MATCHFLG_WILD2_PREFIX;
180                         /* If the pattern ends with ***, note that. */
181                         if (pat_len >= 3
182                          && ret->pattern[pat_len-3] == '*'
183                          && ret->pattern[pat_len-2] == '*'
184                          && ret->pattern[pat_len-1] == '*')
185                                 mflags |= MATCHFLG_WILD3_SUFFIX;
186                 }
187         }
188
189         if (pat_len > 1 && ret->pattern[pat_len-1] == '/') {
190                 ret->pattern[pat_len-1] = 0;
191                 mflags |= MATCHFLG_DIRECTORY;
192         }
193
194         if (mflags & MATCHFLG_PERDIR_MERGE) {
195                 struct filter_list_struct *lp;
196                 unsigned int len;
197                 int i;
198
199                 if ((cp = strrchr(ret->pattern, '/')) != NULL)
200                         cp++;
201                 else
202                         cp = ret->pattern;
203
204                 /* If the local merge file was already mentioned, don't
205                  * add it again. */
206                 for (i = 0; i < mergelist_cnt; i++) {
207                         struct filter_struct *ex = mergelist_parents[i];
208                         const char *s = strrchr(ex->pattern, '/');
209                         if (s)
210                                 s++;
211                         else
212                                 s = ex->pattern;
213                         len = strlen(s);
214                         if (len == pat_len - (cp - ret->pattern)
215                             && memcmp(s, cp, len) == 0) {
216                                 free_filter(ret);
217                                 return;
218                         }
219                 }
220
221                 if (!(lp = new_array(struct filter_list_struct, 1)))
222                         out_of_memory("add_rule");
223                 lp->head = lp->tail = NULL;
224                 if (asprintf(&lp->debug_type, " [per-dir %s]", cp) < 0)
225                         out_of_memory("add_rule");
226                 ret->u.mergelist = lp;
227
228                 if (mergelist_cnt == mergelist_size) {
229                         mergelist_size += 5;
230                         mergelist_parents = realloc_array(mergelist_parents,
231                                                 struct filter_struct *,
232                                                 mergelist_size);
233                         if (!mergelist_parents)
234                                 out_of_memory("add_rule");
235                 }
236                 mergelist_parents[mergelist_cnt++] = ret;
237         } else {
238                 for (cp = ret->pattern; (cp = strchr(cp, '/')) != NULL; cp++)
239                         ret->u.slash_cnt++;
240         }
241
242         ret->match_flags = mflags;
243
244         if (!listp->tail) {
245                 ret->next = listp->head;
246                 listp->head = listp->tail = ret;
247         } else {
248                 ret->next = listp->tail->next;
249                 listp->tail->next = ret;
250                 listp->tail = ret;
251         }
252 }
253
254 static void clear_filter_list(struct filter_list_struct *listp)
255 {
256         if (listp->tail) {
257                 struct filter_struct *ent, *next;
258                 /* Truncate any inherited items from the local list. */
259                 listp->tail->next = NULL;
260                 /* Now free everything that is left. */
261                 for (ent = listp->head; ent; ent = next) {
262                         next = ent->next;
263                         free_filter(ent);
264                 }
265         }
266
267         listp->head = listp->tail = NULL;
268 }
269
270 /* This returns an expanded (absolute) filename for the merge-file name if
271  * the name has any slashes in it OR if the parent_dirscan var is True;
272  * otherwise it returns the original merge_file name.  If the len_ptr value
273  * is non-NULL the merge_file name is limited by the referenced length
274  * value and will be updated with the length of the resulting name.  We
275  * always return a name that is null terminated, even if the merge_file
276  * name was not. */
277 static char *parse_merge_name(const char *merge_file, unsigned int *len_ptr,
278                               unsigned int prefix_skip)
279 {
280         static char buf[MAXPATHLEN];
281         char *fn, tmpbuf[MAXPATHLEN];
282         unsigned int fn_len;
283
284         if (!parent_dirscan && *merge_file != '/') {
285                 /* Return the name unchanged it doesn't have any slashes. */
286                 if (len_ptr) {
287                         const char *p = merge_file + *len_ptr;
288                         while (--p > merge_file && *p != '/') {}
289                         if (p == merge_file) {
290                                 strlcpy(buf, merge_file, *len_ptr + 1);
291                                 return buf;
292                         }
293                 } else if (strchr(merge_file, '/') == NULL)
294                         return (char *)merge_file;
295         }
296
297         fn = *merge_file == '/' ? buf : tmpbuf;
298         if (sanitize_paths) {
299                 const char *r = prefix_skip ? "/" : NULL;
300                 /* null-terminate the name if it isn't already */
301                 if (len_ptr && merge_file[*len_ptr]) {
302                         char *to = fn == buf ? tmpbuf : buf;
303                         strlcpy(to, merge_file, *len_ptr + 1);
304                         merge_file = to;
305                 }
306                 if (!sanitize_path(fn, merge_file, r, dirbuf_depth)) {
307                         rprintf(FERROR, "merge-file name overflows: %s\n",
308                                 merge_file);
309                         return NULL;
310                 }
311         } else {
312                 strlcpy(fn, merge_file, len_ptr ? *len_ptr + 1 : MAXPATHLEN);
313                 clean_fname(fn, 1);
314         }
315         
316         fn_len = strlen(fn);
317         if (fn == buf)
318                 goto done;
319
320         if (dirbuf_len + fn_len >= MAXPATHLEN) {
321                 rprintf(FERROR, "merge-file name overflows: %s\n", fn);
322                 return NULL;
323         }
324         memcpy(buf, dirbuf + prefix_skip, dirbuf_len - prefix_skip);
325         memcpy(buf + dirbuf_len - prefix_skip, fn, fn_len + 1);
326         fn_len = clean_fname(buf, 1);
327
328     done:
329         if (len_ptr)
330                 *len_ptr = fn_len;
331         return buf;
332 }
333
334 /* Sets the dirbuf and dirbuf_len values. */
335 void set_filter_dir(const char *dir, unsigned int dirlen)
336 {
337         unsigned int len;
338         if (*dir != '/') {
339                 memcpy(dirbuf, curr_dir, curr_dir_len);
340                 dirbuf[curr_dir_len] = '/';
341                 len = curr_dir_len + 1;
342                 if (len + dirlen >= MAXPATHLEN)
343                         dirlen = 0;
344         } else
345                 len = 0;
346         memcpy(dirbuf + len, dir, dirlen);
347         dirbuf[dirlen + len] = '\0';
348         dirbuf_len = clean_fname(dirbuf, 1);
349         if (dirbuf_len > 1 && dirbuf[dirbuf_len-1] == '.'
350             && dirbuf[dirbuf_len-2] == '/')
351                 dirbuf_len -= 2;
352         if (dirbuf_len != 1)
353                 dirbuf[dirbuf_len++] = '/';
354         dirbuf[dirbuf_len] = '\0';
355         if (sanitize_paths)
356                 dirbuf_depth = count_dir_elements(dirbuf + module_dirlen);
357 }
358
359 /* This routine takes a per-dir merge-file entry and finishes its setup.
360  * If the name has a path portion then we check to see if it refers to a
361  * parent directory of the first transfer dir.  If it does, we scan all the
362  * dirs from that point through the parent dir of the transfer dir looking
363  * for the per-dir merge-file in each one. */
364 static BOOL setup_merge_file(struct filter_struct *ex,
365                              struct filter_list_struct *lp)
366 {
367         char buf[MAXPATHLEN];
368         char *x, *y, *pat = ex->pattern;
369         unsigned int len;
370
371         if (!(x = parse_merge_name(pat, NULL, 0)) || *x != '/')
372                 return 0;
373
374         y = strrchr(x, '/');
375         *y = '\0';
376         ex->pattern = strdup(y+1);
377         if (!*x)
378                 x = "/";
379         if (*x == '/')
380                 strlcpy(buf, x, MAXPATHLEN);
381         else
382                 pathjoin(buf, MAXPATHLEN, dirbuf, x);
383
384         len = clean_fname(buf, 1);
385         if (len != 1 && len < MAXPATHLEN-1) {
386                 buf[len++] = '/';
387                 buf[len] = '\0';
388         }
389         /* This ensures that the specified dir is a parent of the transfer. */
390         for (x = buf, y = dirbuf; *x && *x == *y; x++, y++) {}
391         if (*x)
392                 y += strlen(y); /* nope -- skip the scan */
393
394         parent_dirscan = True;
395         while (*y) {
396                 char save[MAXPATHLEN];
397                 strlcpy(save, y, MAXPATHLEN);
398                 *y = '\0';
399                 dirbuf_len = y - dirbuf;
400                 strlcpy(x, ex->pattern, MAXPATHLEN - (x - buf));
401                 parse_filter_file(lp, buf, ex->match_flags, XFLG_ANCHORED2ABS);
402                 if (ex->match_flags & MATCHFLG_NO_INHERIT)
403                         lp->head = NULL;
404                 lp->tail = NULL;
405                 strlcpy(y, save, MAXPATHLEN);
406                 while ((*x++ = *y++) != '/') {}
407         }
408         parent_dirscan = False;
409         free(pat);
410         return 1;
411 }
412
413 /* Each time rsync changes to a new directory it call this function to
414  * handle all the per-dir merge-files.  The "dir" value is the current path
415  * relative to curr_dir (which might not be null-terminated).  We copy it
416  * into dirbuf so that we can easily append a file name on the end. */
417 void *push_local_filters(const char *dir, unsigned int dirlen)
418 {
419         struct filter_list_struct *ap, *push;
420         int i;
421
422         set_filter_dir(dir, dirlen);
423
424         if (!mergelist_cnt)
425                 return NULL;
426
427         push = new_array(struct filter_list_struct, mergelist_cnt);
428         if (!push)
429                 out_of_memory("push_local_filters");
430
431         for (i = 0, ap = push; i < mergelist_cnt; i++) {
432                 memcpy(ap++, mergelist_parents[i]->u.mergelist,
433                        sizeof (struct filter_list_struct));
434         }
435
436         /* Note: parse_filter_file() might increase mergelist_cnt, so keep
437          * this loop separate from the above loop. */
438         for (i = 0; i < mergelist_cnt; i++) {
439                 struct filter_struct *ex = mergelist_parents[i];
440                 struct filter_list_struct *lp = ex->u.mergelist;
441
442                 if (verbose > 2) {
443                         rprintf(FINFO, "[%s] pushing filter list%s\n",
444                                 who_am_i(), lp->debug_type);
445                 }
446
447                 lp->tail = NULL; /* Switch any local rules to inherited. */
448                 if (ex->match_flags & MATCHFLG_NO_INHERIT)
449                         lp->head = NULL;
450
451                 if (ex->match_flags & MATCHFLG_FINISH_SETUP) {
452                         ex->match_flags &= ~MATCHFLG_FINISH_SETUP;
453                         if (setup_merge_file(ex, lp))
454                                 set_filter_dir(dir, dirlen);
455                 }
456
457                 if (strlcpy(dirbuf + dirbuf_len, ex->pattern,
458                     MAXPATHLEN - dirbuf_len) < MAXPATHLEN - dirbuf_len) {
459                         parse_filter_file(lp, dirbuf, ex->match_flags,
460                                           XFLG_ANCHORED2ABS);
461                 } else {
462                         io_error |= IOERR_GENERAL;
463                         rprintf(FINFO,
464                             "cannot add local filter rules in long-named directory: %s\n",
465                             full_fname(dirbuf));
466                 }
467                 dirbuf[dirbuf_len] = '\0';
468         }
469
470         return (void*)push;
471 }
472
473 void pop_local_filters(void *mem)
474 {
475         struct filter_list_struct *ap, *pop = (struct filter_list_struct*)mem;
476         int i;
477
478         for (i = mergelist_cnt; i-- > 0; ) {
479                 struct filter_struct *ex = mergelist_parents[i];
480                 struct filter_list_struct *lp = ex->u.mergelist;
481
482                 if (verbose > 2) {
483                         rprintf(FINFO, "[%s] popping filter list%s\n",
484                                 who_am_i(), lp->debug_type);
485                 }
486
487                 clear_filter_list(lp);
488         }
489
490         if (!pop)
491                 return;
492
493         for (i = 0, ap = pop; i < mergelist_cnt; i++) {
494                 memcpy(mergelist_parents[i]->u.mergelist, ap++,
495                        sizeof (struct filter_list_struct));
496         }
497
498         free(pop);
499 }
500
501 static int rule_matches(char *name, struct filter_struct *ex, int name_is_dir)
502 {
503         int slash_handling, str_cnt = 0, anchored_match = 0;
504         int ret_match = ex->match_flags & MATCHFLG_NEGATE ? 0 : 1;
505         char *p, *pattern = ex->pattern;
506         const char *strings[16]; /* more than enough */
507
508         if (!*name)
509                 return 0;
510
511         if (!ex->u.slash_cnt && !(ex->match_flags & MATCHFLG_WILD2)) {
512                 /* If the pattern does not have any slashes AND it does
513                  * not have a "**" (which could match a slash), then we
514                  * just match the name portion of the path. */
515                 if ((p = strrchr(name,'/')) != NULL)
516                         name = p+1;
517         } else if (ex->match_flags & MATCHFLG_ABS_PATH && *name != '/'
518             && curr_dir_len > module_dirlen + 1) {
519                 /* If we're matching against an absolute-path pattern,
520                  * we need to prepend our full path info. */
521                 strings[str_cnt++] = curr_dir + module_dirlen + 1;
522                 strings[str_cnt++] = "/";
523         } else if (ex->match_flags & MATCHFLG_WILD2_PREFIX && *name != '/') {
524                 /* Allow "**"+"/" to match at the start of the string. */
525                 strings[str_cnt++] = "/";
526         }
527         strings[str_cnt++] = name;
528         if (name_is_dir) {
529                 /* Allow a trailing "/"+"***" to match the directory. */
530                 if (ex->match_flags & MATCHFLG_WILD3_SUFFIX)
531                         strings[str_cnt++] = "/";
532         } else if (ex->match_flags & MATCHFLG_DIRECTORY)
533                 return !ret_match;
534         strings[str_cnt] = NULL;
535
536         if (*pattern == '/') {
537                 anchored_match = 1;
538                 pattern++;
539                 if (strings[0][0] == '/')
540                         strings[0]++;
541         }
542
543         if (!anchored_match && ex->u.slash_cnt
544             && !(ex->match_flags & MATCHFLG_WILD2)) {
545                 /* A non-anchored match with an infix slash and no "**"
546                  * needs to match the last slash_cnt+1 name elements. */
547                 slash_handling = ex->u.slash_cnt + 1;
548         } else if (!anchored_match && !(ex->match_flags & MATCHFLG_WILD2_PREFIX)
549                                    && ex->match_flags & MATCHFLG_WILD2) {
550                 /* A non-anchored match with an infix or trailing "**" (but not
551                  * a prefixed "**") needs to try matching after every slash. */
552                 slash_handling = -1;
553         } else {
554                 /* The pattern matches only at the start of the path or name. */
555                 slash_handling = 0;
556         }
557
558         if (ex->match_flags & MATCHFLG_WILD) {
559                 if (wildmatch_array(pattern, strings, slash_handling))
560                         return ret_match;
561         } else if (str_cnt > 1) {
562                 if (litmatch_array(pattern, strings, slash_handling))
563                         return ret_match;
564         } else if (anchored_match) {
565                 if (strcmp(name,pattern) == 0)
566                         return ret_match;
567         } else {
568                 int l1 = strlen(name);
569                 int l2 = strlen(pattern);
570                 if (l2 <= l1 &&
571                     strcmp(name+(l1-l2),pattern) == 0 &&
572                     (l1==l2 || name[l1-(l2+1)] == '/')) {
573                         return ret_match;
574                 }
575         }
576
577         return !ret_match;
578 }
579
580
581 static void report_filter_result(char const *name,
582                                  struct filter_struct const *ent,
583                                  int name_is_dir, const char *type)
584 {
585         /* If a trailing slash is present to match only directories,
586          * then it is stripped out by add_rule().  So as a special
587          * case we add it back in here. */
588
589         if (verbose >= 2) {
590                 static char *actions[2][2]
591                     = { {"show", "hid"}, {"risk", "protect"} };
592                 const char *w = who_am_i();
593                 rprintf(FINFO, "[%s] %sing %s %s because of pattern %s%s%s\n",
594                     w, actions[*w!='s'][!(ent->match_flags&MATCHFLG_INCLUDE)],
595                     name_is_dir ? "directory" : "file", name, ent->pattern,
596                     ent->match_flags & MATCHFLG_DIRECTORY ? "/" : "", type);
597         }
598 }
599
600
601 /*
602  * Return -1 if file "name" is defined to be excluded by the specified
603  * exclude list, 1 if it is included, and 0 if it was not matched.
604  */
605 int check_filter(struct filter_list_struct *listp, char *name, int name_is_dir)
606 {
607         struct filter_struct *ent;
608
609         for (ent = listp->head; ent; ent = ent->next) {
610                 if (ent->match_flags & MATCHFLG_PERDIR_MERGE) {
611                         int rc = check_filter(ent->u.mergelist, name,
612                                               name_is_dir);
613                         if (rc)
614                                 return rc;
615                         continue;
616                 }
617                 if (ent->match_flags & MATCHFLG_CVS_IGNORE) {
618                         int rc = check_filter(&cvs_filter_list, name,
619                                               name_is_dir);
620                         if (rc)
621                                 return rc;
622                         continue;
623                 }
624                 if (rule_matches(name, ent, name_is_dir)) {
625                         report_filter_result(name, ent, name_is_dir,
626                                               listp->debug_type);
627                         return ent->match_flags & MATCHFLG_INCLUDE ? 1 : -1;
628                 }
629         }
630
631         return 0;
632 }
633
634 #define RULE_STRCMP(s,r) rule_strcmp((s), (r), sizeof (r) - 1)
635
636 static const uchar *rule_strcmp(const uchar *str, const char *rule, int rule_len)
637 {
638         if (strncmp((char*)str, rule, rule_len) != 0)
639                 return NULL;
640         if (isspace(str[rule_len]) || str[rule_len] == '_' || !str[rule_len])
641                 return str + rule_len - 1;
642         if (str[rule_len] == ',')
643                 return str + rule_len;
644         return NULL;
645 }
646
647 /* Get the next include/exclude arg from the string.  The token will not
648  * be '\0' terminated, so use the returned length to limit the string.
649  * Also, be sure to add this length to the returned pointer before passing
650  * it back to ask for the next token.  This routine parses the "!" (list-
651  * clearing) token and (depending on the mflags) the various prefixes.
652  * The *mflags_ptr value will be set on exit to the new MATCHFLG_* bits
653  * for the current token. */
654 static const char *parse_rule_tok(const char *p, uint32 mflags, int xflags,
655                                   unsigned int *len_ptr, uint32 *mflags_ptr)
656 {
657         const uchar *s = (const uchar *)p;
658         uint32 new_mflags;
659         unsigned int len;
660
661         if (mflags & MATCHFLG_WORD_SPLIT) {
662                 /* Skip over any initial whitespace. */
663                 while (isspace(*s))
664                         s++;
665                 /* Update to point to real start of rule. */
666                 p = (const char *)s;
667         }
668         if (!*s)
669                 return NULL;
670
671         new_mflags = mflags & MATCHFLGS_FROM_CONTAINER;
672
673         /* Figure out what kind of a filter rule "s" is pointing at.  Note
674          * that if MATCHFLG_NO_PREFIXES is set, the rule is either an include
675          * or an exclude based on the inheritance of the MATCHFLG_INCLUDE
676          * flag (above).  XFLG_OLD_PREFIXES indicates a compatibility mode
677          * for old include/exclude patterns where just "+ " and "- " are
678          * allowed as optional prefixes.  */
679         if (mflags & MATCHFLG_NO_PREFIXES) {
680                 if (*s == '!' && mflags & MATCHFLG_CVS_IGNORE)
681                         new_mflags |= MATCHFLG_CLEAR_LIST; /* Tentative! */
682         } else if (xflags & XFLG_OLD_PREFIXES) {
683                 if (*s == '-' && s[1] == ' ') {
684                         new_mflags &= ~MATCHFLG_INCLUDE;
685                         s += 2;
686                 } else if (*s == '+' && s[1] == ' ') {
687                         new_mflags |= MATCHFLG_INCLUDE;
688                         s += 2;
689                 } else if (*s == '!')
690                         new_mflags |= MATCHFLG_CLEAR_LIST; /* Tentative! */
691         } else {
692                 char ch = 0, *mods = "";
693                 switch (*s) {
694                 case 'c':
695                         if ((s = RULE_STRCMP(s, "clear")) != NULL)
696                                 ch = '!';
697                         break;
698                 case 'd':
699                         if ((s = RULE_STRCMP(s, "dir-merge")) != NULL)
700                                 ch = ':';
701                         break;
702                 case 'e':
703                         if ((s = RULE_STRCMP(s, "exclude")) != NULL)
704                                 ch = '-';
705                         break;
706                 case 'h':
707                         if ((s = RULE_STRCMP(s, "hide")) != NULL)
708                                 ch = 'H';
709                         break;
710                 case 'i':
711                         if ((s = RULE_STRCMP(s, "include")) != NULL)
712                                 ch = '+';
713                         break;
714                 case 'm':
715                         if ((s = RULE_STRCMP(s, "merge")) != NULL)
716                                 ch = '.';
717                         break;
718                 case 'p':
719                         if ((s = RULE_STRCMP(s, "protect")) != NULL)
720                                 ch = 'P';
721                         break;
722                 case 'r':
723                         if ((s = RULE_STRCMP(s, "risk")) != NULL)
724                                 ch = 'R';
725                         break;
726                 case 's':
727                         if ((s = RULE_STRCMP(s, "show")) != NULL)
728                                 ch = 'S';
729                         break;
730                 default:
731                         ch = *s;
732                         if (s[1] == ',')
733                                 s++;
734                         break;
735                 }
736                 switch (ch) {
737                 case ':':
738                         new_mflags |= MATCHFLG_PERDIR_MERGE
739                                     | MATCHFLG_FINISH_SETUP;
740                         /* FALL THROUGH */
741                 case '.':
742                         new_mflags |= MATCHFLG_MERGE_FILE;
743                         mods = MODIFIERS_INCL_EXCL MODIFIERS_MERGE_FILE;
744                         break;
745                 case '+':
746                         new_mflags |= MATCHFLG_INCLUDE;
747                         /* FALL THROUGH */
748                 case '-':
749                         mods = MODIFIERS_INCL_EXCL;
750                         break;
751                 case 'S':
752                         new_mflags |= MATCHFLG_INCLUDE;
753                         /* FALL THROUGH */
754                 case 'H':
755                         new_mflags |= MATCHFLG_SENDER_SIDE;
756                         mods = MODIFIERS_HIDE_PROTECT;
757                         break;
758                 case 'R':
759                         new_mflags |= MATCHFLG_INCLUDE;
760                         /* FALL THROUGH */
761                 case 'P':
762                         new_mflags |= MATCHFLG_RECEIVER_SIDE;
763                         mods = MODIFIERS_HIDE_PROTECT;
764                         break;
765                 case '!':
766                         new_mflags |= MATCHFLG_CLEAR_LIST;
767                         mods = NULL;
768                         break;
769                 default:
770                         rprintf(FERROR, "Unknown filter rule: `%s'\n", p);
771                         exit_cleanup(RERR_SYNTAX);
772                 }
773                 while (mods && *++s && *s != ' ' && *s != '_') {
774                         if (strchr(mods, *s) == NULL) {
775                                 if (mflags & MATCHFLG_WORD_SPLIT && isspace(*s)) {
776                                         s--;
777                                         break;
778                                 }
779                             invalid:
780                                 rprintf(FERROR,
781                                         "invalid modifier sequence at '%c' in filter rule: %s\n",
782                                         *s, p);
783                                 exit_cleanup(RERR_SYNTAX);
784                         }
785                         switch (*s) {
786                         case '-':
787                                 if (new_mflags & MATCHFLG_NO_PREFIXES)
788                                     goto invalid;
789                                 new_mflags |= MATCHFLG_NO_PREFIXES;
790                                 break;
791                         case '+':
792                                 if (new_mflags & MATCHFLG_NO_PREFIXES)
793                                     goto invalid;
794                                 new_mflags |= MATCHFLG_NO_PREFIXES
795                                             | MATCHFLG_INCLUDE;
796                                 break;
797                         case '/':
798                                 new_mflags |= MATCHFLG_ABS_PATH;
799                                 break;
800                         case '!':
801                                 new_mflags |= MATCHFLG_NEGATE;
802                                 break;
803                         case 'C':
804                                 if (new_mflags & MATCHFLG_NO_PREFIXES)
805                                     goto invalid;
806                                 new_mflags |= MATCHFLG_NO_PREFIXES
807                                             | MATCHFLG_WORD_SPLIT
808                                             | MATCHFLG_NO_INHERIT
809                                             | MATCHFLG_CVS_IGNORE;
810                                 break;
811                         case 'e':
812                                 new_mflags |= MATCHFLG_EXCLUDE_SELF;
813                                 break;
814                         case 'n':
815                                 new_mflags |= MATCHFLG_NO_INHERIT;
816                                 break;
817                         case 'r':
818                                 new_mflags |= MATCHFLG_RECEIVER_SIDE;
819                                 break;
820                         case 's':
821                                 new_mflags |= MATCHFLG_SENDER_SIDE;
822                                 break;
823                         case 'w':
824                                 new_mflags |= MATCHFLG_WORD_SPLIT;
825                                 break;
826                         }
827                 }
828                 if (*s)
829                         s++;
830         }
831
832         if (mflags & MATCHFLG_WORD_SPLIT) {
833                 const uchar *cp = s;
834                 /* Token ends at whitespace or the end of the string. */
835                 while (!isspace(*cp) && *cp != '\0')
836                         cp++;
837                 len = cp - s;
838         } else
839                 len = strlen((char*)s);
840
841         if (new_mflags & MATCHFLG_CLEAR_LIST) {
842                 if (!(mflags & MATCHFLG_NO_PREFIXES)
843                  && !(xflags & XFLG_OLD_PREFIXES) && len) {
844                         rprintf(FERROR,
845                                 "'!' rule has trailing characters: %s\n", p);
846                         exit_cleanup(RERR_SYNTAX);
847                 }
848                 if (len > 1)
849                         new_mflags &= ~MATCHFLG_CLEAR_LIST;
850         } else if (!len && !(new_mflags & MATCHFLG_CVS_IGNORE)) {
851                 rprintf(FERROR, "unexpected end of filter rule: %s\n", p);
852                 exit_cleanup(RERR_SYNTAX);
853         }
854
855         *len_ptr = len;
856         *mflags_ptr = new_mflags;
857         return (const char *)s;
858 }
859
860
861 static char default_cvsignore[] = 
862         /* These default ignored items come from the CVS manual. */
863         "RCS SCCS CVS CVS.adm RCSLOG cvslog.* tags TAGS"
864         " .make.state .nse_depinfo *~ #* .#* ,* _$* *$"
865         " *.old *.bak *.BAK *.orig *.rej .del-*"
866         " *.a *.olb *.o *.obj *.so *.exe"
867         " *.Z *.elc *.ln core"
868         /* The rest we added to suit ourself. */
869         " .svn/";
870
871 static void get_cvs_excludes(uint32 mflags)
872 {
873         char *p, fname[MAXPATHLEN];
874         static int initialized = 0;
875
876         if (initialized)
877                 return;
878         initialized = 1;
879
880         parse_rule(&cvs_filter_list, default_cvsignore, mflags, 0);
881
882         p = module_id >= 0 && lp_use_chroot(module_id) ? "/" : getenv("HOME");
883         if (p && pathjoin(fname, MAXPATHLEN, p, ".cvsignore") < MAXPATHLEN)
884                 parse_filter_file(&cvs_filter_list, fname, mflags, 0);
885
886         parse_rule(&cvs_filter_list, getenv("CVSIGNORE"), mflags, 0);
887 }
888
889
890 void parse_rule(struct filter_list_struct *listp, const char *pattern,
891                 uint32 mflags, int xflags)
892 {
893         unsigned int pat_len;
894         uint32 new_mflags;
895         const char *cp, *p;
896
897         if (!pattern)
898                 return;
899
900         while (1) {
901                 /* Remember that the returned string is NOT '\0' terminated! */
902                 cp = parse_rule_tok(pattern, mflags, xflags,
903                                     &pat_len, &new_mflags);
904                 if (!cp)
905                         break;
906                 if (pat_len >= MAXPATHLEN) {
907                         rprintf(FERROR, "discarding over-long filter: %s\n",
908                                 cp);
909                         continue;
910                 }
911                 pattern = cp + pat_len;
912
913                 if (new_mflags & MATCHFLG_CLEAR_LIST) {
914                         if (verbose > 2) {
915                                 rprintf(FINFO,
916                                         "[%s] clearing filter list%s\n",
917                                         who_am_i(), listp->debug_type);
918                         }
919                         clear_filter_list(listp);
920                         continue;
921                 }
922
923                 if (new_mflags & MATCHFLG_MERGE_FILE) {
924                         unsigned int len;
925                         if (!pat_len) {
926                                 cp = ".cvsignore";
927                                 pat_len = 10;
928                         }
929                         len = pat_len;
930                         if (new_mflags & MATCHFLG_EXCLUDE_SELF) {
931                                 const char *name = strrchr(cp, '/');
932                                 if (name)
933                                         len -= ++name - cp;
934                                 else
935                                         name = cp;
936                                 add_rule(listp, name, len, 0, 0);
937                                 new_mflags &= ~MATCHFLG_EXCLUDE_SELF;
938                                 len = pat_len;
939                         }
940                         if (new_mflags & MATCHFLG_PERDIR_MERGE) {
941                                 if (parent_dirscan) {
942                                         if (!(p = parse_merge_name(cp, &len,
943                                                                 module_dirlen)))
944                                                 continue;
945                                         add_rule(listp, p, len, new_mflags, 0);
946                                         continue;
947                                 }
948                         } else {
949                                 if (!(p = parse_merge_name(cp, &len, 0)))
950                                         continue;
951                                 parse_filter_file(listp, p, new_mflags,
952                                                   XFLG_FATAL_ERRORS);
953                                 continue;
954                         }
955                 }
956
957                 add_rule(listp, cp, pat_len, new_mflags, xflags);
958
959                 if (new_mflags & MATCHFLG_CVS_IGNORE
960                     && !(new_mflags & MATCHFLG_MERGE_FILE))
961                         get_cvs_excludes(new_mflags);
962         }
963 }
964
965
966 void parse_filter_file(struct filter_list_struct *listp, const char *fname,
967                        uint32 mflags, int xflags)
968 {
969         FILE *fp;
970         char line[BIGPATHBUFLEN];
971         char *eob = line + sizeof line - 1;
972         int word_split = mflags & MATCHFLG_WORD_SPLIT;
973
974         if (!fname || !*fname)
975                 return;
976
977         if (*fname != '-' || fname[1] || am_server) {
978                 if (server_filter_list.head) {
979                         strlcpy(line, fname, sizeof line);
980                         clean_fname(line, 1);
981                         if (check_filter(&server_filter_list, line, 0) < 0)
982                                 fp = NULL;
983                         else
984                                 fp = fopen(line, "rb");
985                 } else
986                         fp = fopen(fname, "rb");
987         } else
988                 fp = stdin;
989
990         if (verbose > 2) {
991                 rprintf(FINFO, "[%s] parse_filter_file(%s,%x,%x)%s\n",
992                         who_am_i(), fname, mflags, xflags,
993                         fp ? "" : " [not found]");
994         }
995
996         if (!fp) {
997                 if (xflags & XFLG_FATAL_ERRORS) {
998                         rsyserr(FERROR, errno,
999                                 "failed to open %sclude file %s",
1000                                 mflags & MATCHFLG_INCLUDE ? "in" : "ex",
1001                                 fname);
1002                         exit_cleanup(RERR_FILEIO);
1003                 }
1004                 return;
1005         }
1006         dirbuf[dirbuf_len] = '\0';
1007
1008         while (1) {
1009                 char *s = line;
1010                 int ch, overflow = 0;
1011                 while (1) {
1012                         if ((ch = getc(fp)) == EOF) {
1013                                 if (ferror(fp) && errno == EINTR) {
1014                                         clearerr(fp);
1015                                         continue;
1016                                 }
1017                                 break;
1018                         }
1019                         if (word_split && isspace(ch))
1020                                 break;
1021                         if (eol_nulls? !ch : (ch == '\n' || ch == '\r'))
1022                                 break;
1023                         if (s < eob)
1024                                 *s++ = ch;
1025                         else
1026                                 overflow = 1;
1027                 }
1028                 if (overflow) {
1029                         rprintf(FERROR, "discarding over-long filter: %s...\n", line);
1030                         s = line;
1031                 }
1032                 *s = '\0';
1033                 /* Skip an empty token and (when line parsing) comments. */
1034                 if (*line && (word_split || (*line != ';' && *line != '#')))
1035                         parse_rule(listp, line, mflags, xflags);
1036                 if (ch == EOF)
1037                         break;
1038         }
1039         fclose(fp);
1040 }
1041
1042 /* If the "for_xfer" flag is set, the prefix is made compatible with the
1043  * current protocol_version (if possible) or a NULL is returned (if not
1044  * possible). */
1045 char *get_rule_prefix(int match_flags, const char *pat, int for_xfer,
1046                       unsigned int *plen_ptr)
1047 {
1048         static char buf[MAX_RULE_PREFIX+1];
1049         char *op = buf;
1050         int legal_len = for_xfer && protocol_version < 29 ? 1 : MAX_RULE_PREFIX-1;
1051
1052         if (match_flags & MATCHFLG_PERDIR_MERGE) {
1053                 if (legal_len == 1)
1054                         return NULL;
1055                 *op++ = ':';
1056         } else if (match_flags & MATCHFLG_INCLUDE)
1057                 *op++ = '+';
1058         else if (legal_len != 1
1059             || ((*pat == '-' || *pat == '+') && pat[1] == ' '))
1060                 *op++ = '-';
1061         else
1062                 legal_len = 0;
1063
1064         if (match_flags & MATCHFLG_CVS_IGNORE)
1065                 *op++ = 'C';
1066         else {
1067                 if (match_flags & MATCHFLG_NO_INHERIT)
1068                         *op++ = 'n';
1069                 if (match_flags & MATCHFLG_WORD_SPLIT)
1070                         *op++ = 'w';
1071                 if (match_flags & MATCHFLG_NO_PREFIXES) {
1072                         if (match_flags & MATCHFLG_INCLUDE)
1073                                 *op++ = '+';
1074                         else
1075                                 *op++ = '-';
1076                 }
1077         }
1078         if (match_flags & MATCHFLG_EXCLUDE_SELF)
1079                 *op++ = 'e';
1080         if (match_flags & MATCHFLG_SENDER_SIDE
1081             && (!for_xfer || protocol_version >= 29))
1082                 *op++ = 's';
1083         if (match_flags & MATCHFLG_RECEIVER_SIDE
1084             && (!for_xfer || protocol_version >= 29
1085              || (delete_excluded && am_sender)))
1086                 *op++ = 'r';
1087         if (op - buf > legal_len)
1088                 return NULL;
1089         if (legal_len)
1090                 *op++ = ' ';
1091         *op = '\0';
1092         if (plen_ptr)
1093                 *plen_ptr = op - buf;
1094         return buf;
1095 }
1096
1097 static void send_rules(int f_out, struct filter_list_struct *flp)
1098 {
1099         struct filter_struct *ent, *prev = NULL;
1100
1101         for (ent = flp->head; ent; ent = ent->next) {
1102                 unsigned int len, plen, dlen;
1103                 int elide = 0;
1104                 char *p;
1105
1106                 if (ent->match_flags & MATCHFLG_SENDER_SIDE)
1107                         elide = am_sender ? 1 : -1;
1108                 if (ent->match_flags & MATCHFLG_RECEIVER_SIDE)
1109                         elide = elide ? 0 : am_sender ? -1 : 1;
1110                 else if (delete_excluded && !elide)
1111                         elide = am_sender ? 1 : -1;
1112                 if (elide < 0) {
1113                         if (prev)
1114                                 prev->next = ent->next;
1115                         else
1116                                 flp->head = ent->next;
1117                 } else
1118                         prev = ent;
1119                 if (elide > 0)
1120                         continue;
1121                 if (ent->match_flags & MATCHFLG_CVS_IGNORE
1122                     && !(ent->match_flags & MATCHFLG_MERGE_FILE)) {
1123                         int f = am_sender || protocol_version < 29 ? f_out : -2;
1124                         send_rules(f, &cvs_filter_list);
1125                         if (f == f_out)
1126                                 continue;
1127                 }
1128                 p = get_rule_prefix(ent->match_flags, ent->pattern, 1, &plen);
1129                 if (!p) {
1130                         rprintf(FERROR,
1131                                 "filter rules are too modern for remote rsync.\n");
1132                         exit_cleanup(RERR_SYNTAX);
1133                 }
1134                 if (f_out < 0)
1135                         continue;
1136                 len = strlen(ent->pattern);
1137                 dlen = ent->match_flags & MATCHFLG_DIRECTORY ? 1 : 0;
1138                 if (!(plen + len + dlen))
1139                         continue;
1140                 write_int(f_out, plen + len + dlen);
1141                 if (plen)
1142                         write_buf(f_out, p, plen);
1143                 write_buf(f_out, ent->pattern, len);
1144                 if (dlen)
1145                         write_byte(f_out, '/');
1146         }
1147         flp->tail = prev;
1148 }
1149
1150 /* This is only called by the client. */
1151 void send_filter_list(int f_out)
1152 {
1153         int receiver_wants_list = prune_empty_dirs
1154             || (delete_mode && (!delete_excluded || protocol_version >= 29));
1155
1156         if (local_server || (am_sender && !receiver_wants_list))
1157                 f_out = -1;
1158         if (cvs_exclude && am_sender) {
1159                 if (protocol_version >= 29)
1160                         parse_rule(&filter_list, ":C", 0, 0);
1161                 parse_rule(&filter_list, "-C", 0, 0);
1162         }
1163
1164         /* This is a complete hack - blame Rusty.  FIXME!
1165          * Remove this hack when older rsyncs (below 2.6.4) are gone. */
1166         if (list_only == 1 && !recurse)
1167                 parse_rule(&filter_list, "/*/*", MATCHFLG_NO_PREFIXES, 0);
1168
1169         send_rules(f_out, &filter_list);
1170
1171         if (f_out >= 0)
1172                 write_int(f_out, 0);
1173
1174         if (cvs_exclude) {
1175                 if (!am_sender || protocol_version < 29)
1176                         parse_rule(&filter_list, ":C", 0, 0);
1177                 if (!am_sender)
1178                         parse_rule(&filter_list, "-C", 0, 0);
1179         }
1180 }
1181
1182 /* This is only called by the server. */
1183 void recv_filter_list(int f_in)
1184 {
1185         char line[BIGPATHBUFLEN];
1186         int xflags = protocol_version >= 29 ? 0 : XFLG_OLD_PREFIXES;
1187         int receiver_wants_list = prune_empty_dirs
1188             || (saw_delete_opt
1189              && (!saw_delete_excluded_opt || protocol_version >= 29));
1190         unsigned int len;
1191
1192         if (!local_server && (am_sender || receiver_wants_list)) {
1193                 while ((len = read_int(f_in)) != 0) {
1194                         if (len >= sizeof line)
1195                                 overflow_exit("recv_rules");
1196                         read_sbuf(f_in, line, len);
1197                         parse_rule(&filter_list, line, 0, xflags);
1198                 }
1199         }
1200
1201         if (cvs_exclude) {
1202                 if (local_server || am_sender || protocol_version < 29)
1203                         parse_rule(&filter_list, ":C", 0, 0);
1204                 if (local_server || am_sender)
1205                         parse_rule(&filter_list, "-C", 0, 0);
1206         }
1207
1208         if (local_server) /* filter out any rules that aren't for us. */
1209                 send_rules(-1, &filter_list);
1210 }