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