Add safety check for local --remove-source-files.
[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                 if (partial_string_len)
365                         add_implied_include("", 0);
366                 free(partial_string_buf);
367                 partial_string_buf = NULL;
368         }
369         partial_string_len = 0; /* paranoia */
370 }
371
372 /* Each arg the client sends to the remote sender turns into an implied include
373  * that the receiver uses to validate the file list from the sender. */
374 void add_implied_include(const char *arg, int skip_daemon_module)
375 {
376         int arg_len, saw_wild = 0, saw_live_open_brkt = 0, backslash_cnt = 0;
377         int slash_cnt = 0;
378         const char *cp;
379         char *p;
380         if (trust_sender_args)
381                 return;
382         if (partial_string_len) {
383                 arg_len = strlen(arg);
384                 if (partial_string_len + arg_len >= MAXPATHLEN) {
385                         partial_string_len = 0;
386                         return; /* Should be impossible... */
387                 }
388                 memcpy(partial_string_buf + partial_string_len, arg, arg_len + 1);
389                 partial_string_len = 0;
390                 arg = partial_string_buf;
391         }
392         if (skip_daemon_module) {
393                 if ((cp = strchr(arg, '/')) != NULL)
394                         arg = cp + 1;
395                 else
396                         arg = "";
397         }
398         if (relative_paths) {
399                 if ((cp = strstr(arg, "/./")) != NULL)
400                         arg = cp + 3;
401         } else if ((cp = strrchr(arg, '/')) != NULL) {
402                 arg = cp + 1;
403         }
404         if (*arg == '.' && arg[1] == '\0')
405                 arg++;
406         arg_len = strlen(arg);
407         if (arg_len) {
408                 char *new_pat;
409                 if (strpbrk(arg, "*[?")) {
410                         /* We need to add room to escape backslashes if wildcard chars are present. */
411                         for (cp = arg; (cp = strchr(cp, '\\')) != NULL; cp++)
412                                 arg_len++;
413                         saw_wild = 1;
414                 }
415                 arg_len++; /* Leave room for the prefixed slash */
416                 p = new_pat = new_array(char, arg_len + 1);
417                 *p++ = '/';
418                 slash_cnt++;
419                 for (cp = arg; *cp; ) {
420                         switch (*cp) {
421                           case '\\':
422                                 if (cp[1] == ']') {
423                                         if (!saw_wild)
424                                                 cp++; /* A \] in a non-wild filter causes a problem, so drop the \ . */
425                                 } else if (!strchr("*[?", cp[1])) {
426                                         backslash_cnt++;
427                                         if (saw_wild)
428                                                 *p++ = '\\';
429                                 }
430                                 *p++ = *cp++;
431                                 break;
432                           case '/':
433                                 if (p[-1] == '/') { /* This is safe because of the initial slash. */
434                                         if (*++cp == '\0') {
435                                                 slash_cnt--;
436                                                 p--;
437                                         }
438                                 } else if (cp[1] == '\0') {
439                                         cp++;
440                                 } else {
441                                         slash_cnt++;
442                                         *p++ = *cp++;
443                                 }
444                                 break;
445                           case '.':
446                                 if (p[-1] == '/') {
447                                         if (cp[1] == '/') {
448                                                 cp += 2;
449                                                 if (!*cp) {
450                                                         slash_cnt--;
451                                                         p--;
452                                                 }
453                                         } else if (cp[1] == '\0') {
454                                                 cp++;
455                                                 slash_cnt--;
456                                                 p--;
457                                                 break;
458                                         }
459                                 } else
460                                         *p++ = *cp++;
461                                 break;
462                           case '[':
463                                 saw_live_open_brkt = 1;
464                                 *p++ = *cp++;
465                                 break;
466                           default:
467                                 *p++ = *cp++;
468                                 break;
469                         }
470                 }
471                 *p = '\0';
472                 arg_len = p - new_pat;
473                 if (!arg_len)
474                         free(new_pat);
475                 else {
476                         filter_rule *rule = new0(filter_rule);
477                         rule->rflags = FILTRULE_INCLUDE + (saw_wild ? FILTRULE_WILD : 0);
478                         rule->u.slash_cnt = slash_cnt;
479                         arg = rule->pattern = new_pat;
480                         if (!implied_filter_list.head)
481                                 implied_filter_list.head = implied_filter_list.tail = rule;
482                         else {
483                                 rule->next = implied_filter_list.head;
484                                 implied_filter_list.head = rule;
485                         }
486                         if (DEBUG_GTE(FILTER, 3))
487                                 rprintf(FINFO, "[%s] add_IMPlied_include(%s)\n", who_am_i(), arg);
488                         if (saw_live_open_brkt)
489                                 maybe_add_literal_brackets_rule(rule, arg_len);
490                         if (relative_paths && slash_cnt) {
491                                 filter_rule const *ent;
492                                 int found = 0;
493                                 slash_cnt = 1;
494                                 for (p = new_pat + 1; (p = strchr(p, '/')) != NULL; p++) {
495                                         *p = '\0';
496                                         for (ent = implied_filter_list.head; ent; ent = ent->next) {
497                                                 if (ent != rule && strcmp(ent->pattern, new_pat) == 0) {
498                                                         found = 1;
499                                                         break;
500                                                 }
501                                         }
502                                         if (!found) {
503                                                 filter_rule *R_rule = new0(filter_rule);
504                                                 R_rule->rflags = FILTRULE_INCLUDE | FILTRULE_DIRECTORY;
505                                                 /* Check if our sub-path has wildcards or escaped backslashes */
506                                                 if (saw_wild && strpbrk(rule->pattern, "*[?\\"))
507                                                         R_rule->rflags |= FILTRULE_WILD;
508                                                 R_rule->pattern = strdup(new_pat);
509                                                 R_rule->u.slash_cnt = slash_cnt;
510                                                 R_rule->next = implied_filter_list.head;
511                                                 implied_filter_list.head = R_rule;
512                                                 if (DEBUG_GTE(FILTER, 3)) {
513                                                         rprintf(FINFO, "[%s] add_implied_include(%s/)\n",
514                                                                 who_am_i(), R_rule->pattern);
515                                                 }
516                                                 if (saw_live_open_brkt)
517                                                         maybe_add_literal_brackets_rule(R_rule, -1);
518                                         }
519                                         *p = '/';
520                                         slash_cnt++;
521                                 }
522                         }
523                 }
524         }
525
526         if (recurse || xfer_dirs) {
527                 /* Now create a rule with an added "/" & "**" or "*" at the end */
528                 filter_rule *rule = new0(filter_rule);
529                 rule->rflags = FILTRULE_INCLUDE | FILTRULE_WILD;
530                 if (recurse)
531                         rule->rflags |= FILTRULE_WILD2;
532                 /* We must leave enough room for / * * \0. */
533                 if (!saw_wild && backslash_cnt) {
534                         /* We are appending a wildcard, so now the backslashes need to be escaped. */
535                         p = rule->pattern = new_array(char, arg_len + backslash_cnt + 3 + 1);
536                         for (cp = arg; *cp; ) { /* Note that arg_len != 0 because backslash_cnt > 0 */
537                                 if (*cp == '\\')
538                                         *p++ = '\\';
539                                 *p++ = *cp++;
540                         }
541                 } else {
542                         p = rule->pattern = new_array(char, arg_len + 3 + 1);
543                         if (arg_len) {
544                                 memcpy(p, arg, arg_len);
545                                 p += arg_len;
546                         }
547                 }
548                 if (p[-1] != '/') {
549                         *p++ = '/';
550                         slash_cnt++;
551                 }
552                 *p++ = '*';
553                 if (recurse)
554                         *p++ = '*';
555                 *p = '\0';
556                 rule->u.slash_cnt = slash_cnt;
557                 rule->next = implied_filter_list.head;
558                 implied_filter_list.head = rule;
559                 if (DEBUG_GTE(FILTER, 3))
560                         rprintf(FINFO, "[%s] add_implied_include(%s)\n", who_am_i(), rule->pattern);
561                 if (saw_live_open_brkt)
562                         maybe_add_literal_brackets_rule(rule, p - rule->pattern);
563         }
564 }
565
566 /* This frees any non-inherited items, leaving just inherited items on the list. */
567 static void pop_filter_list(filter_rule_list *listp)
568 {
569         filter_rule *inherited;
570
571         if (!listp->tail)
572                 return;
573
574         inherited = listp->tail->next;
575
576         /* Truncate any inherited items from the local list. */
577         listp->tail->next = NULL;
578         /* Now free everything that is left. */
579         free_filters(listp->head);
580
581         listp->head = inherited;
582         listp->tail = NULL;
583 }
584
585 /* This returns an expanded (absolute) filename for the merge-file name if
586  * the name has any slashes in it OR if the parent_dirscan var is True;
587  * otherwise it returns the original merge_file name.  If the len_ptr value
588  * is non-NULL the merge_file name is limited by the referenced length
589  * value and will be updated with the length of the resulting name.  We
590  * always return a name that is null terminated, even if the merge_file
591  * name was not. */
592 static char *parse_merge_name(const char *merge_file, unsigned int *len_ptr,
593                               unsigned int prefix_skip)
594 {
595         static char buf[MAXPATHLEN];
596         char *fn, tmpbuf[MAXPATHLEN];
597         unsigned int fn_len;
598
599         if (!parent_dirscan && *merge_file != '/') {
600                 /* Return the name unchanged it doesn't have any slashes. */
601                 if (len_ptr) {
602                         const char *p = merge_file + *len_ptr;
603                         while (--p > merge_file && *p != '/') {}
604                         if (p == merge_file) {
605                                 strlcpy(buf, merge_file, *len_ptr + 1);
606                                 return buf;
607                         }
608                 } else if (strchr(merge_file, '/') == NULL)
609                         return (char *)merge_file;
610         }
611
612         fn = *merge_file == '/' ? buf : tmpbuf;
613         if (sanitize_paths) {
614                 const char *r = prefix_skip ? "/" : NULL;
615                 /* null-terminate the name if it isn't already */
616                 if (len_ptr && merge_file[*len_ptr]) {
617                         char *to = fn == buf ? tmpbuf : buf;
618                         strlcpy(to, merge_file, *len_ptr + 1);
619                         merge_file = to;
620                 }
621                 if (!sanitize_path(fn, merge_file, r, dirbuf_depth, SP_DEFAULT)) {
622                         rprintf(FERROR, "merge-file name overflows: %s\n",
623                                 merge_file);
624                         return NULL;
625                 }
626                 fn_len = strlen(fn);
627         } else {
628                 strlcpy(fn, merge_file, len_ptr ? *len_ptr + 1 : MAXPATHLEN);
629                 fn_len = clean_fname(fn, CFN_COLLAPSE_DOT_DOT_DIRS);
630         }
631
632         /* If the name isn't in buf yet, it wasn't absolute. */
633         if (fn != buf) {
634                 int d_len = dirbuf_len - prefix_skip;
635                 if (d_len + fn_len >= MAXPATHLEN) {
636                         rprintf(FERROR, "merge-file name overflows: %s\n", fn);
637                         return NULL;
638                 }
639                 memcpy(buf, dirbuf + prefix_skip, d_len);
640                 memcpy(buf + d_len, fn, fn_len + 1);
641                 fn_len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
642         }
643
644         if (len_ptr)
645                 *len_ptr = fn_len;
646         return buf;
647 }
648
649 /* Sets the dirbuf and dirbuf_len values. */
650 void set_filter_dir(const char *dir, unsigned int dirlen)
651 {
652         unsigned int len;
653         if (*dir != '/') {
654                 memcpy(dirbuf, curr_dir, curr_dir_len);
655                 dirbuf[curr_dir_len] = '/';
656                 len = curr_dir_len + 1;
657                 if (len + dirlen >= MAXPATHLEN)
658                         dirlen = 0;
659         } else
660                 len = 0;
661         memcpy(dirbuf + len, dir, dirlen);
662         dirbuf[dirlen + len] = '\0';
663         dirbuf_len = clean_fname(dirbuf, CFN_COLLAPSE_DOT_DOT_DIRS);
664         if (dirbuf_len > 1 && dirbuf[dirbuf_len-1] == '.'
665             && dirbuf[dirbuf_len-2] == '/')
666                 dirbuf_len -= 2;
667         if (dirbuf_len != 1)
668                 dirbuf[dirbuf_len++] = '/';
669         dirbuf[dirbuf_len] = '\0';
670         if (sanitize_paths)
671                 dirbuf_depth = count_dir_elements(dirbuf + module_dirlen);
672 }
673
674 /* This routine takes a per-dir merge-file entry and finishes its setup.
675  * If the name has a path portion then we check to see if it refers to a
676  * parent directory of the first transfer dir.  If it does, we scan all the
677  * dirs from that point through the parent dir of the transfer dir looking
678  * for the per-dir merge-file in each one. */
679 static BOOL setup_merge_file(int mergelist_num, filter_rule *ex,
680                              filter_rule_list *lp)
681 {
682         char buf[MAXPATHLEN];
683         char *x, *y, *pat = ex->pattern;
684         unsigned int len;
685
686         if (!(x = parse_merge_name(pat, NULL, 0)) || *x != '/')
687                 return 0;
688
689         if (DEBUG_GTE(FILTER, 2)) {
690                 rprintf(FINFO, "[%s] performing parent_dirscan for mergelist #%d%s\n",
691                         who_am_i(), mergelist_num, lp->debug_type);
692         }
693         y = strrchr(x, '/');
694         *y = '\0';
695         ex->pattern = strdup(y+1);
696         if (!*x)
697                 x = "/";
698         if (*x == '/')
699                 strlcpy(buf, x, MAXPATHLEN);
700         else
701                 pathjoin(buf, MAXPATHLEN, dirbuf, x);
702
703         len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
704         if (len != 1 && len < MAXPATHLEN-1) {
705                 buf[len++] = '/';
706                 buf[len] = '\0';
707         }
708         /* This ensures that the specified dir is a parent of the transfer. */
709         for (x = buf, y = dirbuf; *x && *x == *y; x++, y++) {}
710         if (*x)
711                 y += strlen(y); /* nope -- skip the scan */
712
713         parent_dirscan = True;
714         while (*y) {
715                 char save[MAXPATHLEN];
716                 strlcpy(save, y, MAXPATHLEN);
717                 *y = '\0';
718                 dirbuf_len = y - dirbuf;
719                 strlcpy(x, ex->pattern, MAXPATHLEN - (x - buf));
720                 parse_filter_file(lp, buf, ex, XFLG_ANCHORED2ABS);
721                 if (ex->rflags & FILTRULE_NO_INHERIT) {
722                         /* Free the undesired rules to clean up any per-dir
723                          * mergelists they defined.  Otherwise pop_local_filters
724                          * may crash trying to restore nonexistent state for
725                          * those mergelists. */
726                         free_filters(lp->head);
727                         lp->head = NULL;
728                 }
729                 lp->tail = NULL;
730                 strlcpy(y, save, MAXPATHLEN);
731                 while ((*x++ = *y++) != '/') {}
732         }
733         parent_dirscan = False;
734         if (DEBUG_GTE(FILTER, 2)) {
735                 rprintf(FINFO, "[%s] completed parent_dirscan for mergelist #%d%s\n",
736                         who_am_i(), mergelist_num, lp->debug_type);
737         }
738         free(pat);
739         return 1;
740 }
741
742 struct local_filter_state {
743         int mergelist_cnt;
744         filter_rule_list mergelists[1];
745 };
746
747 /* Each time rsync changes to a new directory it call this function to
748  * handle all the per-dir merge-files.  The "dir" value is the current path
749  * relative to curr_dir (which might not be null-terminated).  We copy it
750  * into dirbuf so that we can easily append a file name on the end. */
751 void *push_local_filters(const char *dir, unsigned int dirlen)
752 {
753         struct local_filter_state *push;
754         int i;
755
756         set_filter_dir(dir, dirlen);
757         if (DEBUG_GTE(FILTER, 2)) {
758                 rprintf(FINFO, "[%s] pushing local filters for %s\n",
759                         who_am_i(), dirbuf);
760         }
761
762         if (!mergelist_cnt) {
763                 /* No old state to save and no new merge files to push. */
764                 return NULL;
765         }
766
767         push = (struct local_filter_state *)new_array(char,
768                           sizeof (struct local_filter_state)
769                         + (mergelist_cnt-1) * sizeof (filter_rule_list));
770
771         push->mergelist_cnt = mergelist_cnt;
772         for (i = 0; i < mergelist_cnt; i++) {
773                 filter_rule *ex = mergelist_parents[i];
774                 if (!ex)
775                         continue;
776                 memcpy(&push->mergelists[i], ex->u.mergelist, sizeof (filter_rule_list));
777         }
778
779         /* Note: parse_filter_file() might increase mergelist_cnt, so keep
780          * this loop separate from the above loop. */
781         for (i = 0; i < mergelist_cnt; i++) {
782                 filter_rule *ex = mergelist_parents[i];
783                 filter_rule_list *lp;
784                 if (!ex)
785                         continue;
786                 lp = ex->u.mergelist;
787
788                 if (DEBUG_GTE(FILTER, 2)) {
789                         rprintf(FINFO, "[%s] pushing mergelist #%d%s\n",
790                                 who_am_i(), i, lp->debug_type);
791                 }
792
793                 lp->tail = NULL; /* Switch any local rules to inherited. */
794                 if (ex->rflags & FILTRULE_NO_INHERIT)
795                         lp->head = NULL;
796
797                 if (ex->rflags & FILTRULE_FINISH_SETUP) {
798                         ex->rflags &= ~FILTRULE_FINISH_SETUP;
799                         if (setup_merge_file(i, ex, lp))
800                                 set_filter_dir(dir, dirlen);
801                 }
802
803                 if (strlcpy(dirbuf + dirbuf_len, ex->pattern,
804                     MAXPATHLEN - dirbuf_len) < MAXPATHLEN - dirbuf_len) {
805                         parse_filter_file(lp, dirbuf, ex,
806                                           XFLG_ANCHORED2ABS);
807                 } else {
808                         io_error |= IOERR_GENERAL;
809                         rprintf(FERROR,
810                             "cannot add local filter rules in long-named directory: %s\n",
811                             full_fname(dirbuf));
812                 }
813                 dirbuf[dirbuf_len] = '\0';
814         }
815
816         return (void*)push;
817 }
818
819 void pop_local_filters(void *mem)
820 {
821         struct local_filter_state *pop = (struct local_filter_state *)mem;
822         int i;
823         int old_mergelist_cnt = pop ? pop->mergelist_cnt : 0;
824
825         if (DEBUG_GTE(FILTER, 2))
826                 rprintf(FINFO, "[%s] popping local filters\n", who_am_i());
827
828         for (i = mergelist_cnt; i-- > 0; ) {
829                 filter_rule *ex = mergelist_parents[i];
830                 filter_rule_list *lp;
831                 if (!ex)
832                         continue;
833                 lp = ex->u.mergelist;
834
835                 if (DEBUG_GTE(FILTER, 2)) {
836                         rprintf(FINFO, "[%s] popping mergelist #%d%s\n",
837                                 who_am_i(), i, lp->debug_type);
838                 }
839
840                 pop_filter_list(lp);
841                 if (i >= old_mergelist_cnt && lp->head) {
842                         /* This mergelist does not exist in the state to be restored, but it
843                          * still has inherited rules.  This can sometimes happen if a per-dir
844                          * merge file calls setup_merge_file() in push_local_filters() and that
845                          * leaves some inherited rules that aren't in the pushed list state. */
846                         if (DEBUG_GTE(FILTER, 2)) {
847                                 rprintf(FINFO, "[%s] freeing parent_dirscan filters of mergelist #%d%s\n",
848                                         who_am_i(), i, ex->u.mergelist->debug_type);
849                         }
850                         pop_filter_list(lp);
851                 }
852         }
853
854         if (!pop)
855                 return; /* No state to restore. */
856
857         for (i = 0; i < old_mergelist_cnt; i++) {
858                 filter_rule *ex = mergelist_parents[i];
859                 if (!ex)
860                         continue;
861                 memcpy(ex->u.mergelist, &pop->mergelists[i], sizeof (filter_rule_list));
862         }
863
864         free(pop);
865 }
866
867 void change_local_filter_dir(const char *dname, int dlen, int dir_depth)
868 {
869         static int cur_depth = -1;
870         static void *filt_array[MAXPATHLEN/2+1];
871
872         if (!dname) {
873                 for ( ; cur_depth >= 0; cur_depth--) {
874                         if (filt_array[cur_depth]) {
875                                 pop_local_filters(filt_array[cur_depth]);
876                                 filt_array[cur_depth] = NULL;
877                         }
878                 }
879                 return;
880         }
881
882         assert(dir_depth < MAXPATHLEN/2+1);
883
884         for ( ; cur_depth >= dir_depth; cur_depth--) {
885                 if (filt_array[cur_depth]) {
886                         pop_local_filters(filt_array[cur_depth]);
887                         filt_array[cur_depth] = NULL;
888                 }
889         }
890
891         cur_depth = dir_depth;
892         filt_array[cur_depth] = push_local_filters(dname, dlen);
893 }
894
895 static int rule_matches(const char *fname, filter_rule *ex, int name_flags)
896 {
897         int slash_handling, str_cnt = 0, anchored_match = 0;
898         int ret_match = ex->rflags & FILTRULE_NEGATE ? 0 : 1;
899         char *p, *pattern = ex->pattern;
900         const char *strings[16]; /* more than enough */
901         const char *name = fname + (*fname == '/');
902
903         if (!*name)
904                 return 0;
905
906         if (!(name_flags & NAME_IS_XATTR) ^ !(ex->rflags & FILTRULE_XATTR))
907                 return 0;
908
909         if (!ex->u.slash_cnt && !(ex->rflags & FILTRULE_WILD2)) {
910                 /* If the pattern does not have any slashes AND it does
911                  * not have a "**" (which could match a slash), then we
912                  * just match the name portion of the path. */
913                 if ((p = strrchr(name,'/')) != NULL)
914                         name = p+1;
915         } else if (ex->rflags & FILTRULE_ABS_PATH && *fname != '/'
916             && curr_dir_len > module_dirlen + 1) {
917                 /* If we're matching against an absolute-path pattern,
918                  * we need to prepend our full path info. */
919                 strings[str_cnt++] = curr_dir + module_dirlen + 1;
920                 strings[str_cnt++] = "/";
921         } else if (ex->rflags & FILTRULE_WILD2_PREFIX && *fname != '/') {
922                 /* Allow "**"+"/" to match at the start of the string. */
923                 strings[str_cnt++] = "/";
924         }
925         strings[str_cnt++] = name;
926         if (name_flags & NAME_IS_DIR) {
927                 /* Allow a trailing "/"+"***" to match the directory. */
928                 if (ex->rflags & FILTRULE_WILD3_SUFFIX)
929                         strings[str_cnt++] = "/";
930         } else if (ex->rflags & FILTRULE_DIRECTORY)
931                 return !ret_match;
932         strings[str_cnt] = NULL;
933
934         if (*pattern == '/') {
935                 anchored_match = 1;
936                 pattern++;
937         }
938
939         if (!anchored_match && ex->u.slash_cnt
940             && !(ex->rflags & FILTRULE_WILD2)) {
941                 /* A non-anchored match with an infix slash and no "**"
942                  * needs to match the last slash_cnt+1 name elements. */
943                 slash_handling = ex->u.slash_cnt + 1;
944         } else if (!anchored_match && !(ex->rflags & FILTRULE_WILD2_PREFIX)
945                                    && ex->rflags & FILTRULE_WILD2) {
946                 /* A non-anchored match with an infix or trailing "**" (but not
947                  * a prefixed "**") needs to try matching after every slash. */
948                 slash_handling = -1;
949         } else {
950                 /* The pattern matches only at the start of the path or name. */
951                 slash_handling = 0;
952         }
953
954         if (ex->rflags & FILTRULE_WILD) {
955                 if (wildmatch_array(pattern, strings, slash_handling))
956                         return ret_match;
957         } else if (str_cnt > 1) {
958                 if (litmatch_array(pattern, strings, slash_handling))
959                         return ret_match;
960         } else if (anchored_match) {
961                 if (strcmp(name, pattern) == 0)
962                         return ret_match;
963         } else {
964                 int l1 = strlen(name);
965                 int l2 = strlen(pattern);
966                 if (l2 <= l1 &&
967                     strcmp(name+(l1-l2),pattern) == 0 &&
968                     (l1==l2 || name[l1-(l2+1)] == '/')) {
969                         return ret_match;
970                 }
971         }
972
973         return !ret_match;
974 }
975
976 static void report_filter_result(enum logcode code, char const *name,
977                                  filter_rule const *ent,
978                                  int name_flags, const char *type)
979 {
980         int log_level = am_sender || am_generator ? 1 : 3;
981
982         /* If a trailing slash is present to match only directories,
983          * then it is stripped out by add_rule().  So as a special
984          * case we add it back in the log output. */
985         if (DEBUG_GTE(FILTER, log_level)) {
986                 static char *actions[2][2]
987                     = { {"show", "hid"}, {"risk", "protect"} };
988                 const char *w = who_am_i();
989                 const char *t = name_flags & NAME_IS_XATTR ? "xattr"
990                               : name_flags & NAME_IS_DIR ? "directory"
991                               : "file";
992                 rprintf(code, "[%s] %sing %s %s because of pattern %s%s%s\n",
993                     w, actions[*w=='g'][!(ent->rflags & FILTRULE_INCLUDE)],
994                     t, name, ent->pattern,
995                     ent->rflags & FILTRULE_DIRECTORY ? "/" : "", type);
996         }
997 }
998
999 /* This function is used to check if a file should be included/excluded
1000  * from the list of files based on its name and type etc.  The value of
1001  * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
1002 int name_is_excluded(const char *fname, int name_flags, int filter_level)
1003 {
1004         if (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, name_flags) < 0) {
1005                 if (!(name_flags & NAME_IS_XATTR))
1006                         errno = ENOENT;
1007                 return 1;
1008         }
1009
1010         if (filter_level != ALL_FILTERS)
1011                 return 0;
1012
1013         if (filter_list.head && check_filter(&filter_list, FINFO, fname, name_flags) < 0)
1014                 return 1;
1015
1016         return 0;
1017 }
1018
1019 /* Return -1 if file "name" is defined to be excluded by the specified
1020  * exclude list, 1 if it is included, and 0 if it was not matched. */
1021 int check_filter(filter_rule_list *listp, enum logcode code,
1022                  const char *name, int name_flags)
1023 {
1024         filter_rule *ent;
1025
1026         for (ent = listp->head; ent; ent = ent->next) {
1027                 if (ignore_perishable && ent->rflags & FILTRULE_PERISHABLE)
1028                         continue;
1029                 if (ent->rflags & FILTRULE_PERDIR_MERGE) {
1030                         int rc = check_filter(ent->u.mergelist, code, name, name_flags);
1031                         if (rc)
1032                                 return rc;
1033                         continue;
1034                 }
1035                 if (ent->rflags & FILTRULE_CVS_IGNORE) {
1036                         int rc = check_filter(&cvs_filter_list, code, name, name_flags);
1037                         if (rc)
1038                                 return rc;
1039                         continue;
1040                 }
1041                 if (rule_matches(name, ent, name_flags)) {
1042                         report_filter_result(code, name, ent, name_flags, listp->debug_type);
1043                         return ent->rflags & FILTRULE_INCLUDE ? 1 : -1;
1044                 }
1045         }
1046
1047         return 0;
1048 }
1049
1050 #define RULE_STRCMP(s,r) rule_strcmp((s), (r), sizeof (r) - 1)
1051
1052 static const uchar *rule_strcmp(const uchar *str, const char *rule, int rule_len)
1053 {
1054         if (strncmp((char*)str, rule, rule_len) != 0)
1055                 return NULL;
1056         if (isspace(str[rule_len]) || str[rule_len] == '_' || !str[rule_len])
1057                 return str + rule_len - 1;
1058         if (str[rule_len] == ',')
1059                 return str + rule_len;
1060         return NULL;
1061 }
1062
1063 #define FILTRULES_FROM_CONTAINER (FILTRULE_ABS_PATH | FILTRULE_INCLUDE \
1064                                 | FILTRULE_DIRECTORY | FILTRULE_NEGATE \
1065                                 | FILTRULE_PERISHABLE)
1066
1067 /* Gets the next include/exclude rule from *rulestr_ptr and advances
1068  * *rulestr_ptr to point beyond it.  Stores the pattern's start (within
1069  * *rulestr_ptr) and length in *pat_ptr and *pat_len_ptr, and returns a newly
1070  * allocated filter_rule containing the rest of the information.  Returns
1071  * NULL if there are no more rules in the input.
1072  *
1073  * The template provides defaults for the new rule to inherit, and the
1074  * template rflags and the xflags additionally affect parsing. */
1075 static filter_rule *parse_rule_tok(const char **rulestr_ptr,
1076                                    const filter_rule *template, int xflags,
1077                                    const char **pat_ptr, unsigned int *pat_len_ptr)
1078 {
1079         const uchar *s = (const uchar *)*rulestr_ptr;
1080         filter_rule *rule;
1081         unsigned int len;
1082
1083         if (template->rflags & FILTRULE_WORD_SPLIT) {
1084                 /* Skip over any initial whitespace. */
1085                 while (isspace(*s))
1086                         s++;
1087                 /* Update to point to real start of rule. */
1088                 *rulestr_ptr = (const char *)s;
1089         }
1090         if (!*s)
1091                 return NULL;
1092
1093         rule = new0(filter_rule);
1094
1095         /* Inherit from the template.  Don't inherit FILTRULES_SIDES; we check
1096          * that later. */
1097         rule->rflags = template->rflags & FILTRULES_FROM_CONTAINER;
1098
1099         /* Figure out what kind of a filter rule "s" is pointing at.  Note
1100          * that if FILTRULE_NO_PREFIXES is set, the rule is either an include
1101          * or an exclude based on the inheritance of the FILTRULE_INCLUDE
1102          * flag (above).  XFLG_OLD_PREFIXES indicates a compatibility mode
1103          * for old include/exclude patterns where just "+ " and "- " are
1104          * allowed as optional prefixes.  */
1105         if (template->rflags & FILTRULE_NO_PREFIXES) {
1106                 if (*s == '!' && template->rflags & FILTRULE_CVS_IGNORE)
1107                         rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
1108         } else if (xflags & XFLG_OLD_PREFIXES) {
1109                 if (*s == '-' && s[1] == ' ') {
1110                         rule->rflags &= ~FILTRULE_INCLUDE;
1111                         s += 2;
1112                 } else if (*s == '+' && s[1] == ' ') {
1113                         rule->rflags |= FILTRULE_INCLUDE;
1114                         s += 2;
1115                 } else if (*s == '!')
1116                         rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
1117         } else {
1118                 char ch = 0;
1119                 BOOL prefix_specifies_side = False;
1120                 switch (*s) {
1121                 case 'c':
1122                         if ((s = RULE_STRCMP(s, "clear")) != NULL)
1123                                 ch = '!';
1124                         break;
1125                 case 'd':
1126                         if ((s = RULE_STRCMP(s, "dir-merge")) != NULL)
1127                                 ch = ':';
1128                         break;
1129                 case 'e':
1130                         if ((s = RULE_STRCMP(s, "exclude")) != NULL)
1131                                 ch = '-';
1132                         break;
1133                 case 'h':
1134                         if ((s = RULE_STRCMP(s, "hide")) != NULL)
1135                                 ch = 'H';
1136                         break;
1137                 case 'i':
1138                         if ((s = RULE_STRCMP(s, "include")) != NULL)
1139                                 ch = '+';
1140                         break;
1141                 case 'm':
1142                         if ((s = RULE_STRCMP(s, "merge")) != NULL)
1143                                 ch = '.';
1144                         break;
1145                 case 'p':
1146                         if ((s = RULE_STRCMP(s, "protect")) != NULL)
1147                                 ch = 'P';
1148                         break;
1149                 case 'r':
1150                         if ((s = RULE_STRCMP(s, "risk")) != NULL)
1151                                 ch = 'R';
1152                         break;
1153                 case 's':
1154                         if ((s = RULE_STRCMP(s, "show")) != NULL)
1155                                 ch = 'S';
1156                         break;
1157                 default:
1158                         ch = *s;
1159                         if (s[1] == ',')
1160                                 s++;
1161                         break;
1162                 }
1163                 switch (ch) {
1164                 case ':':
1165                         trust_sender_filter = 1;
1166                         rule->rflags |= FILTRULE_PERDIR_MERGE
1167                                       | FILTRULE_FINISH_SETUP;
1168                         /* FALL THROUGH */
1169                 case '.':
1170                         rule->rflags |= FILTRULE_MERGE_FILE;
1171                         break;
1172                 case '+':
1173                         rule->rflags |= FILTRULE_INCLUDE;
1174                         break;
1175                 case '-':
1176                         break;
1177                 case 'S':
1178                         rule->rflags |= FILTRULE_INCLUDE;
1179                         /* FALL THROUGH */
1180                 case 'H':
1181                         rule->rflags |= FILTRULE_SENDER_SIDE;
1182                         prefix_specifies_side = True;
1183                         break;
1184                 case 'R':
1185                         rule->rflags |= FILTRULE_INCLUDE;
1186                         /* FALL THROUGH */
1187                 case 'P':
1188                         rule->rflags |= FILTRULE_RECEIVER_SIDE;
1189                         prefix_specifies_side = True;
1190                         break;
1191                 case '!':
1192                         rule->rflags |= FILTRULE_CLEAR_LIST;
1193                         break;
1194                 default:
1195                         rprintf(FERROR, "Unknown filter rule: `%s'\n", *rulestr_ptr);
1196                         exit_cleanup(RERR_SYNTAX);
1197                 }
1198                 while (ch != '!' && *++s && *s != ' ' && *s != '_') {
1199                         if (template->rflags & FILTRULE_WORD_SPLIT && isspace(*s)) {
1200                                 s--;
1201                                 break;
1202                         }
1203                         switch (*s) {
1204                         default:
1205                             invalid:
1206                                 rprintf(FERROR,
1207                                         "invalid modifier '%c' at position %d in filter rule: %s\n",
1208                                         *s, (int)(s - (const uchar *)*rulestr_ptr), *rulestr_ptr);
1209                                 exit_cleanup(RERR_SYNTAX);
1210                         case '-':
1211                                 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
1212                                         goto invalid;
1213                                 rule->rflags |= FILTRULE_NO_PREFIXES;
1214                                 break;
1215                         case '+':
1216                                 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
1217                                         goto invalid;
1218                                 rule->rflags |= FILTRULE_NO_PREFIXES
1219                                               | FILTRULE_INCLUDE;
1220                                 break;
1221                         case '/':
1222                                 rule->rflags |= FILTRULE_ABS_PATH;
1223                                 break;
1224                         case '!':
1225                                 /* Negation really goes with the pattern, so it
1226                                  * isn't useful as a merge-file default. */
1227                                 if (rule->rflags & FILTRULE_MERGE_FILE)
1228                                         goto invalid;
1229                                 rule->rflags |= FILTRULE_NEGATE;
1230                                 break;
1231                         case 'C':
1232                                 if (rule->rflags & FILTRULE_NO_PREFIXES || prefix_specifies_side)
1233                                         goto invalid;
1234                                 rule->rflags |= FILTRULE_NO_PREFIXES
1235                                               | FILTRULE_WORD_SPLIT
1236                                               | FILTRULE_NO_INHERIT
1237                                               | FILTRULE_CVS_IGNORE;
1238                                 break;
1239                         case 'e':
1240                                 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1241                                         goto invalid;
1242                                 rule->rflags |= FILTRULE_EXCLUDE_SELF;
1243                                 break;
1244                         case 'n':
1245                                 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1246                                         goto invalid;
1247                                 rule->rflags |= FILTRULE_NO_INHERIT;
1248                                 break;
1249                         case 'p':
1250                                 rule->rflags |= FILTRULE_PERISHABLE;
1251                                 break;
1252                         case 'r':
1253                                 if (prefix_specifies_side)
1254                                         goto invalid;
1255                                 rule->rflags |= FILTRULE_RECEIVER_SIDE;
1256                                 break;
1257                         case 's':
1258                                 if (prefix_specifies_side)
1259                                         goto invalid;
1260                                 rule->rflags |= FILTRULE_SENDER_SIDE;
1261                                 break;
1262                         case 'w':
1263                                 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1264                                         goto invalid;
1265                                 rule->rflags |= FILTRULE_WORD_SPLIT;
1266                                 break;
1267                         case 'x':
1268                                 rule->rflags |= FILTRULE_XATTR;
1269                                 saw_xattr_filter = 1;
1270                                 break;
1271                         }
1272                 }
1273                 if (*s)
1274                         s++;
1275         }
1276         if (template->rflags & FILTRULES_SIDES) {
1277                 if (rule->rflags & FILTRULES_SIDES) {
1278                         /* The filter and template both specify side(s).  This
1279                          * is dodgy (and won't work correctly if the template is
1280                          * a one-sided per-dir merge rule), so reject it. */
1281                         rprintf(FERROR,
1282                                 "specified-side merge file contains specified-side filter: %s\n",
1283                                 *rulestr_ptr);
1284                         exit_cleanup(RERR_SYNTAX);
1285                 }
1286                 rule->rflags |= template->rflags & FILTRULES_SIDES;
1287         }
1288
1289         if (template->rflags & FILTRULE_WORD_SPLIT) {
1290                 const uchar *cp = s;
1291                 /* Token ends at whitespace or the end of the string. */
1292                 while (!isspace(*cp) && *cp != '\0')
1293                         cp++;
1294                 len = cp - s;
1295         } else
1296                 len = strlen((char*)s);
1297
1298         if (rule->rflags & FILTRULE_CLEAR_LIST) {
1299                 if (!(rule->rflags & FILTRULE_NO_PREFIXES)
1300                  && !(xflags & XFLG_OLD_PREFIXES) && len) {
1301                         rprintf(FERROR,
1302                                 "'!' rule has trailing characters: %s\n", *rulestr_ptr);
1303                         exit_cleanup(RERR_SYNTAX);
1304                 }
1305                 if (len > 1)
1306                         rule->rflags &= ~FILTRULE_CLEAR_LIST;
1307         } else if (!len && !(rule->rflags & FILTRULE_CVS_IGNORE)) {
1308                 rprintf(FERROR, "unexpected end of filter rule: %s\n", *rulestr_ptr);
1309                 exit_cleanup(RERR_SYNTAX);
1310         }
1311
1312         /* --delete-excluded turns an un-modified include/exclude into a sender-side rule.  */
1313         if (delete_excluded
1314          && !(rule->rflags & (FILTRULES_SIDES|FILTRULE_MERGE_FILE|FILTRULE_PERDIR_MERGE)))
1315                 rule->rflags |= FILTRULE_SENDER_SIDE;
1316
1317         *pat_ptr = (const char *)s;
1318         *pat_len_ptr = len;
1319         *rulestr_ptr = *pat_ptr + len;
1320         return rule;
1321 }
1322
1323 static void get_cvs_excludes(uint32 rflags)
1324 {
1325         static int initialized = 0;
1326         char *p, fname[MAXPATHLEN];
1327
1328         if (initialized)
1329                 return;
1330         initialized = 1;
1331
1332         parse_filter_str(&cvs_filter_list, default_cvsignore(),
1333                          rule_template(rflags | (protocol_version >= 30 ? FILTRULE_PERISHABLE : 0)),
1334                          0);
1335
1336         p = module_id >= 0 && lp_use_chroot(module_id) ? "/" : getenv("HOME");
1337         if (p && pathjoin(fname, MAXPATHLEN, p, ".cvsignore") < MAXPATHLEN)
1338                 parse_filter_file(&cvs_filter_list, fname, rule_template(rflags), 0);
1339
1340         parse_filter_str(&cvs_filter_list, getenv("CVSIGNORE"), rule_template(rflags), 0);
1341 }
1342
1343 const filter_rule *rule_template(uint32 rflags)
1344 {
1345         static filter_rule template; /* zero-initialized */
1346         template.rflags = rflags;
1347         return &template;
1348 }
1349
1350 void parse_filter_str(filter_rule_list *listp, const char *rulestr,
1351                      const filter_rule *template, int xflags)
1352 {
1353         filter_rule *rule;
1354         const char *pat;
1355         unsigned int pat_len;
1356
1357         if (!rulestr)
1358                 return;
1359
1360         while (1) {
1361                 uint32 new_rflags;
1362
1363                 /* Remember that the returned string is NOT '\0' terminated! */
1364                 if (!(rule = parse_rule_tok(&rulestr, template, xflags, &pat, &pat_len)))
1365                         break;
1366
1367                 if (pat_len >= MAXPATHLEN) {
1368                         rprintf(FERROR, "discarding over-long filter: %.*s\n",
1369                                 (int)pat_len, pat);
1370                     free_continue:
1371                         free_filter(rule);
1372                         continue;
1373                 }
1374
1375                 new_rflags = rule->rflags;
1376                 if (new_rflags & FILTRULE_CLEAR_LIST) {
1377                         if (DEBUG_GTE(FILTER, 2)) {
1378                                 rprintf(FINFO,
1379                                         "[%s] clearing filter list%s\n",
1380                                         who_am_i(), listp->debug_type);
1381                         }
1382                         pop_filter_list(listp);
1383                         listp->head = NULL;
1384                         goto free_continue;
1385                 }
1386
1387                 if (new_rflags & FILTRULE_MERGE_FILE) {
1388                         if (!pat_len) {
1389                                 pat = ".cvsignore";
1390                                 pat_len = 10;
1391                         }
1392                         if (new_rflags & FILTRULE_EXCLUDE_SELF) {
1393                                 const char *name;
1394                                 filter_rule *excl_self;
1395
1396                                 excl_self = new0(filter_rule);
1397                                 /* Find the beginning of the basename and add an exclude for it. */
1398                                 for (name = pat + pat_len; name > pat && name[-1] != '/'; name--) {}
1399                                 add_rule(listp, name, (pat + pat_len) - name, excl_self, 0);
1400                                 rule->rflags &= ~FILTRULE_EXCLUDE_SELF;
1401                         }
1402                         if (new_rflags & FILTRULE_PERDIR_MERGE) {
1403                                 if (parent_dirscan) {
1404                                         const char *p;
1405                                         unsigned int len = pat_len;
1406                                         if ((p = parse_merge_name(pat, &len, module_dirlen)))
1407                                                 add_rule(listp, p, len, rule, 0);
1408                                         else
1409                                                 free_filter(rule);
1410                                         continue;
1411                                 }
1412                         } else {
1413                                 const char *p;
1414                                 unsigned int len = pat_len;
1415                                 if ((p = parse_merge_name(pat, &len, 0)))
1416                                         parse_filter_file(listp, p, rule, XFLG_FATAL_ERRORS);
1417                                 free_filter(rule);
1418                                 continue;
1419                         }
1420                 }
1421
1422                 add_rule(listp, pat, pat_len, rule, xflags);
1423
1424                 if (new_rflags & FILTRULE_CVS_IGNORE
1425                     && !(new_rflags & FILTRULE_MERGE_FILE))
1426                         get_cvs_excludes(new_rflags);
1427         }
1428 }
1429
1430 void parse_filter_file(filter_rule_list *listp, const char *fname, const filter_rule *template, int xflags)
1431 {
1432         FILE *fp;
1433         char line[BIGPATHBUFLEN];
1434         char *eob = line + sizeof line - 1;
1435         BOOL word_split = (template->rflags & FILTRULE_WORD_SPLIT) != 0;
1436
1437         if (!fname || !*fname)
1438                 return;
1439
1440         if (*fname != '-' || fname[1] || am_server) {
1441                 if (daemon_filter_list.head) {
1442                         strlcpy(line, fname, sizeof line);
1443                         clean_fname(line, CFN_COLLAPSE_DOT_DOT_DIRS);
1444                         if (check_filter(&daemon_filter_list, FLOG, line, 0) < 0)
1445                                 fp = NULL;
1446                         else
1447                                 fp = fopen(line, "rb");
1448                 } else
1449                         fp = fopen(fname, "rb");
1450         } else
1451                 fp = stdin;
1452
1453         if (DEBUG_GTE(FILTER, 2)) {
1454                 rprintf(FINFO, "[%s] parse_filter_file(%s,%x,%x)%s\n",
1455                         who_am_i(), fname, template->rflags, xflags,
1456                         fp ? "" : " [not found]");
1457         }
1458
1459         if (!fp) {
1460                 if (xflags & XFLG_FATAL_ERRORS) {
1461                         rsyserr(FERROR, errno,
1462                                 "failed to open %sclude file %s",
1463                                 template->rflags & FILTRULE_INCLUDE ? "in" : "ex",
1464                                 fname);
1465                         exit_cleanup(RERR_FILEIO);
1466                 }
1467                 return;
1468         }
1469         dirbuf[dirbuf_len] = '\0';
1470
1471         while (1) {
1472                 char *s = line;
1473                 int ch, overflow = 0;
1474                 while (1) {
1475                         if ((ch = getc(fp)) == EOF) {
1476                                 if (ferror(fp) && errno == EINTR) {
1477                                         clearerr(fp);
1478                                         continue;
1479                                 }
1480                                 break;
1481                         }
1482                         if (word_split && isspace(ch))
1483                                 break;
1484                         if (eol_nulls? !ch : (ch == '\n' || ch == '\r'))
1485                                 break;
1486                         if (s < eob)
1487                                 *s++ = ch;
1488                         else
1489                                 overflow = 1;
1490                 }
1491                 if (overflow) {
1492                         rprintf(FERROR, "discarding over-long filter: %s...\n", line);
1493                         s = line;
1494                 }
1495                 *s = '\0';
1496                 /* Skip an empty token and (when line parsing) comments. */
1497                 if (*line && (word_split || (*line != ';' && *line != '#')))
1498                         parse_filter_str(listp, line, template, xflags);
1499                 if (ch == EOF)
1500                         break;
1501         }
1502         fclose(fp);
1503 }
1504
1505 /* If the "for_xfer" flag is set, the prefix is made compatible with the
1506  * current protocol_version (if possible) or a NULL is returned (if not
1507  * possible). */
1508 char *get_rule_prefix(filter_rule *rule, const char *pat, int for_xfer,
1509                       unsigned int *plen_ptr)
1510 {
1511         static char buf[MAX_RULE_PREFIX+1];
1512         char *op = buf;
1513         int legal_len = for_xfer && protocol_version < 29 ? 1 : MAX_RULE_PREFIX-1;
1514
1515         if (rule->rflags & FILTRULE_PERDIR_MERGE) {
1516                 if (legal_len == 1)
1517                         return NULL;
1518                 *op++ = ':';
1519         } else if (rule->rflags & FILTRULE_INCLUDE)
1520                 *op++ = '+';
1521         else if (legal_len != 1
1522             || ((*pat == '-' || *pat == '+') && pat[1] == ' '))
1523                 *op++ = '-';
1524         else
1525                 legal_len = 0;
1526
1527         if (rule->rflags & FILTRULE_ABS_PATH)
1528                 *op++ = '/';
1529         if (rule->rflags & FILTRULE_NEGATE)
1530                 *op++ = '!';
1531         if (rule->rflags & FILTRULE_CVS_IGNORE)
1532                 *op++ = 'C';
1533         else {
1534                 if (rule->rflags & FILTRULE_NO_INHERIT)
1535                         *op++ = 'n';
1536                 if (rule->rflags & FILTRULE_WORD_SPLIT)
1537                         *op++ = 'w';
1538                 if (rule->rflags & FILTRULE_NO_PREFIXES) {
1539                         if (rule->rflags & FILTRULE_INCLUDE)
1540                                 *op++ = '+';
1541                         else
1542                                 *op++ = '-';
1543                 }
1544         }
1545         if (rule->rflags & FILTRULE_EXCLUDE_SELF)
1546                 *op++ = 'e';
1547         if (rule->rflags & FILTRULE_XATTR)
1548                 *op++ = 'x';
1549         if (rule->rflags & FILTRULE_SENDER_SIDE
1550             && (!for_xfer || protocol_version >= 29))
1551                 *op++ = 's';
1552         if (rule->rflags & FILTRULE_RECEIVER_SIDE
1553             && (!for_xfer || protocol_version >= 29
1554              || (delete_excluded && am_sender)))
1555                 *op++ = 'r';
1556         if (rule->rflags & FILTRULE_PERISHABLE) {
1557                 if (!for_xfer || protocol_version >= 30)
1558                         *op++ = 'p';
1559                 else if (am_sender)
1560                         return NULL;
1561         }
1562         if (op - buf > legal_len)
1563                 return NULL;
1564         if (legal_len)
1565                 *op++ = ' ';
1566         *op = '\0';
1567         if (plen_ptr)
1568                 *plen_ptr = op - buf;
1569         return buf;
1570 }
1571
1572 static void send_rules(int f_out, filter_rule_list *flp)
1573 {
1574         filter_rule *ent, *prev = NULL;
1575
1576         for (ent = flp->head; ent; ent = ent->next) {
1577                 unsigned int len, plen, dlen;
1578                 int elide = 0;
1579                 char *p;
1580
1581                 /* Note we need to check delete_excluded here in addition to
1582                  * the code in parse_rule_tok() because some rules may have
1583                  * been added before we found the --delete-excluded option.
1584                  * We must also elide any CVS merge-file rules to avoid a
1585                  * backward compatibility problem, and we elide any no-prefix
1586                  * merge files as an optimization (since they can only have
1587                  * include/exclude rules). */
1588                 if (ent->rflags & FILTRULE_SENDER_SIDE)
1589                         elide = am_sender ? 1 : -1;
1590                 if (ent->rflags & FILTRULE_RECEIVER_SIDE)
1591                         elide = elide ? 0 : am_sender ? -1 : 1;
1592                 else if (delete_excluded && !elide
1593                  && (!(ent->rflags & FILTRULE_PERDIR_MERGE)
1594                   || ent->rflags & FILTRULE_NO_PREFIXES))
1595                         elide = am_sender ? 1 : -1;
1596                 if (elide < 0) {
1597                         if (prev)
1598                                 prev->next = ent->next;
1599                         else
1600                                 flp->head = ent->next;
1601                 } else
1602                         prev = ent;
1603                 if (elide > 0)
1604                         continue;
1605                 if (ent->rflags & FILTRULE_CVS_IGNORE
1606                     && !(ent->rflags & FILTRULE_MERGE_FILE)) {
1607                         int f = am_sender || protocol_version < 29 ? f_out : -2;
1608                         send_rules(f, &cvs_filter_list);
1609                         if (f == f_out)
1610                                 continue;
1611                 }
1612                 p = get_rule_prefix(ent, ent->pattern, 1, &plen);
1613                 if (!p) {
1614                         rprintf(FERROR,
1615                                 "filter rules are too modern for remote rsync.\n");
1616                         exit_cleanup(RERR_PROTOCOL);
1617                 }
1618                 if (f_out < 0)
1619                         continue;
1620                 len = strlen(ent->pattern);
1621                 dlen = ent->rflags & FILTRULE_DIRECTORY ? 1 : 0;
1622                 if (!(plen + len + dlen))
1623                         continue;
1624                 write_int(f_out, plen + len + dlen);
1625                 if (plen)
1626                         write_buf(f_out, p, plen);
1627                 write_buf(f_out, ent->pattern, len);
1628                 if (dlen)
1629                         write_byte(f_out, '/');
1630         }
1631         flp->tail = prev;
1632 }
1633
1634 /* This is only called by the client. */
1635 void send_filter_list(int f_out)
1636 {
1637         int receiver_wants_list = prune_empty_dirs
1638             || (delete_mode && (!delete_excluded || protocol_version >= 29));
1639
1640         if (local_server || (am_sender && !receiver_wants_list))
1641                 f_out = -1;
1642         if (cvs_exclude && am_sender) {
1643                 if (protocol_version >= 29)
1644                         parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1645                 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1646         }
1647
1648         send_rules(f_out, &filter_list);
1649
1650         if (f_out >= 0)
1651                 write_int(f_out, 0);
1652
1653         if (cvs_exclude) {
1654                 if (!am_sender || protocol_version < 29)
1655                         parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1656                 if (!am_sender)
1657                         parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1658         }
1659 }
1660
1661 /* This is only called by the server. */
1662 void recv_filter_list(int f_in)
1663 {
1664         char line[BIGPATHBUFLEN];
1665         int xflags = protocol_version >= 29 ? 0 : XFLG_OLD_PREFIXES;
1666         int receiver_wants_list = prune_empty_dirs
1667             || (delete_mode && (!delete_excluded || protocol_version >= 29));
1668         unsigned int len;
1669
1670         if (!local_server && (am_sender || receiver_wants_list)) {
1671                 while ((len = read_int(f_in)) != 0) {
1672                         if (len >= sizeof line)
1673                                 overflow_exit("recv_rules");
1674                         read_sbuf(f_in, line, len);
1675                         parse_filter_str(&filter_list, line, rule_template(0), xflags);
1676                 }
1677         }
1678
1679         if (cvs_exclude) {
1680                 if (local_server || am_sender || protocol_version < 29)
1681                         parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1682                 if (local_server || am_sender)
1683                         parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1684         }
1685
1686         if (local_server) /* filter out any rules that aren't for us. */
1687                 send_rules(-1, &filter_list);
1688 }