Fix handling of daemon module names in file-list verification; convert some while...
[rsync.git] / exclude.c
1 /*
2  * The filter include/exclude routines.
3  *
4  * Copyright (C) 1996-2001 Andrew Tridgell <tridge@samba.org>
5  * Copyright (C) 1996 Paul Mackerras
6  * Copyright (C) 2002 Martin Pool
7  * Copyright (C) 2003-2022 Wayne Davison
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, visit the http://fsf.org website.
21  */
22
23 #include "rsync.h"
24 #include "ifuncs.h"
25
26 extern int am_server;
27 extern int am_sender;
28 extern int am_generator;
29 extern int eol_nulls;
30 extern int io_error;
31 extern int xfer_dirs;
32 extern int recurse;
33 extern int local_server;
34 extern int prune_empty_dirs;
35 extern int ignore_perishable;
36 extern int old_style_args;
37 extern int relative_paths;
38 extern int delete_mode;
39 extern int delete_excluded;
40 extern int cvs_exclude;
41 extern int sanitize_paths;
42 extern int protocol_version;
43 extern int read_batch;
44 extern int list_only;
45 extern int module_id;
46
47 extern char *filesfrom_host;
48 extern char curr_dir[MAXPATHLEN];
49 extern unsigned int curr_dir_len;
50 extern unsigned int module_dirlen;
51
52 filter_rule_list filter_list = { .debug_type = "" };
53 filter_rule_list cvs_filter_list = { .debug_type = " [global CVS]" };
54 filter_rule_list daemon_filter_list = { .debug_type = " [daemon]" };
55 filter_rule_list implied_filter_list = { .debug_type = " [implied]" };
56
57 int saw_xattr_filter = 0;
58 int trust_sender_filter = 0;
59
60 /* Need room enough for ":MODS " prefix plus some room to grow. */
61 #define MAX_RULE_PREFIX (16)
62
63 #define SLASH_WILD3_SUFFIX "/***"
64
65 /* The dirbuf is set by push_local_filters() to the current subdirectory
66  * relative to curr_dir that is being processed.  The path always has a
67  * trailing slash appended, and the variable dirbuf_len contains the length
68  * of this path prefix.  The path is always absolute. */
69 static char dirbuf[MAXPATHLEN+1];
70 static unsigned int dirbuf_len = 0;
71 static int dirbuf_depth;
72
73 /* This is True when we're scanning parent dirs for per-dir merge-files. */
74 static BOOL parent_dirscan = False;
75
76 /* This array contains a list of all the currently active per-dir merge
77  * files.  This makes it easier to save the appropriate values when we
78  * "push" down into each subdirectory. */
79 static filter_rule **mergelist_parents;
80 static int mergelist_cnt = 0;
81 static int mergelist_size = 0;
82
83 /* Each filter_list_struct describes a singly-linked list by keeping track
84  * of both the head and tail pointers.  The list is slightly unusual in that
85  * a parent-dir's content can be appended to the end of the local list in a
86  * special way:  the last item in the local list has its "next" pointer set
87  * to point to the inherited list, but the local list's tail pointer points
88  * at the end of the local list.  Thus, if the local list is empty, the head
89  * will be pointing at the inherited content but the tail will be NULL.  To
90  * help you visualize this, here are the possible list arrangements:
91  *
92  * Completely Empty                     Local Content Only
93  * ==================================   ====================================
94  * head -> NULL                         head -> Local1 -> Local2 -> NULL
95  * tail -> NULL                         tail -------------^
96  *
97  * Inherited Content Only               Both Local and Inherited Content
98  * ==================================   ====================================
99  * head -> Parent1 -> Parent2 -> NULL   head -> L1 -> L2 -> P1 -> P2 -> NULL
100  * tail -> NULL                         tail ---------^
101  *
102  * This means that anyone wanting to traverse the whole list to use it just
103  * needs to start at the head and use the "next" pointers until it goes
104  * NULL.  To add new local content, we insert the item after the tail item
105  * and update the tail (obviously, if "tail" was NULL, we insert it at the
106  * head).  To clear the local list, WE MUST NOT FREE THE INHERITED CONTENT
107  * because it is shared between the current list and our parent list(s).
108  * The easiest way to handle this is to simply truncate the list after the
109  * tail item and then free the local list from the head.  When inheriting
110  * the list for a new local dir, we just save off the filter_list_struct
111  * values (so we can pop back to them later) and set the tail to NULL.
112  */
113
114 static void teardown_mergelist(filter_rule *ex)
115 {
116         int j;
117
118         if (!ex->u.mergelist)
119                 return;
120
121         if (DEBUG_GTE(FILTER, 2)) {
122                 rprintf(FINFO, "[%s] deactivating mergelist #%d%s\n",
123                         who_am_i(), mergelist_cnt - 1,
124                         ex->u.mergelist->debug_type);
125         }
126
127         free(ex->u.mergelist->debug_type);
128         free(ex->u.mergelist);
129
130         for (j = 0; j < mergelist_cnt; j++) {
131                 if (mergelist_parents[j] == ex) {
132                         mergelist_parents[j] = NULL;
133                         break;
134                 }
135         }
136         while (mergelist_cnt && mergelist_parents[mergelist_cnt-1] == NULL)
137                 mergelist_cnt--;
138 }
139
140 static void free_filter(filter_rule *ex)
141 {
142         if (ex->rflags & FILTRULE_PERDIR_MERGE)
143                 teardown_mergelist(ex);
144         free(ex->pattern);
145         free(ex);
146 }
147
148 static void free_filters(filter_rule *ent)
149 {
150         while (ent) {
151                 filter_rule *next = ent->next;
152                 free_filter(ent);
153                 ent = next;
154         }
155 }
156
157 /* Build a filter structure given a filter pattern.  The value in "pat"
158  * is not null-terminated.  "rule" is either held or freed, so the
159  * caller should not free it. */
160 static void add_rule(filter_rule_list *listp, const char *pat, unsigned int pat_len,
161                      filter_rule *rule, int xflags)
162 {
163         const char *cp;
164         unsigned int pre_len, suf_len, slash_cnt = 0;
165         char *mention_rule_suffix;
166
167         if (DEBUG_GTE(FILTER, 1) && pat_len && (pat[pat_len-1] == ' ' || pat[pat_len-1] == '\t'))
168                 mention_rule_suffix = " -- CAUTION: trailing whitespace!";
169         else
170                 mention_rule_suffix = DEBUG_GTE(FILTER, 2) ? "" : NULL;
171         if (mention_rule_suffix) {
172                 rprintf(FINFO, "[%s] add_rule(%s%.*s%s)%s%s\n",
173                         who_am_i(), get_rule_prefix(rule, pat, 0, NULL),
174                         (int)pat_len, pat, (rule->rflags & FILTRULE_DIRECTORY) ? "/" : "",
175                         listp->debug_type, mention_rule_suffix);
176         }
177
178         /* These flags also indicate that we're reading a list that
179          * needs to be filtered now, not post-filtered later. */
180         if (xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH)
181                 && (rule->rflags & FILTRULES_SIDES)
182                         == (am_sender ? FILTRULE_RECEIVER_SIDE : FILTRULE_SENDER_SIDE)) {
183                 /* This filter applies only to the other side.  Drop it. */
184                 free_filter(rule);
185                 return;
186         }
187
188         if (pat_len > 1 && pat[pat_len-1] == '/') {
189                 pat_len--;
190                 rule->rflags |= FILTRULE_DIRECTORY;
191         }
192
193         for (cp = pat; cp < pat + pat_len; cp++) {
194                 if (*cp == '/')
195                         slash_cnt++;
196         }
197
198         if (!(rule->rflags & (FILTRULE_ABS_PATH | FILTRULE_MERGE_FILE))
199          && ((xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH) && *pat == '/')
200           || (xflags & XFLG_ABS_IF_SLASH && slash_cnt))) {
201                 rule->rflags |= FILTRULE_ABS_PATH;
202                 if (*pat == '/')
203                         pre_len = dirbuf_len - module_dirlen - 1;
204                 else
205                         pre_len = 0;
206         } else
207                 pre_len = 0;
208
209         /* The daemon wants dir-exclude rules to get an appended "/" + "***". */
210         if (xflags & XFLG_DIR2WILD3
211          && BITS_SETnUNSET(rule->rflags, FILTRULE_DIRECTORY, FILTRULE_INCLUDE)) {
212                 rule->rflags &= ~FILTRULE_DIRECTORY;
213                 suf_len = sizeof SLASH_WILD3_SUFFIX - 1;
214         } else
215                 suf_len = 0;
216
217         rule->pattern = new_array(char, pre_len + pat_len + suf_len + 1);
218         if (pre_len) {
219                 memcpy(rule->pattern, dirbuf + module_dirlen, pre_len);
220                 for (cp = rule->pattern; cp < rule->pattern + pre_len; cp++) {
221                         if (*cp == '/')
222                                 slash_cnt++;
223                 }
224         }
225         strlcpy(rule->pattern + pre_len, pat, pat_len + 1);
226         pat_len += pre_len;
227         if (suf_len) {
228                 memcpy(rule->pattern + pat_len, SLASH_WILD3_SUFFIX, suf_len+1);
229                 pat_len += suf_len;
230                 slash_cnt++;
231         }
232
233         if (strpbrk(rule->pattern, "*[?")) {
234                 rule->rflags |= FILTRULE_WILD;
235                 if ((cp = strstr(rule->pattern, "**")) != NULL) {
236                         rule->rflags |= FILTRULE_WILD2;
237                         /* If the pattern starts with **, note that. */
238                         if (cp == rule->pattern)
239                                 rule->rflags |= FILTRULE_WILD2_PREFIX;
240                         /* If the pattern ends with ***, note that. */
241                         if (pat_len >= 3
242                          && rule->pattern[pat_len-3] == '*'
243                          && rule->pattern[pat_len-2] == '*'
244                          && rule->pattern[pat_len-1] == '*')
245                                 rule->rflags |= FILTRULE_WILD3_SUFFIX;
246                 }
247         }
248
249         if (rule->rflags & FILTRULE_PERDIR_MERGE) {
250                 filter_rule_list *lp;
251                 unsigned int len;
252                 int i;
253
254                 if ((cp = strrchr(rule->pattern, '/')) != NULL)
255                         cp++;
256                 else
257                         cp = rule->pattern;
258
259                 /* If the local merge file was already mentioned, don't
260                  * add it again. */
261                 for (i = 0; i < mergelist_cnt; i++) {
262                         filter_rule *ex = mergelist_parents[i];
263                         const char *s;
264                         if (!ex)
265                                 continue;
266                         s = strrchr(ex->pattern, '/');
267                         if (s)
268                                 s++;
269                         else
270                                 s = ex->pattern;
271                         len = strlen(s);
272                         if (len == pat_len - (cp - rule->pattern) && memcmp(s, cp, len) == 0) {
273                                 free_filter(rule);
274                                 return;
275                         }
276                 }
277
278                 lp = new_array0(filter_rule_list, 1);
279                 if (asprintf(&lp->debug_type, " [per-dir %s]", cp) < 0)
280                         out_of_memory("add_rule");
281                 rule->u.mergelist = lp;
282
283                 if (mergelist_cnt == mergelist_size) {
284                         mergelist_size += 5;
285                         mergelist_parents = realloc_array(mergelist_parents, filter_rule *, mergelist_size);
286                 }
287                 if (DEBUG_GTE(FILTER, 2)) {
288                         rprintf(FINFO, "[%s] activating mergelist #%d%s\n",
289                                 who_am_i(), mergelist_cnt, lp->debug_type);
290                 }
291                 mergelist_parents[mergelist_cnt++] = rule;
292         } else
293                 rule->u.slash_cnt = slash_cnt;
294
295         if (!listp->tail) {
296                 rule->next = listp->head;
297                 listp->head = listp->tail = rule;
298         } else {
299                 rule->next = listp->tail->next;
300                 listp->tail->next = rule;
301                 listp->tail = rule;
302         }
303 }
304
305 /* If the wildcards failed, the remote shell might give us a file matching the literal
306  * wildcards.  Since "*" & "?" already match themselves, this just needs to deal with
307  * failed "[foo]" idioms.
308  */
309 static void maybe_add_literal_brackets_rule(filter_rule const *based_on, int arg_len)
310 {
311         filter_rule *rule;
312         const char *arg = based_on->pattern, *cp;
313         char *p;
314         int cnt = 0;
315
316         if (arg_len < 0)
317                 arg_len = strlen(arg);
318
319         for (cp = arg; *cp; cp++) {
320                 if (*cp == '\\' && cp[1]) {
321                         cp++;
322                 } else if (*cp == '[')
323                         cnt++;
324         }
325         if (!cnt)
326                 return;
327
328         rule = new0(filter_rule);
329         rule->rflags = based_on->rflags;
330         rule->u.slash_cnt = based_on->u.slash_cnt;
331         p = rule->pattern = new_array(char, arg_len + cnt + 1);
332         for (cp = arg; *cp; ) {
333                 if (*cp == '\\' && cp[1]) {
334                         *p++ = *cp++;
335                 } else if (*cp == '[')
336                         *p++ = '\\';
337                 *p++ = *cp++;
338         }
339         *p++ = '\0';
340
341         rule->next = implied_filter_list.head;
342         implied_filter_list.head = rule;
343         if (DEBUG_GTE(FILTER, 3)) {
344                 rprintf(FINFO, "[%s] add_implied_include(%s%s)\n", who_am_i(), rule->pattern,
345                         rule->rflags & FILTRULE_DIRECTORY ? "/" : "");
346         }
347 }
348
349 static char *partial_string_buf = NULL;
350 static int partial_string_len = 0;
351 void implied_include_partial_string(const char *s_start, const char *s_end)
352 {
353         partial_string_len = s_end - s_start;
354         if (partial_string_len <= 0 || partial_string_len >= MAXPATHLEN) { /* too-large should be impossible... */
355                 partial_string_len = 0;
356                 return;
357         }
358         if (!partial_string_buf)
359                 partial_string_buf = new_array(char, MAXPATHLEN);
360         memcpy(partial_string_buf, s_start, partial_string_len);
361 }
362
363 void free_implied_include_partial_string()
364 {
365         if (partial_string_buf) {
366                 free(partial_string_buf);
367                 partial_string_buf = NULL;
368         }
369 }
370
371 /* Each arg the client sends to the remote sender turns into an implied include
372  * that the receiver uses to validate the file list from the sender. */
373 void add_implied_include(const char *arg, int skip_daemon_module)
374 {
375         filter_rule *rule;
376         int arg_len, saw_wild = 0, saw_live_open_brkt = 0, backslash_cnt = 0;
377         int slash_cnt = 1; /* We know we're adding a leading slash. */
378         const char *cp;
379         char *p;
380         if (am_server || old_style_args || list_only || read_batch || filesfrom_host != NULL)
381                 return;
382         if (partial_string_len) {
383                 arg_len = strlen(arg);
384                 if (partial_string_len + arg_len >= MAXPATHLEN)
385                         return; /* Should be impossible... */
386                 memcpy(partial_string_buf + partial_string_len, arg, arg_len + 1);
387                 partial_string_len = 0;
388                 arg = partial_string_buf;
389         }
390         if (skip_daemon_module) {
391                 if ((cp = strchr(arg, '/')) != NULL)
392                         arg = cp + 1;
393                 else
394                         arg = "";
395         }
396         if (relative_paths) {
397                 if ((cp = strstr(arg, "/./")) != NULL)
398                         arg = cp + 3;
399         } else if ((cp = strrchr(arg, '/')) != NULL) {
400                 arg = cp + 1;
401                 if (*arg == '.' && arg[1] == '\0')
402                         arg++;
403         }
404         arg_len = strlen(arg);
405         if (arg_len) {
406                 if (strpbrk(arg, "*[?")) {
407                         /* We need to add room to escape backslashes if wildcard chars are present. */
408                         for (cp = arg; (cp = strchr(cp, '\\')) != NULL; cp++)
409                                 arg_len++;
410                         saw_wild = 1;
411                 }
412                 arg_len++; /* Leave room for the prefixed slash */
413                 rule = new0(filter_rule);
414                 if (!implied_filter_list.head)
415                         implied_filter_list.head = implied_filter_list.tail = rule;
416                 else {
417                         rule->next = implied_filter_list.head;
418                         implied_filter_list.head = rule;
419                 }
420                 rule->rflags = FILTRULE_INCLUDE + (saw_wild ? FILTRULE_WILD : 0);
421                 p = rule->pattern = new_array(char, arg_len + 1);
422                 *p++ = '/';
423                 for (cp = arg; *cp; ) {
424                         switch (*cp) {
425                           case '\\':
426                                 if (cp[1] == ']')
427                                         cp++; /* A \] in a filter might cause a problem w/o wildcards. */
428                                 else if (!strchr("*[?", cp[1])) {
429                                         backslash_cnt++;
430                                         if (saw_wild)
431                                                 *p++ = '\\';
432                                 }
433                                 *p++ = *cp++;
434                                 break;
435                           case '/':
436                                 if (p[-1] == '/') { /* This is safe because of the initial slash. */
437                                         cp++;
438                                         break;
439                                 }
440                                 if (relative_paths) {
441                                         filter_rule const *ent;
442                                         int found = 0;
443                                         *p = '\0';
444                                         for (ent = implied_filter_list.head; ent; ent = ent->next) {
445                                                 if (ent != rule && strcmp(ent->pattern, rule->pattern) == 0) {
446                                                         found = 1;
447                                                         break;
448                                                 }
449                                         }
450                                         if (!found) {
451                                                 filter_rule *R_rule = new0(filter_rule);
452                                                 R_rule->rflags = FILTRULE_INCLUDE | FILTRULE_DIRECTORY;
453                                                 /* Check if our sub-path has wildcards or escaped backslashes */
454                                                 if (saw_wild && strpbrk(rule->pattern, "*[?\\"))
455                                                         R_rule->rflags |= FILTRULE_WILD;
456                                                 R_rule->pattern = strdup(rule->pattern);
457                                                 R_rule->u.slash_cnt = slash_cnt;
458                                                 R_rule->next = implied_filter_list.head;
459                                                 implied_filter_list.head = R_rule;
460                                                 if (DEBUG_GTE(FILTER, 3)) {
461                                                         rprintf(FINFO, "[%s] add_implied_include(%s/)\n",
462                                                                 who_am_i(), R_rule->pattern);
463                                                 }
464                                                 if (saw_live_open_brkt)
465                                                         maybe_add_literal_brackets_rule(R_rule, -1);
466                                         }
467                                 }
468                                 slash_cnt++;
469                                 *p++ = *cp++;
470                                 break;
471                           case '[':
472                                 saw_live_open_brkt = 1;
473                                 *p++ = *cp++;
474                                 break;
475                           default:
476                                 *p++ = *cp++;
477                                 break;
478                         }
479                 }
480                 *p = '\0';
481                 rule->u.slash_cnt = slash_cnt;
482                 arg = rule->pattern;
483                 arg_len = p - arg; /* We recompute it due to backslash weirdness. */
484                 if (DEBUG_GTE(FILTER, 3))
485                         rprintf(FINFO, "[%s] add_implied_include(%s)\n", who_am_i(), rule->pattern);
486                 if (saw_live_open_brkt)
487                         maybe_add_literal_brackets_rule(rule, arg_len);
488         }
489
490         if (recurse || xfer_dirs) {
491                 /* Now create a rule with an added "/" & "**" or "*" at the end */
492                 rule = new0(filter_rule);
493                 rule->rflags = FILTRULE_INCLUDE | FILTRULE_WILD;
494                 if (recurse)
495                         rule->rflags |= FILTRULE_WILD2;
496                 /* We must leave enough room for / * * \0. */
497                 if (!saw_wild && backslash_cnt) {
498                         /* We are appending a wildcard, so now the backslashes need to be escaped. */
499                         p = rule->pattern = new_array(char, arg_len + backslash_cnt + 3 + 1);
500                         for (cp = arg; *cp; ) {
501                                 if (*cp == '\\')
502                                         *p++ = '\\';
503                                 *p++ = *cp++;
504                         }
505                 } else {
506                         p = rule->pattern = new_array(char, arg_len + 3 + 1);
507                         if (arg_len) {
508                                 memcpy(p, arg, arg_len);
509                                 p += arg_len;
510                         }
511                 }
512                 if (p[-1] != '/')
513                         *p++ = '/';
514                 *p++ = '*';
515                 if (recurse)
516                         *p++ = '*';
517                 *p = '\0';
518                 rule->u.slash_cnt = slash_cnt + 1;
519                 rule->next = implied_filter_list.head;
520                 implied_filter_list.head = rule;
521                 if (DEBUG_GTE(FILTER, 3))
522                         rprintf(FINFO, "[%s] add_implied_include(%s)\n", who_am_i(), rule->pattern);
523                 if (saw_live_open_brkt)
524                         maybe_add_literal_brackets_rule(rule, p - rule->pattern);
525         }
526 }
527
528 /* This frees any non-inherited items, leaving just inherited items on the list. */
529 static void pop_filter_list(filter_rule_list *listp)
530 {
531         filter_rule *inherited;
532
533         if (!listp->tail)
534                 return;
535
536         inherited = listp->tail->next;
537
538         /* Truncate any inherited items from the local list. */
539         listp->tail->next = NULL;
540         /* Now free everything that is left. */
541         free_filters(listp->head);
542
543         listp->head = inherited;
544         listp->tail = NULL;
545 }
546
547 /* This returns an expanded (absolute) filename for the merge-file name if
548  * the name has any slashes in it OR if the parent_dirscan var is True;
549  * otherwise it returns the original merge_file name.  If the len_ptr value
550  * is non-NULL the merge_file name is limited by the referenced length
551  * value and will be updated with the length of the resulting name.  We
552  * always return a name that is null terminated, even if the merge_file
553  * name was not. */
554 static char *parse_merge_name(const char *merge_file, unsigned int *len_ptr,
555                               unsigned int prefix_skip)
556 {
557         static char buf[MAXPATHLEN];
558         char *fn, tmpbuf[MAXPATHLEN];
559         unsigned int fn_len;
560
561         if (!parent_dirscan && *merge_file != '/') {
562                 /* Return the name unchanged it doesn't have any slashes. */
563                 if (len_ptr) {
564                         const char *p = merge_file + *len_ptr;
565                         while (--p > merge_file && *p != '/') {}
566                         if (p == merge_file) {
567                                 strlcpy(buf, merge_file, *len_ptr + 1);
568                                 return buf;
569                         }
570                 } else if (strchr(merge_file, '/') == NULL)
571                         return (char *)merge_file;
572         }
573
574         fn = *merge_file == '/' ? buf : tmpbuf;
575         if (sanitize_paths) {
576                 const char *r = prefix_skip ? "/" : NULL;
577                 /* null-terminate the name if it isn't already */
578                 if (len_ptr && merge_file[*len_ptr]) {
579                         char *to = fn == buf ? tmpbuf : buf;
580                         strlcpy(to, merge_file, *len_ptr + 1);
581                         merge_file = to;
582                 }
583                 if (!sanitize_path(fn, merge_file, r, dirbuf_depth, SP_DEFAULT)) {
584                         rprintf(FERROR, "merge-file name overflows: %s\n",
585                                 merge_file);
586                         return NULL;
587                 }
588                 fn_len = strlen(fn);
589         } else {
590                 strlcpy(fn, merge_file, len_ptr ? *len_ptr + 1 : MAXPATHLEN);
591                 fn_len = clean_fname(fn, CFN_COLLAPSE_DOT_DOT_DIRS);
592         }
593
594         /* If the name isn't in buf yet, it wasn't absolute. */
595         if (fn != buf) {
596                 int d_len = dirbuf_len - prefix_skip;
597                 if (d_len + fn_len >= MAXPATHLEN) {
598                         rprintf(FERROR, "merge-file name overflows: %s\n", fn);
599                         return NULL;
600                 }
601                 memcpy(buf, dirbuf + prefix_skip, d_len);
602                 memcpy(buf + d_len, fn, fn_len + 1);
603                 fn_len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
604         }
605
606         if (len_ptr)
607                 *len_ptr = fn_len;
608         return buf;
609 }
610
611 /* Sets the dirbuf and dirbuf_len values. */
612 void set_filter_dir(const char *dir, unsigned int dirlen)
613 {
614         unsigned int len;
615         if (*dir != '/') {
616                 memcpy(dirbuf, curr_dir, curr_dir_len);
617                 dirbuf[curr_dir_len] = '/';
618                 len = curr_dir_len + 1;
619                 if (len + dirlen >= MAXPATHLEN)
620                         dirlen = 0;
621         } else
622                 len = 0;
623         memcpy(dirbuf + len, dir, dirlen);
624         dirbuf[dirlen + len] = '\0';
625         dirbuf_len = clean_fname(dirbuf, CFN_COLLAPSE_DOT_DOT_DIRS);
626         if (dirbuf_len > 1 && dirbuf[dirbuf_len-1] == '.'
627             && dirbuf[dirbuf_len-2] == '/')
628                 dirbuf_len -= 2;
629         if (dirbuf_len != 1)
630                 dirbuf[dirbuf_len++] = '/';
631         dirbuf[dirbuf_len] = '\0';
632         if (sanitize_paths)
633                 dirbuf_depth = count_dir_elements(dirbuf + module_dirlen);
634 }
635
636 /* This routine takes a per-dir merge-file entry and finishes its setup.
637  * If the name has a path portion then we check to see if it refers to a
638  * parent directory of the first transfer dir.  If it does, we scan all the
639  * dirs from that point through the parent dir of the transfer dir looking
640  * for the per-dir merge-file in each one. */
641 static BOOL setup_merge_file(int mergelist_num, filter_rule *ex,
642                              filter_rule_list *lp)
643 {
644         char buf[MAXPATHLEN];
645         char *x, *y, *pat = ex->pattern;
646         unsigned int len;
647
648         if (!(x = parse_merge_name(pat, NULL, 0)) || *x != '/')
649                 return 0;
650
651         if (DEBUG_GTE(FILTER, 2)) {
652                 rprintf(FINFO, "[%s] performing parent_dirscan for mergelist #%d%s\n",
653                         who_am_i(), mergelist_num, lp->debug_type);
654         }
655         y = strrchr(x, '/');
656         *y = '\0';
657         ex->pattern = strdup(y+1);
658         if (!*x)
659                 x = "/";
660         if (*x == '/')
661                 strlcpy(buf, x, MAXPATHLEN);
662         else
663                 pathjoin(buf, MAXPATHLEN, dirbuf, x);
664
665         len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
666         if (len != 1 && len < MAXPATHLEN-1) {
667                 buf[len++] = '/';
668                 buf[len] = '\0';
669         }
670         /* This ensures that the specified dir is a parent of the transfer. */
671         for (x = buf, y = dirbuf; *x && *x == *y; x++, y++) {}
672         if (*x)
673                 y += strlen(y); /* nope -- skip the scan */
674
675         parent_dirscan = True;
676         while (*y) {
677                 char save[MAXPATHLEN];
678                 strlcpy(save, y, MAXPATHLEN);
679                 *y = '\0';
680                 dirbuf_len = y - dirbuf;
681                 strlcpy(x, ex->pattern, MAXPATHLEN - (x - buf));
682                 parse_filter_file(lp, buf, ex, XFLG_ANCHORED2ABS);
683                 if (ex->rflags & FILTRULE_NO_INHERIT) {
684                         /* Free the undesired rules to clean up any per-dir
685                          * mergelists they defined.  Otherwise pop_local_filters
686                          * may crash trying to restore nonexistent state for
687                          * those mergelists. */
688                         free_filters(lp->head);
689                         lp->head = NULL;
690                 }
691                 lp->tail = NULL;
692                 strlcpy(y, save, MAXPATHLEN);
693                 while ((*x++ = *y++) != '/') {}
694         }
695         parent_dirscan = False;
696         if (DEBUG_GTE(FILTER, 2)) {
697                 rprintf(FINFO, "[%s] completed parent_dirscan for mergelist #%d%s\n",
698                         who_am_i(), mergelist_num, lp->debug_type);
699         }
700         free(pat);
701         return 1;
702 }
703
704 struct local_filter_state {
705         int mergelist_cnt;
706         filter_rule_list mergelists[1];
707 };
708
709 /* Each time rsync changes to a new directory it call this function to
710  * handle all the per-dir merge-files.  The "dir" value is the current path
711  * relative to curr_dir (which might not be null-terminated).  We copy it
712  * into dirbuf so that we can easily append a file name on the end. */
713 void *push_local_filters(const char *dir, unsigned int dirlen)
714 {
715         struct local_filter_state *push;
716         int i;
717
718         set_filter_dir(dir, dirlen);
719         if (DEBUG_GTE(FILTER, 2)) {
720                 rprintf(FINFO, "[%s] pushing local filters for %s\n",
721                         who_am_i(), dirbuf);
722         }
723
724         if (!mergelist_cnt) {
725                 /* No old state to save and no new merge files to push. */
726                 return NULL;
727         }
728
729         push = (struct local_filter_state *)new_array(char,
730                           sizeof (struct local_filter_state)
731                         + (mergelist_cnt-1) * sizeof (filter_rule_list));
732
733         push->mergelist_cnt = mergelist_cnt;
734         for (i = 0; i < mergelist_cnt; i++) {
735                 filter_rule *ex = mergelist_parents[i];
736                 if (!ex)
737                         continue;
738                 memcpy(&push->mergelists[i], ex->u.mergelist, sizeof (filter_rule_list));
739         }
740
741         /* Note: parse_filter_file() might increase mergelist_cnt, so keep
742          * this loop separate from the above loop. */
743         for (i = 0; i < mergelist_cnt; i++) {
744                 filter_rule *ex = mergelist_parents[i];
745                 filter_rule_list *lp;
746                 if (!ex)
747                         continue;
748                 lp = ex->u.mergelist;
749
750                 if (DEBUG_GTE(FILTER, 2)) {
751                         rprintf(FINFO, "[%s] pushing mergelist #%d%s\n",
752                                 who_am_i(), i, lp->debug_type);
753                 }
754
755                 lp->tail = NULL; /* Switch any local rules to inherited. */
756                 if (ex->rflags & FILTRULE_NO_INHERIT)
757                         lp->head = NULL;
758
759                 if (ex->rflags & FILTRULE_FINISH_SETUP) {
760                         ex->rflags &= ~FILTRULE_FINISH_SETUP;
761                         if (setup_merge_file(i, ex, lp))
762                                 set_filter_dir(dir, dirlen);
763                 }
764
765                 if (strlcpy(dirbuf + dirbuf_len, ex->pattern,
766                     MAXPATHLEN - dirbuf_len) < MAXPATHLEN - dirbuf_len) {
767                         parse_filter_file(lp, dirbuf, ex,
768                                           XFLG_ANCHORED2ABS);
769                 } else {
770                         io_error |= IOERR_GENERAL;
771                         rprintf(FERROR,
772                             "cannot add local filter rules in long-named directory: %s\n",
773                             full_fname(dirbuf));
774                 }
775                 dirbuf[dirbuf_len] = '\0';
776         }
777
778         return (void*)push;
779 }
780
781 void pop_local_filters(void *mem)
782 {
783         struct local_filter_state *pop = (struct local_filter_state *)mem;
784         int i;
785         int old_mergelist_cnt = pop ? pop->mergelist_cnt : 0;
786
787         if (DEBUG_GTE(FILTER, 2))
788                 rprintf(FINFO, "[%s] popping local filters\n", who_am_i());
789
790         for (i = mergelist_cnt; i-- > 0; ) {
791                 filter_rule *ex = mergelist_parents[i];
792                 filter_rule_list *lp;
793                 if (!ex)
794                         continue;
795                 lp = ex->u.mergelist;
796
797                 if (DEBUG_GTE(FILTER, 2)) {
798                         rprintf(FINFO, "[%s] popping mergelist #%d%s\n",
799                                 who_am_i(), i, lp->debug_type);
800                 }
801
802                 pop_filter_list(lp);
803                 if (i >= old_mergelist_cnt && lp->head) {
804                         /* This mergelist does not exist in the state to be restored, but it
805                          * still has inherited rules.  This can sometimes happen if a per-dir
806                          * merge file calls setup_merge_file() in push_local_filters() and that
807                          * leaves some inherited rules that aren't in the pushed list state. */
808                         if (DEBUG_GTE(FILTER, 2)) {
809                                 rprintf(FINFO, "[%s] freeing parent_dirscan filters of mergelist #%d%s\n",
810                                         who_am_i(), i, ex->u.mergelist->debug_type);
811                         }
812                         pop_filter_list(lp);
813                 }
814         }
815
816         if (!pop)
817                 return; /* No state to restore. */
818
819         for (i = 0; i < old_mergelist_cnt; i++) {
820                 filter_rule *ex = mergelist_parents[i];
821                 if (!ex)
822                         continue;
823                 memcpy(ex->u.mergelist, &pop->mergelists[i], sizeof (filter_rule_list));
824         }
825
826         free(pop);
827 }
828
829 void change_local_filter_dir(const char *dname, int dlen, int dir_depth)
830 {
831         static int cur_depth = -1;
832         static void *filt_array[MAXPATHLEN/2+1];
833
834         if (!dname) {
835                 for ( ; cur_depth >= 0; cur_depth--) {
836                         if (filt_array[cur_depth]) {
837                                 pop_local_filters(filt_array[cur_depth]);
838                                 filt_array[cur_depth] = NULL;
839                         }
840                 }
841                 return;
842         }
843
844         assert(dir_depth < MAXPATHLEN/2+1);
845
846         for ( ; cur_depth >= dir_depth; cur_depth--) {
847                 if (filt_array[cur_depth]) {
848                         pop_local_filters(filt_array[cur_depth]);
849                         filt_array[cur_depth] = NULL;
850                 }
851         }
852
853         cur_depth = dir_depth;
854         filt_array[cur_depth] = push_local_filters(dname, dlen);
855 }
856
857 static int rule_matches(const char *fname, filter_rule *ex, int name_flags)
858 {
859         int slash_handling, str_cnt = 0, anchored_match = 0;
860         int ret_match = ex->rflags & FILTRULE_NEGATE ? 0 : 1;
861         char *p, *pattern = ex->pattern;
862         const char *strings[16]; /* more than enough */
863         const char *name = fname + (*fname == '/');
864
865         if (!*name)
866                 return 0;
867
868         if (!(name_flags & NAME_IS_XATTR) ^ !(ex->rflags & FILTRULE_XATTR))
869                 return 0;
870
871         if (!ex->u.slash_cnt && !(ex->rflags & FILTRULE_WILD2)) {
872                 /* If the pattern does not have any slashes AND it does
873                  * not have a "**" (which could match a slash), then we
874                  * just match the name portion of the path. */
875                 if ((p = strrchr(name,'/')) != NULL)
876                         name = p+1;
877         } else if (ex->rflags & FILTRULE_ABS_PATH && *fname != '/'
878             && curr_dir_len > module_dirlen + 1) {
879                 /* If we're matching against an absolute-path pattern,
880                  * we need to prepend our full path info. */
881                 strings[str_cnt++] = curr_dir + module_dirlen + 1;
882                 strings[str_cnt++] = "/";
883         } else if (ex->rflags & FILTRULE_WILD2_PREFIX && *fname != '/') {
884                 /* Allow "**"+"/" to match at the start of the string. */
885                 strings[str_cnt++] = "/";
886         }
887         strings[str_cnt++] = name;
888         if (name_flags & NAME_IS_DIR) {
889                 /* Allow a trailing "/"+"***" to match the directory. */
890                 if (ex->rflags & FILTRULE_WILD3_SUFFIX)
891                         strings[str_cnt++] = "/";
892         } else if (ex->rflags & FILTRULE_DIRECTORY)
893                 return !ret_match;
894         strings[str_cnt] = NULL;
895
896         if (*pattern == '/') {
897                 anchored_match = 1;
898                 pattern++;
899         }
900
901         if (!anchored_match && ex->u.slash_cnt
902             && !(ex->rflags & FILTRULE_WILD2)) {
903                 /* A non-anchored match with an infix slash and no "**"
904                  * needs to match the last slash_cnt+1 name elements. */
905                 slash_handling = ex->u.slash_cnt + 1;
906         } else if (!anchored_match && !(ex->rflags & FILTRULE_WILD2_PREFIX)
907                                    && ex->rflags & FILTRULE_WILD2) {
908                 /* A non-anchored match with an infix or trailing "**" (but not
909                  * a prefixed "**") needs to try matching after every slash. */
910                 slash_handling = -1;
911         } else {
912                 /* The pattern matches only at the start of the path or name. */
913                 slash_handling = 0;
914         }
915
916         if (ex->rflags & FILTRULE_WILD) {
917                 if (wildmatch_array(pattern, strings, slash_handling))
918                         return ret_match;
919         } else if (str_cnt > 1) {
920                 if (litmatch_array(pattern, strings, slash_handling))
921                         return ret_match;
922         } else if (anchored_match) {
923                 if (strcmp(name, pattern) == 0)
924                         return ret_match;
925         } else {
926                 int l1 = strlen(name);
927                 int l2 = strlen(pattern);
928                 if (l2 <= l1 &&
929                     strcmp(name+(l1-l2),pattern) == 0 &&
930                     (l1==l2 || name[l1-(l2+1)] == '/')) {
931                         return ret_match;
932                 }
933         }
934
935         return !ret_match;
936 }
937
938 static void report_filter_result(enum logcode code, char const *name,
939                                  filter_rule const *ent,
940                                  int name_flags, const char *type)
941 {
942         int log_level = am_sender || am_generator ? 1 : 3;
943
944         /* If a trailing slash is present to match only directories,
945          * then it is stripped out by add_rule().  So as a special
946          * case we add it back in the log output. */
947         if (DEBUG_GTE(FILTER, log_level)) {
948                 static char *actions[2][2]
949                     = { {"show", "hid"}, {"risk", "protect"} };
950                 const char *w = who_am_i();
951                 const char *t = name_flags & NAME_IS_XATTR ? "xattr"
952                               : name_flags & NAME_IS_DIR ? "directory"
953                               : "file";
954                 rprintf(code, "[%s] %sing %s %s because of pattern %s%s%s\n",
955                     w, actions[*w=='g'][!(ent->rflags & FILTRULE_INCLUDE)],
956                     t, name, ent->pattern,
957                     ent->rflags & FILTRULE_DIRECTORY ? "/" : "", type);
958         }
959 }
960
961 /* This function is used to check if a file should be included/excluded
962  * from the list of files based on its name and type etc.  The value of
963  * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
964 int name_is_excluded(const char *fname, int name_flags, int filter_level)
965 {
966         if (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, name_flags) < 0) {
967                 if (!(name_flags & NAME_IS_XATTR))
968                         errno = ENOENT;
969                 return 1;
970         }
971
972         if (filter_level != ALL_FILTERS)
973                 return 0;
974
975         if (filter_list.head && check_filter(&filter_list, FINFO, fname, name_flags) < 0)
976                 return 1;
977
978         return 0;
979 }
980
981 /* Return -1 if file "name" is defined to be excluded by the specified
982  * exclude list, 1 if it is included, and 0 if it was not matched. */
983 int check_filter(filter_rule_list *listp, enum logcode code,
984                  const char *name, int name_flags)
985 {
986         filter_rule *ent;
987
988         for (ent = listp->head; ent; ent = ent->next) {
989                 if (ignore_perishable && ent->rflags & FILTRULE_PERISHABLE)
990                         continue;
991                 if (ent->rflags & FILTRULE_PERDIR_MERGE) {
992                         int rc = check_filter(ent->u.mergelist, code, name, name_flags);
993                         if (rc)
994                                 return rc;
995                         continue;
996                 }
997                 if (ent->rflags & FILTRULE_CVS_IGNORE) {
998                         int rc = check_filter(&cvs_filter_list, code, name, name_flags);
999                         if (rc)
1000                                 return rc;
1001                         continue;
1002                 }
1003                 if (rule_matches(name, ent, name_flags)) {
1004                         report_filter_result(code, name, ent, name_flags, listp->debug_type);
1005                         return ent->rflags & FILTRULE_INCLUDE ? 1 : -1;
1006                 }
1007         }
1008
1009         return 0;
1010 }
1011
1012 #define RULE_STRCMP(s,r) rule_strcmp((s), (r), sizeof (r) - 1)
1013
1014 static const uchar *rule_strcmp(const uchar *str, const char *rule, int rule_len)
1015 {
1016         if (strncmp((char*)str, rule, rule_len) != 0)
1017                 return NULL;
1018         if (isspace(str[rule_len]) || str[rule_len] == '_' || !str[rule_len])
1019                 return str + rule_len - 1;
1020         if (str[rule_len] == ',')
1021                 return str + rule_len;
1022         return NULL;
1023 }
1024
1025 #define FILTRULES_FROM_CONTAINER (FILTRULE_ABS_PATH | FILTRULE_INCLUDE \
1026                                 | FILTRULE_DIRECTORY | FILTRULE_NEGATE \
1027                                 | FILTRULE_PERISHABLE)
1028
1029 /* Gets the next include/exclude rule from *rulestr_ptr and advances
1030  * *rulestr_ptr to point beyond it.  Stores the pattern's start (within
1031  * *rulestr_ptr) and length in *pat_ptr and *pat_len_ptr, and returns a newly
1032  * allocated filter_rule containing the rest of the information.  Returns
1033  * NULL if there are no more rules in the input.
1034  *
1035  * The template provides defaults for the new rule to inherit, and the
1036  * template rflags and the xflags additionally affect parsing. */
1037 static filter_rule *parse_rule_tok(const char **rulestr_ptr,
1038                                    const filter_rule *template, int xflags,
1039                                    const char **pat_ptr, unsigned int *pat_len_ptr)
1040 {
1041         const uchar *s = (const uchar *)*rulestr_ptr;
1042         filter_rule *rule;
1043         unsigned int len;
1044
1045         if (template->rflags & FILTRULE_WORD_SPLIT) {
1046                 /* Skip over any initial whitespace. */
1047                 while (isspace(*s))
1048                         s++;
1049                 /* Update to point to real start of rule. */
1050                 *rulestr_ptr = (const char *)s;
1051         }
1052         if (!*s)
1053                 return NULL;
1054
1055         rule = new0(filter_rule);
1056
1057         /* Inherit from the template.  Don't inherit FILTRULES_SIDES; we check
1058          * that later. */
1059         rule->rflags = template->rflags & FILTRULES_FROM_CONTAINER;
1060
1061         /* Figure out what kind of a filter rule "s" is pointing at.  Note
1062          * that if FILTRULE_NO_PREFIXES is set, the rule is either an include
1063          * or an exclude based on the inheritance of the FILTRULE_INCLUDE
1064          * flag (above).  XFLG_OLD_PREFIXES indicates a compatibility mode
1065          * for old include/exclude patterns where just "+ " and "- " are
1066          * allowed as optional prefixes.  */
1067         if (template->rflags & FILTRULE_NO_PREFIXES) {
1068                 if (*s == '!' && template->rflags & FILTRULE_CVS_IGNORE)
1069                         rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
1070         } else if (xflags & XFLG_OLD_PREFIXES) {
1071                 if (*s == '-' && s[1] == ' ') {
1072                         rule->rflags &= ~FILTRULE_INCLUDE;
1073                         s += 2;
1074                 } else if (*s == '+' && s[1] == ' ') {
1075                         rule->rflags |= FILTRULE_INCLUDE;
1076                         s += 2;
1077                 } else if (*s == '!')
1078                         rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
1079         } else {
1080                 char ch = 0;
1081                 BOOL prefix_specifies_side = False;
1082                 switch (*s) {
1083                 case 'c':
1084                         if ((s = RULE_STRCMP(s, "clear")) != NULL)
1085                                 ch = '!';
1086                         break;
1087                 case 'd':
1088                         if ((s = RULE_STRCMP(s, "dir-merge")) != NULL)
1089                                 ch = ':';
1090                         break;
1091                 case 'e':
1092                         if ((s = RULE_STRCMP(s, "exclude")) != NULL)
1093                                 ch = '-';
1094                         break;
1095                 case 'h':
1096                         if ((s = RULE_STRCMP(s, "hide")) != NULL)
1097                                 ch = 'H';
1098                         break;
1099                 case 'i':
1100                         if ((s = RULE_STRCMP(s, "include")) != NULL)
1101                                 ch = '+';
1102                         break;
1103                 case 'm':
1104                         if ((s = RULE_STRCMP(s, "merge")) != NULL)
1105                                 ch = '.';
1106                         break;
1107                 case 'p':
1108                         if ((s = RULE_STRCMP(s, "protect")) != NULL)
1109                                 ch = 'P';
1110                         break;
1111                 case 'r':
1112                         if ((s = RULE_STRCMP(s, "risk")) != NULL)
1113                                 ch = 'R';
1114                         break;
1115                 case 's':
1116                         if ((s = RULE_STRCMP(s, "show")) != NULL)
1117                                 ch = 'S';
1118                         break;
1119                 default:
1120                         ch = *s;
1121                         if (s[1] == ',')
1122                                 s++;
1123                         break;
1124                 }
1125                 switch (ch) {
1126                 case ':':
1127                         trust_sender_filter = 1;
1128                         rule->rflags |= FILTRULE_PERDIR_MERGE
1129                                       | FILTRULE_FINISH_SETUP;
1130                         /* FALL THROUGH */
1131                 case '.':
1132                         rule->rflags |= FILTRULE_MERGE_FILE;
1133                         break;
1134                 case '+':
1135                         rule->rflags |= FILTRULE_INCLUDE;
1136                         break;
1137                 case '-':
1138                         break;
1139                 case 'S':
1140                         rule->rflags |= FILTRULE_INCLUDE;
1141                         /* FALL THROUGH */
1142                 case 'H':
1143                         rule->rflags |= FILTRULE_SENDER_SIDE;
1144                         prefix_specifies_side = True;
1145                         break;
1146                 case 'R':
1147                         rule->rflags |= FILTRULE_INCLUDE;
1148                         /* FALL THROUGH */
1149                 case 'P':
1150                         rule->rflags |= FILTRULE_RECEIVER_SIDE;
1151                         prefix_specifies_side = True;
1152                         break;
1153                 case '!':
1154                         rule->rflags |= FILTRULE_CLEAR_LIST;
1155                         break;
1156                 default:
1157                         rprintf(FERROR, "Unknown filter rule: `%s'\n", *rulestr_ptr);
1158                         exit_cleanup(RERR_SYNTAX);
1159                 }
1160                 while (ch != '!' && *++s && *s != ' ' && *s != '_') {
1161                         if (template->rflags & FILTRULE_WORD_SPLIT && isspace(*s)) {
1162                                 s--;
1163                                 break;
1164                         }
1165                         switch (*s) {
1166                         default:
1167                             invalid:
1168                                 rprintf(FERROR,
1169                                         "invalid modifier '%c' at position %d in filter rule: %s\n",
1170                                         *s, (int)(s - (const uchar *)*rulestr_ptr), *rulestr_ptr);
1171                                 exit_cleanup(RERR_SYNTAX);
1172                         case '-':
1173                                 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
1174                                         goto invalid;
1175                                 rule->rflags |= FILTRULE_NO_PREFIXES;
1176                                 break;
1177                         case '+':
1178                                 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
1179                                         goto invalid;
1180                                 rule->rflags |= FILTRULE_NO_PREFIXES
1181                                               | FILTRULE_INCLUDE;
1182                                 break;
1183                         case '/':
1184                                 rule->rflags |= FILTRULE_ABS_PATH;
1185                                 break;
1186                         case '!':
1187                                 /* Negation really goes with the pattern, so it
1188                                  * isn't useful as a merge-file default. */
1189                                 if (rule->rflags & FILTRULE_MERGE_FILE)
1190                                         goto invalid;
1191                                 rule->rflags |= FILTRULE_NEGATE;
1192                                 break;
1193                         case 'C':
1194                                 if (rule->rflags & FILTRULE_NO_PREFIXES || prefix_specifies_side)
1195                                         goto invalid;
1196                                 rule->rflags |= FILTRULE_NO_PREFIXES
1197                                               | FILTRULE_WORD_SPLIT
1198                                               | FILTRULE_NO_INHERIT
1199                                               | FILTRULE_CVS_IGNORE;
1200                                 break;
1201                         case 'e':
1202                                 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1203                                         goto invalid;
1204                                 rule->rflags |= FILTRULE_EXCLUDE_SELF;
1205                                 break;
1206                         case 'n':
1207                                 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1208                                         goto invalid;
1209                                 rule->rflags |= FILTRULE_NO_INHERIT;
1210                                 break;
1211                         case 'p':
1212                                 rule->rflags |= FILTRULE_PERISHABLE;
1213                                 break;
1214                         case 'r':
1215                                 if (prefix_specifies_side)
1216                                         goto invalid;
1217                                 rule->rflags |= FILTRULE_RECEIVER_SIDE;
1218                                 break;
1219                         case 's':
1220                                 if (prefix_specifies_side)
1221                                         goto invalid;
1222                                 rule->rflags |= FILTRULE_SENDER_SIDE;
1223                                 break;
1224                         case 'w':
1225                                 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1226                                         goto invalid;
1227                                 rule->rflags |= FILTRULE_WORD_SPLIT;
1228                                 break;
1229                         case 'x':
1230                                 rule->rflags |= FILTRULE_XATTR;
1231                                 saw_xattr_filter = 1;
1232                                 break;
1233                         }
1234                 }
1235                 if (*s)
1236                         s++;
1237         }
1238         if (template->rflags & FILTRULES_SIDES) {
1239                 if (rule->rflags & FILTRULES_SIDES) {
1240                         /* The filter and template both specify side(s).  This
1241                          * is dodgy (and won't work correctly if the template is
1242                          * a one-sided per-dir merge rule), so reject it. */
1243                         rprintf(FERROR,
1244                                 "specified-side merge file contains specified-side filter: %s\n",
1245                                 *rulestr_ptr);
1246                         exit_cleanup(RERR_SYNTAX);
1247                 }
1248                 rule->rflags |= template->rflags & FILTRULES_SIDES;
1249         }
1250
1251         if (template->rflags & FILTRULE_WORD_SPLIT) {
1252                 const uchar *cp = s;
1253                 /* Token ends at whitespace or the end of the string. */
1254                 while (!isspace(*cp) && *cp != '\0')
1255                         cp++;
1256                 len = cp - s;
1257         } else
1258                 len = strlen((char*)s);
1259
1260         if (rule->rflags & FILTRULE_CLEAR_LIST) {
1261                 if (!(rule->rflags & FILTRULE_NO_PREFIXES)
1262                  && !(xflags & XFLG_OLD_PREFIXES) && len) {
1263                         rprintf(FERROR,
1264                                 "'!' rule has trailing characters: %s\n", *rulestr_ptr);
1265                         exit_cleanup(RERR_SYNTAX);
1266                 }
1267                 if (len > 1)
1268                         rule->rflags &= ~FILTRULE_CLEAR_LIST;
1269         } else if (!len && !(rule->rflags & FILTRULE_CVS_IGNORE)) {
1270                 rprintf(FERROR, "unexpected end of filter rule: %s\n", *rulestr_ptr);
1271                 exit_cleanup(RERR_SYNTAX);
1272         }
1273
1274         /* --delete-excluded turns an un-modified include/exclude into a sender-side rule.  */
1275         if (delete_excluded
1276          && !(rule->rflags & (FILTRULES_SIDES|FILTRULE_MERGE_FILE|FILTRULE_PERDIR_MERGE)))
1277                 rule->rflags |= FILTRULE_SENDER_SIDE;
1278
1279         *pat_ptr = (const char *)s;
1280         *pat_len_ptr = len;
1281         *rulestr_ptr = *pat_ptr + len;
1282         return rule;
1283 }
1284
1285 static void get_cvs_excludes(uint32 rflags)
1286 {
1287         static int initialized = 0;
1288         char *p, fname[MAXPATHLEN];
1289
1290         if (initialized)
1291                 return;
1292         initialized = 1;
1293
1294         parse_filter_str(&cvs_filter_list, default_cvsignore(),
1295                          rule_template(rflags | (protocol_version >= 30 ? FILTRULE_PERISHABLE : 0)),
1296                          0);
1297
1298         p = module_id >= 0 && lp_use_chroot(module_id) ? "/" : getenv("HOME");
1299         if (p && pathjoin(fname, MAXPATHLEN, p, ".cvsignore") < MAXPATHLEN)
1300                 parse_filter_file(&cvs_filter_list, fname, rule_template(rflags), 0);
1301
1302         parse_filter_str(&cvs_filter_list, getenv("CVSIGNORE"), rule_template(rflags), 0);
1303 }
1304
1305 const filter_rule *rule_template(uint32 rflags)
1306 {
1307         static filter_rule template; /* zero-initialized */
1308         template.rflags = rflags;
1309         return &template;
1310 }
1311
1312 void parse_filter_str(filter_rule_list *listp, const char *rulestr,
1313                      const filter_rule *template, int xflags)
1314 {
1315         filter_rule *rule;
1316         const char *pat;
1317         unsigned int pat_len;
1318
1319         if (!rulestr)
1320                 return;
1321
1322         while (1) {
1323                 uint32 new_rflags;
1324
1325                 /* Remember that the returned string is NOT '\0' terminated! */
1326                 if (!(rule = parse_rule_tok(&rulestr, template, xflags, &pat, &pat_len)))
1327                         break;
1328
1329                 if (pat_len >= MAXPATHLEN) {
1330                         rprintf(FERROR, "discarding over-long filter: %.*s\n",
1331                                 (int)pat_len, pat);
1332                     free_continue:
1333                         free_filter(rule);
1334                         continue;
1335                 }
1336
1337                 new_rflags = rule->rflags;
1338                 if (new_rflags & FILTRULE_CLEAR_LIST) {
1339                         if (DEBUG_GTE(FILTER, 2)) {
1340                                 rprintf(FINFO,
1341                                         "[%s] clearing filter list%s\n",
1342                                         who_am_i(), listp->debug_type);
1343                         }
1344                         pop_filter_list(listp);
1345                         listp->head = NULL;
1346                         goto free_continue;
1347                 }
1348
1349                 if (new_rflags & FILTRULE_MERGE_FILE) {
1350                         if (!pat_len) {
1351                                 pat = ".cvsignore";
1352                                 pat_len = 10;
1353                         }
1354                         if (new_rflags & FILTRULE_EXCLUDE_SELF) {
1355                                 const char *name;
1356                                 filter_rule *excl_self;
1357
1358                                 excl_self = new0(filter_rule);
1359                                 /* Find the beginning of the basename and add an exclude for it. */
1360                                 for (name = pat + pat_len; name > pat && name[-1] != '/'; name--) {}
1361                                 add_rule(listp, name, (pat + pat_len) - name, excl_self, 0);
1362                                 rule->rflags &= ~FILTRULE_EXCLUDE_SELF;
1363                         }
1364                         if (new_rflags & FILTRULE_PERDIR_MERGE) {
1365                                 if (parent_dirscan) {
1366                                         const char *p;
1367                                         unsigned int len = pat_len;
1368                                         if ((p = parse_merge_name(pat, &len, module_dirlen)))
1369                                                 add_rule(listp, p, len, rule, 0);
1370                                         else
1371                                                 free_filter(rule);
1372                                         continue;
1373                                 }
1374                         } else {
1375                                 const char *p;
1376                                 unsigned int len = pat_len;
1377                                 if ((p = parse_merge_name(pat, &len, 0)))
1378                                         parse_filter_file(listp, p, rule, XFLG_FATAL_ERRORS);
1379                                 free_filter(rule);
1380                                 continue;
1381                         }
1382                 }
1383
1384                 add_rule(listp, pat, pat_len, rule, xflags);
1385
1386                 if (new_rflags & FILTRULE_CVS_IGNORE
1387                     && !(new_rflags & FILTRULE_MERGE_FILE))
1388                         get_cvs_excludes(new_rflags);
1389         }
1390 }
1391
1392 void parse_filter_file(filter_rule_list *listp, const char *fname, const filter_rule *template, int xflags)
1393 {
1394         FILE *fp;
1395         char line[BIGPATHBUFLEN];
1396         char *eob = line + sizeof line - 1;
1397         BOOL word_split = (template->rflags & FILTRULE_WORD_SPLIT) != 0;
1398
1399         if (!fname || !*fname)
1400                 return;
1401
1402         if (*fname != '-' || fname[1] || am_server) {
1403                 if (daemon_filter_list.head) {
1404                         strlcpy(line, fname, sizeof line);
1405                         clean_fname(line, CFN_COLLAPSE_DOT_DOT_DIRS);
1406                         if (check_filter(&daemon_filter_list, FLOG, line, 0) < 0)
1407                                 fp = NULL;
1408                         else
1409                                 fp = fopen(line, "rb");
1410                 } else
1411                         fp = fopen(fname, "rb");
1412         } else
1413                 fp = stdin;
1414
1415         if (DEBUG_GTE(FILTER, 2)) {
1416                 rprintf(FINFO, "[%s] parse_filter_file(%s,%x,%x)%s\n",
1417                         who_am_i(), fname, template->rflags, xflags,
1418                         fp ? "" : " [not found]");
1419         }
1420
1421         if (!fp) {
1422                 if (xflags & XFLG_FATAL_ERRORS) {
1423                         rsyserr(FERROR, errno,
1424                                 "failed to open %sclude file %s",
1425                                 template->rflags & FILTRULE_INCLUDE ? "in" : "ex",
1426                                 fname);
1427                         exit_cleanup(RERR_FILEIO);
1428                 }
1429                 return;
1430         }
1431         dirbuf[dirbuf_len] = '\0';
1432
1433         while (1) {
1434                 char *s = line;
1435                 int ch, overflow = 0;
1436                 while (1) {
1437                         if ((ch = getc(fp)) == EOF) {
1438                                 if (ferror(fp) && errno == EINTR) {
1439                                         clearerr(fp);
1440                                         continue;
1441                                 }
1442                                 break;
1443                         }
1444                         if (word_split && isspace(ch))
1445                                 break;
1446                         if (eol_nulls? !ch : (ch == '\n' || ch == '\r'))
1447                                 break;
1448                         if (s < eob)
1449                                 *s++ = ch;
1450                         else
1451                                 overflow = 1;
1452                 }
1453                 if (overflow) {
1454                         rprintf(FERROR, "discarding over-long filter: %s...\n", line);
1455                         s = line;
1456                 }
1457                 *s = '\0';
1458                 /* Skip an empty token and (when line parsing) comments. */
1459                 if (*line && (word_split || (*line != ';' && *line != '#')))
1460                         parse_filter_str(listp, line, template, xflags);
1461                 if (ch == EOF)
1462                         break;
1463         }
1464         fclose(fp);
1465 }
1466
1467 /* If the "for_xfer" flag is set, the prefix is made compatible with the
1468  * current protocol_version (if possible) or a NULL is returned (if not
1469  * possible). */
1470 char *get_rule_prefix(filter_rule *rule, const char *pat, int for_xfer,
1471                       unsigned int *plen_ptr)
1472 {
1473         static char buf[MAX_RULE_PREFIX+1];
1474         char *op = buf;
1475         int legal_len = for_xfer && protocol_version < 29 ? 1 : MAX_RULE_PREFIX-1;
1476
1477         if (rule->rflags & FILTRULE_PERDIR_MERGE) {
1478                 if (legal_len == 1)
1479                         return NULL;
1480                 *op++ = ':';
1481         } else if (rule->rflags & FILTRULE_INCLUDE)
1482                 *op++ = '+';
1483         else if (legal_len != 1
1484             || ((*pat == '-' || *pat == '+') && pat[1] == ' '))
1485                 *op++ = '-';
1486         else
1487                 legal_len = 0;
1488
1489         if (rule->rflags & FILTRULE_ABS_PATH)
1490                 *op++ = '/';
1491         if (rule->rflags & FILTRULE_NEGATE)
1492                 *op++ = '!';
1493         if (rule->rflags & FILTRULE_CVS_IGNORE)
1494                 *op++ = 'C';
1495         else {
1496                 if (rule->rflags & FILTRULE_NO_INHERIT)
1497                         *op++ = 'n';
1498                 if (rule->rflags & FILTRULE_WORD_SPLIT)
1499                         *op++ = 'w';
1500                 if (rule->rflags & FILTRULE_NO_PREFIXES) {
1501                         if (rule->rflags & FILTRULE_INCLUDE)
1502                                 *op++ = '+';
1503                         else
1504                                 *op++ = '-';
1505                 }
1506         }
1507         if (rule->rflags & FILTRULE_EXCLUDE_SELF)
1508                 *op++ = 'e';
1509         if (rule->rflags & FILTRULE_XATTR)
1510                 *op++ = 'x';
1511         if (rule->rflags & FILTRULE_SENDER_SIDE
1512             && (!for_xfer || protocol_version >= 29))
1513                 *op++ = 's';
1514         if (rule->rflags & FILTRULE_RECEIVER_SIDE
1515             && (!for_xfer || protocol_version >= 29
1516              || (delete_excluded && am_sender)))
1517                 *op++ = 'r';
1518         if (rule->rflags & FILTRULE_PERISHABLE) {
1519                 if (!for_xfer || protocol_version >= 30)
1520                         *op++ = 'p';
1521                 else if (am_sender)
1522                         return NULL;
1523         }
1524         if (op - buf > legal_len)
1525                 return NULL;
1526         if (legal_len)
1527                 *op++ = ' ';
1528         *op = '\0';
1529         if (plen_ptr)
1530                 *plen_ptr = op - buf;
1531         return buf;
1532 }
1533
1534 static void send_rules(int f_out, filter_rule_list *flp)
1535 {
1536         filter_rule *ent, *prev = NULL;
1537
1538         for (ent = flp->head; ent; ent = ent->next) {
1539                 unsigned int len, plen, dlen;
1540                 int elide = 0;
1541                 char *p;
1542
1543                 /* Note we need to check delete_excluded here in addition to
1544                  * the code in parse_rule_tok() because some rules may have
1545                  * been added before we found the --delete-excluded option.
1546                  * We must also elide any CVS merge-file rules to avoid a
1547                  * backward compatibility problem, and we elide any no-prefix
1548                  * merge files as an optimization (since they can only have
1549                  * include/exclude rules). */
1550                 if (ent->rflags & FILTRULE_SENDER_SIDE)
1551                         elide = am_sender ? 1 : -1;
1552                 if (ent->rflags & FILTRULE_RECEIVER_SIDE)
1553                         elide = elide ? 0 : am_sender ? -1 : 1;
1554                 else if (delete_excluded && !elide
1555                  && (!(ent->rflags & FILTRULE_PERDIR_MERGE)
1556                   || ent->rflags & FILTRULE_NO_PREFIXES))
1557                         elide = am_sender ? 1 : -1;
1558                 if (elide < 0) {
1559                         if (prev)
1560                                 prev->next = ent->next;
1561                         else
1562                                 flp->head = ent->next;
1563                 } else
1564                         prev = ent;
1565                 if (elide > 0)
1566                         continue;
1567                 if (ent->rflags & FILTRULE_CVS_IGNORE
1568                     && !(ent->rflags & FILTRULE_MERGE_FILE)) {
1569                         int f = am_sender || protocol_version < 29 ? f_out : -2;
1570                         send_rules(f, &cvs_filter_list);
1571                         if (f == f_out)
1572                                 continue;
1573                 }
1574                 p = get_rule_prefix(ent, ent->pattern, 1, &plen);
1575                 if (!p) {
1576                         rprintf(FERROR,
1577                                 "filter rules are too modern for remote rsync.\n");
1578                         exit_cleanup(RERR_PROTOCOL);
1579                 }
1580                 if (f_out < 0)
1581                         continue;
1582                 len = strlen(ent->pattern);
1583                 dlen = ent->rflags & FILTRULE_DIRECTORY ? 1 : 0;
1584                 if (!(plen + len + dlen))
1585                         continue;
1586                 write_int(f_out, plen + len + dlen);
1587                 if (plen)
1588                         write_buf(f_out, p, plen);
1589                 write_buf(f_out, ent->pattern, len);
1590                 if (dlen)
1591                         write_byte(f_out, '/');
1592         }
1593         flp->tail = prev;
1594 }
1595
1596 /* This is only called by the client. */
1597 void send_filter_list(int f_out)
1598 {
1599         int receiver_wants_list = prune_empty_dirs
1600             || (delete_mode && (!delete_excluded || protocol_version >= 29));
1601
1602         if (local_server || (am_sender && !receiver_wants_list))
1603                 f_out = -1;
1604         if (cvs_exclude && am_sender) {
1605                 if (protocol_version >= 29)
1606                         parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1607                 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1608         }
1609
1610         send_rules(f_out, &filter_list);
1611
1612         if (f_out >= 0)
1613                 write_int(f_out, 0);
1614
1615         if (cvs_exclude) {
1616                 if (!am_sender || protocol_version < 29)
1617                         parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1618                 if (!am_sender)
1619                         parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1620         }
1621 }
1622
1623 /* This is only called by the server. */
1624 void recv_filter_list(int f_in)
1625 {
1626         char line[BIGPATHBUFLEN];
1627         int xflags = protocol_version >= 29 ? 0 : XFLG_OLD_PREFIXES;
1628         int receiver_wants_list = prune_empty_dirs
1629             || (delete_mode && (!delete_excluded || protocol_version >= 29));
1630         unsigned int len;
1631
1632         if (!local_server && (am_sender || receiver_wants_list)) {
1633                 while ((len = read_int(f_in)) != 0) {
1634                         if (len >= sizeof line)
1635                                 overflow_exit("recv_rules");
1636                         read_sbuf(f_in, line, len);
1637                         parse_filter_str(&filter_list, line, rule_template(0), xflags);
1638                 }
1639         }
1640
1641         if (cvs_exclude) {
1642                 if (local_server || am_sender || protocol_version < 29)
1643                         parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1644                 if (local_server || am_sender)
1645                         parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1646         }
1647
1648         if (local_server) /* filter out any rules that aren't for us. */
1649                 send_rules(-1, &filter_list);
1650 }