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