2 * The filter include/exclude routines.
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
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.
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.
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.
28 extern int am_generator;
33 extern int local_server;
34 extern int prune_empty_dirs;
35 extern int ignore_perishable;
36 extern int old_style_args;
37 extern int relative_paths;
38 extern int delete_mode;
39 extern int delete_excluded;
40 extern int cvs_exclude;
41 extern int sanitize_paths;
42 extern int protocol_version;
46 extern char *filesfrom_host;
47 extern char curr_dir[MAXPATHLEN];
48 extern unsigned int curr_dir_len;
49 extern unsigned int module_dirlen;
51 filter_rule_list filter_list = { .debug_type = "" };
52 filter_rule_list cvs_filter_list = { .debug_type = " [global CVS]" };
53 filter_rule_list daemon_filter_list = { .debug_type = " [daemon]" };
54 filter_rule_list implied_filter_list = { .debug_type = " [implied]" };
56 int saw_xattr_filter = 0;
57 int trust_sender_filter = 0;
59 /* Need room enough for ":MODS " prefix plus some room to grow. */
60 #define MAX_RULE_PREFIX (16)
62 #define SLASH_WILD3_SUFFIX "/***"
64 /* The dirbuf is set by push_local_filters() to the current subdirectory
65 * relative to curr_dir that is being processed. The path always has a
66 * trailing slash appended, and the variable dirbuf_len contains the length
67 * of this path prefix. The path is always absolute. */
68 static char dirbuf[MAXPATHLEN+1];
69 static unsigned int dirbuf_len = 0;
70 static int dirbuf_depth;
72 /* This is True when we're scanning parent dirs for per-dir merge-files. */
73 static BOOL parent_dirscan = False;
75 /* This array contains a list of all the currently active per-dir merge
76 * files. This makes it easier to save the appropriate values when we
77 * "push" down into each subdirectory. */
78 static filter_rule **mergelist_parents;
79 static int mergelist_cnt = 0;
80 static int mergelist_size = 0;
82 /* Each filter_list_struct describes a singly-linked list by keeping track
83 * of both the head and tail pointers. The list is slightly unusual in that
84 * a parent-dir's content can be appended to the end of the local list in a
85 * special way: the last item in the local list has its "next" pointer set
86 * to point to the inherited list, but the local list's tail pointer points
87 * at the end of the local list. Thus, if the local list is empty, the head
88 * will be pointing at the inherited content but the tail will be NULL. To
89 * help you visualize this, here are the possible list arrangements:
91 * Completely Empty Local Content Only
92 * ================================== ====================================
93 * head -> NULL head -> Local1 -> Local2 -> NULL
94 * tail -> NULL tail -------------^
96 * Inherited Content Only Both Local and Inherited Content
97 * ================================== ====================================
98 * head -> Parent1 -> Parent2 -> NULL head -> L1 -> L2 -> P1 -> P2 -> NULL
99 * tail -> NULL tail ---------^
101 * This means that anyone wanting to traverse the whole list to use it just
102 * needs to start at the head and use the "next" pointers until it goes
103 * NULL. To add new local content, we insert the item after the tail item
104 * and update the tail (obviously, if "tail" was NULL, we insert it at the
105 * head). To clear the local list, WE MUST NOT FREE THE INHERITED CONTENT
106 * because it is shared between the current list and our parent list(s).
107 * The easiest way to handle this is to simply truncate the list after the
108 * tail item and then free the local list from the head. When inheriting
109 * the list for a new local dir, we just save off the filter_list_struct
110 * values (so we can pop back to them later) and set the tail to NULL.
113 static void teardown_mergelist(filter_rule *ex)
117 if (!ex->u.mergelist)
120 if (DEBUG_GTE(FILTER, 2)) {
121 rprintf(FINFO, "[%s] deactivating mergelist #%d%s\n",
122 who_am_i(), mergelist_cnt - 1,
123 ex->u.mergelist->debug_type);
126 free(ex->u.mergelist->debug_type);
127 free(ex->u.mergelist);
129 for (j = 0; j < mergelist_cnt; j++) {
130 if (mergelist_parents[j] == ex) {
131 mergelist_parents[j] = NULL;
135 while (mergelist_cnt && mergelist_parents[mergelist_cnt-1] == NULL)
139 static void free_filter(filter_rule *ex)
141 if (ex->rflags & FILTRULE_PERDIR_MERGE)
142 teardown_mergelist(ex);
147 static void free_filters(filter_rule *ent)
150 filter_rule *next = ent->next;
156 /* Build a filter structure given a filter pattern. The value in "pat"
157 * is not null-terminated. "rule" is either held or freed, so the
158 * caller should not free it. */
159 static void add_rule(filter_rule_list *listp, const char *pat, unsigned int pat_len,
160 filter_rule *rule, int xflags)
163 unsigned int pre_len, suf_len, slash_cnt = 0;
164 char *mention_rule_suffix;
166 if (DEBUG_GTE(FILTER, 1) && pat_len && (pat[pat_len-1] == ' ' || pat[pat_len-1] == '\t'))
167 mention_rule_suffix = " -- CAUTION: trailing whitespace!";
169 mention_rule_suffix = DEBUG_GTE(FILTER, 2) ? "" : NULL;
170 if (mention_rule_suffix) {
171 rprintf(FINFO, "[%s] add_rule(%s%.*s%s)%s%s\n",
172 who_am_i(), get_rule_prefix(rule, pat, 0, NULL),
173 (int)pat_len, pat, (rule->rflags & FILTRULE_DIRECTORY) ? "/" : "",
174 listp->debug_type, mention_rule_suffix);
177 /* These flags also indicate that we're reading a list that
178 * needs to be filtered now, not post-filtered later. */
179 if (xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH)
180 && (rule->rflags & FILTRULES_SIDES)
181 == (am_sender ? FILTRULE_RECEIVER_SIDE : FILTRULE_SENDER_SIDE)) {
182 /* This filter applies only to the other side. Drop it. */
187 if (pat_len > 1 && pat[pat_len-1] == '/') {
189 rule->rflags |= FILTRULE_DIRECTORY;
192 for (cp = pat; cp < pat + pat_len; cp++) {
197 if (!(rule->rflags & (FILTRULE_ABS_PATH | FILTRULE_MERGE_FILE))
198 && ((xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH) && *pat == '/')
199 || (xflags & XFLG_ABS_IF_SLASH && slash_cnt))) {
200 rule->rflags |= FILTRULE_ABS_PATH;
202 pre_len = dirbuf_len - module_dirlen - 1;
208 /* The daemon wants dir-exclude rules to get an appended "/" + "***". */
209 if (xflags & XFLG_DIR2WILD3
210 && BITS_SETnUNSET(rule->rflags, FILTRULE_DIRECTORY, FILTRULE_INCLUDE)) {
211 rule->rflags &= ~FILTRULE_DIRECTORY;
212 suf_len = sizeof SLASH_WILD3_SUFFIX - 1;
216 rule->pattern = new_array(char, pre_len + pat_len + suf_len + 1);
218 memcpy(rule->pattern, dirbuf + module_dirlen, pre_len);
219 for (cp = rule->pattern; cp < rule->pattern + pre_len; cp++) {
224 strlcpy(rule->pattern + pre_len, pat, pat_len + 1);
227 memcpy(rule->pattern + pat_len, SLASH_WILD3_SUFFIX, suf_len+1);
232 if (strpbrk(rule->pattern, "*[?")) {
233 rule->rflags |= FILTRULE_WILD;
234 if ((cp = strstr(rule->pattern, "**")) != NULL) {
235 rule->rflags |= FILTRULE_WILD2;
236 /* If the pattern starts with **, note that. */
237 if (cp == rule->pattern)
238 rule->rflags |= FILTRULE_WILD2_PREFIX;
239 /* If the pattern ends with ***, note that. */
241 && rule->pattern[pat_len-3] == '*'
242 && rule->pattern[pat_len-2] == '*'
243 && rule->pattern[pat_len-1] == '*')
244 rule->rflags |= FILTRULE_WILD3_SUFFIX;
248 if (rule->rflags & FILTRULE_PERDIR_MERGE) {
249 filter_rule_list *lp;
253 if ((cp = strrchr(rule->pattern, '/')) != NULL)
258 /* If the local merge file was already mentioned, don't
260 for (i = 0; i < mergelist_cnt; i++) {
261 filter_rule *ex = mergelist_parents[i];
265 s = strrchr(ex->pattern, '/');
271 if (len == pat_len - (cp - rule->pattern) && memcmp(s, cp, len) == 0) {
277 lp = new_array0(filter_rule_list, 1);
278 if (asprintf(&lp->debug_type, " [per-dir %s]", cp) < 0)
279 out_of_memory("add_rule");
280 rule->u.mergelist = lp;
282 if (mergelist_cnt == mergelist_size) {
284 mergelist_parents = realloc_array(mergelist_parents, filter_rule *, mergelist_size);
286 if (DEBUG_GTE(FILTER, 2)) {
287 rprintf(FINFO, "[%s] activating mergelist #%d%s\n",
288 who_am_i(), mergelist_cnt, lp->debug_type);
290 mergelist_parents[mergelist_cnt++] = rule;
292 rule->u.slash_cnt = slash_cnt;
295 rule->next = listp->head;
296 listp->head = listp->tail = rule;
298 rule->next = listp->tail->next;
299 listp->tail->next = rule;
304 /* Each arg the client sends to the remote sender turns into an implied include
305 * that the receiver uses to validate the file list from the sender. */
306 void add_implied_include(const char *arg)
309 int arg_len, saw_wild = 0, backslash_cnt = 0;
310 int slash_cnt = 1; /* We know we're adding a leading slash. */
313 if (am_server || old_style_args || list_only || filesfrom_host != NULL)
315 if (relative_paths) {
316 cp = strstr(arg, "/./");
320 if ((cp = strrchr(arg, '/')) != NULL)
323 arg_len = strlen(arg);
325 if (strpbrk(arg, "*[?")) {
326 /* We need to add room to escape backslashes if wildcard chars are present. */
328 while ((cp = strchr(cp, '\\')) != NULL) {
334 arg_len++; /* Leave room for the prefixed slash */
335 rule = new0(filter_rule);
336 if (!implied_filter_list.head)
337 implied_filter_list.head = implied_filter_list.tail = rule;
339 rule->next = implied_filter_list.head;
340 implied_filter_list.head = rule;
342 rule->rflags = FILTRULE_INCLUDE + (saw_wild ? FILTRULE_WILD : 0);
343 p = rule->pattern = new_array(char, arg_len + 1);
355 if (p[-1] == '/') /* This is safe because of the initial slash. */
357 if (relative_paths) {
358 filter_rule const *ent;
361 for (ent = implied_filter_list.head; ent; ent = ent->next) {
362 if (ent != rule && strcmp(ent->pattern, rule->pattern) == 0)
366 filter_rule *R_rule = new0(filter_rule);
367 R_rule->rflags = FILTRULE_INCLUDE | FILTRULE_DIRECTORY
368 | (saw_wild ? FILTRULE_WILD : 0);
369 R_rule->pattern = strdup(rule->pattern);
370 R_rule->u.slash_cnt = slash_cnt;
371 R_rule->next = implied_filter_list.head;
372 implied_filter_list.head = R_rule;
373 if (DEBUG_GTE(FILTER, 3)) {
374 rprintf(FINFO, "[%s] add_implied_include(%s/)\n",
375 who_am_i(), rule->pattern);
388 rule->u.slash_cnt = slash_cnt;
389 arg = (const char *)rule->pattern;
390 if (DEBUG_GTE(FILTER, 3))
391 rprintf(FINFO, "[%s] add_implied_include(%s)\n", who_am_i(), rule->pattern);
394 if (recurse || xfer_dirs) {
395 /* Now create a rule with an added "/" & "**" or "*" at the end */
396 rule = new0(filter_rule);
398 rule->rflags = FILTRULE_INCLUDE | FILTRULE_WILD | FILTRULE_WILD2;
400 rule->rflags = FILTRULE_INCLUDE | FILTRULE_WILD;
401 /* A +4 in the len leaves enough room for / * * \0 or / * \0 \0 */
402 if (!saw_wild && backslash_cnt) {
403 /* We are appending a wildcard, so now the backslashes need to be escaped. */
404 p = rule->pattern = new_array(char, arg_len + backslash_cnt + 3 + 1);
412 p = rule->pattern = new_array(char, arg_len + 3 + 1);
414 memcpy(p, arg, arg_len);
424 rule->u.slash_cnt = slash_cnt + 1;
425 rule->next = implied_filter_list.head;
426 implied_filter_list.head = rule;
427 if (DEBUG_GTE(FILTER, 3))
428 rprintf(FINFO, "[%s] add_implied_include(%s)\n", who_am_i(), rule->pattern);
432 /* This frees any non-inherited items, leaving just inherited items on the list. */
433 static void pop_filter_list(filter_rule_list *listp)
435 filter_rule *inherited;
440 inherited = listp->tail->next;
442 /* Truncate any inherited items from the local list. */
443 listp->tail->next = NULL;
444 /* Now free everything that is left. */
445 free_filters(listp->head);
447 listp->head = inherited;
451 /* This returns an expanded (absolute) filename for the merge-file name if
452 * the name has any slashes in it OR if the parent_dirscan var is True;
453 * otherwise it returns the original merge_file name. If the len_ptr value
454 * is non-NULL the merge_file name is limited by the referenced length
455 * value and will be updated with the length of the resulting name. We
456 * always return a name that is null terminated, even if the merge_file
458 static char *parse_merge_name(const char *merge_file, unsigned int *len_ptr,
459 unsigned int prefix_skip)
461 static char buf[MAXPATHLEN];
462 char *fn, tmpbuf[MAXPATHLEN];
465 if (!parent_dirscan && *merge_file != '/') {
466 /* Return the name unchanged it doesn't have any slashes. */
468 const char *p = merge_file + *len_ptr;
469 while (--p > merge_file && *p != '/') {}
470 if (p == merge_file) {
471 strlcpy(buf, merge_file, *len_ptr + 1);
474 } else if (strchr(merge_file, '/') == NULL)
475 return (char *)merge_file;
478 fn = *merge_file == '/' ? buf : tmpbuf;
479 if (sanitize_paths) {
480 const char *r = prefix_skip ? "/" : NULL;
481 /* null-terminate the name if it isn't already */
482 if (len_ptr && merge_file[*len_ptr]) {
483 char *to = fn == buf ? tmpbuf : buf;
484 strlcpy(to, merge_file, *len_ptr + 1);
487 if (!sanitize_path(fn, merge_file, r, dirbuf_depth, SP_DEFAULT)) {
488 rprintf(FERROR, "merge-file name overflows: %s\n",
494 strlcpy(fn, merge_file, len_ptr ? *len_ptr + 1 : MAXPATHLEN);
495 fn_len = clean_fname(fn, CFN_COLLAPSE_DOT_DOT_DIRS);
498 /* If the name isn't in buf yet, it wasn't absolute. */
500 int d_len = dirbuf_len - prefix_skip;
501 if (d_len + fn_len >= MAXPATHLEN) {
502 rprintf(FERROR, "merge-file name overflows: %s\n", fn);
505 memcpy(buf, dirbuf + prefix_skip, d_len);
506 memcpy(buf + d_len, fn, fn_len + 1);
507 fn_len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
515 /* Sets the dirbuf and dirbuf_len values. */
516 void set_filter_dir(const char *dir, unsigned int dirlen)
520 memcpy(dirbuf, curr_dir, curr_dir_len);
521 dirbuf[curr_dir_len] = '/';
522 len = curr_dir_len + 1;
523 if (len + dirlen >= MAXPATHLEN)
527 memcpy(dirbuf + len, dir, dirlen);
528 dirbuf[dirlen + len] = '\0';
529 dirbuf_len = clean_fname(dirbuf, CFN_COLLAPSE_DOT_DOT_DIRS);
530 if (dirbuf_len > 1 && dirbuf[dirbuf_len-1] == '.'
531 && dirbuf[dirbuf_len-2] == '/')
534 dirbuf[dirbuf_len++] = '/';
535 dirbuf[dirbuf_len] = '\0';
537 dirbuf_depth = count_dir_elements(dirbuf + module_dirlen);
540 /* This routine takes a per-dir merge-file entry and finishes its setup.
541 * If the name has a path portion then we check to see if it refers to a
542 * parent directory of the first transfer dir. If it does, we scan all the
543 * dirs from that point through the parent dir of the transfer dir looking
544 * for the per-dir merge-file in each one. */
545 static BOOL setup_merge_file(int mergelist_num, filter_rule *ex,
546 filter_rule_list *lp)
548 char buf[MAXPATHLEN];
549 char *x, *y, *pat = ex->pattern;
552 if (!(x = parse_merge_name(pat, NULL, 0)) || *x != '/')
555 if (DEBUG_GTE(FILTER, 2)) {
556 rprintf(FINFO, "[%s] performing parent_dirscan for mergelist #%d%s\n",
557 who_am_i(), mergelist_num, lp->debug_type);
561 ex->pattern = strdup(y+1);
565 strlcpy(buf, x, MAXPATHLEN);
567 pathjoin(buf, MAXPATHLEN, dirbuf, x);
569 len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
570 if (len != 1 && len < MAXPATHLEN-1) {
574 /* This ensures that the specified dir is a parent of the transfer. */
575 for (x = buf, y = dirbuf; *x && *x == *y; x++, y++) {}
577 y += strlen(y); /* nope -- skip the scan */
579 parent_dirscan = True;
581 char save[MAXPATHLEN];
582 strlcpy(save, y, MAXPATHLEN);
584 dirbuf_len = y - dirbuf;
585 strlcpy(x, ex->pattern, MAXPATHLEN - (x - buf));
586 parse_filter_file(lp, buf, ex, XFLG_ANCHORED2ABS);
587 if (ex->rflags & FILTRULE_NO_INHERIT) {
588 /* Free the undesired rules to clean up any per-dir
589 * mergelists they defined. Otherwise pop_local_filters
590 * may crash trying to restore nonexistent state for
591 * those mergelists. */
592 free_filters(lp->head);
596 strlcpy(y, save, MAXPATHLEN);
597 while ((*x++ = *y++) != '/') {}
599 parent_dirscan = False;
600 if (DEBUG_GTE(FILTER, 2)) {
601 rprintf(FINFO, "[%s] completed parent_dirscan for mergelist #%d%s\n",
602 who_am_i(), mergelist_num, lp->debug_type);
608 struct local_filter_state {
610 filter_rule_list mergelists[1];
613 /* Each time rsync changes to a new directory it call this function to
614 * handle all the per-dir merge-files. The "dir" value is the current path
615 * relative to curr_dir (which might not be null-terminated). We copy it
616 * into dirbuf so that we can easily append a file name on the end. */
617 void *push_local_filters(const char *dir, unsigned int dirlen)
619 struct local_filter_state *push;
622 set_filter_dir(dir, dirlen);
623 if (DEBUG_GTE(FILTER, 2)) {
624 rprintf(FINFO, "[%s] pushing local filters for %s\n",
628 if (!mergelist_cnt) {
629 /* No old state to save and no new merge files to push. */
633 push = (struct local_filter_state *)new_array(char,
634 sizeof (struct local_filter_state)
635 + (mergelist_cnt-1) * sizeof (filter_rule_list));
637 push->mergelist_cnt = mergelist_cnt;
638 for (i = 0; i < mergelist_cnt; i++) {
639 filter_rule *ex = mergelist_parents[i];
642 memcpy(&push->mergelists[i], ex->u.mergelist, sizeof (filter_rule_list));
645 /* Note: parse_filter_file() might increase mergelist_cnt, so keep
646 * this loop separate from the above loop. */
647 for (i = 0; i < mergelist_cnt; i++) {
648 filter_rule *ex = mergelist_parents[i];
649 filter_rule_list *lp;
652 lp = ex->u.mergelist;
654 if (DEBUG_GTE(FILTER, 2)) {
655 rprintf(FINFO, "[%s] pushing mergelist #%d%s\n",
656 who_am_i(), i, lp->debug_type);
659 lp->tail = NULL; /* Switch any local rules to inherited. */
660 if (ex->rflags & FILTRULE_NO_INHERIT)
663 if (ex->rflags & FILTRULE_FINISH_SETUP) {
664 ex->rflags &= ~FILTRULE_FINISH_SETUP;
665 if (setup_merge_file(i, ex, lp))
666 set_filter_dir(dir, dirlen);
669 if (strlcpy(dirbuf + dirbuf_len, ex->pattern,
670 MAXPATHLEN - dirbuf_len) < MAXPATHLEN - dirbuf_len) {
671 parse_filter_file(lp, dirbuf, ex,
674 io_error |= IOERR_GENERAL;
676 "cannot add local filter rules in long-named directory: %s\n",
679 dirbuf[dirbuf_len] = '\0';
685 void pop_local_filters(void *mem)
687 struct local_filter_state *pop = (struct local_filter_state *)mem;
689 int old_mergelist_cnt = pop ? pop->mergelist_cnt : 0;
691 if (DEBUG_GTE(FILTER, 2))
692 rprintf(FINFO, "[%s] popping local filters\n", who_am_i());
694 for (i = mergelist_cnt; i-- > 0; ) {
695 filter_rule *ex = mergelist_parents[i];
696 filter_rule_list *lp;
699 lp = ex->u.mergelist;
701 if (DEBUG_GTE(FILTER, 2)) {
702 rprintf(FINFO, "[%s] popping mergelist #%d%s\n",
703 who_am_i(), i, lp->debug_type);
707 if (i >= old_mergelist_cnt && lp->head) {
708 /* This mergelist does not exist in the state to be restored, but it
709 * still has inherited rules. This can sometimes happen if a per-dir
710 * merge file calls setup_merge_file() in push_local_filters() and that
711 * leaves some inherited rules that aren't in the pushed list state. */
712 if (DEBUG_GTE(FILTER, 2)) {
713 rprintf(FINFO, "[%s] freeing parent_dirscan filters of mergelist #%d%s\n",
714 who_am_i(), i, ex->u.mergelist->debug_type);
721 return; /* No state to restore. */
723 for (i = 0; i < old_mergelist_cnt; i++) {
724 filter_rule *ex = mergelist_parents[i];
727 memcpy(ex->u.mergelist, &pop->mergelists[i], sizeof (filter_rule_list));
733 void change_local_filter_dir(const char *dname, int dlen, int dir_depth)
735 static int cur_depth = -1;
736 static void *filt_array[MAXPATHLEN/2+1];
739 for ( ; cur_depth >= 0; cur_depth--) {
740 if (filt_array[cur_depth]) {
741 pop_local_filters(filt_array[cur_depth]);
742 filt_array[cur_depth] = NULL;
748 assert(dir_depth < MAXPATHLEN/2+1);
750 for ( ; cur_depth >= dir_depth; cur_depth--) {
751 if (filt_array[cur_depth]) {
752 pop_local_filters(filt_array[cur_depth]);
753 filt_array[cur_depth] = NULL;
757 cur_depth = dir_depth;
758 filt_array[cur_depth] = push_local_filters(dname, dlen);
761 static int rule_matches(const char *fname, filter_rule *ex, int name_flags)
763 int slash_handling, str_cnt = 0, anchored_match = 0;
764 int ret_match = ex->rflags & FILTRULE_NEGATE ? 0 : 1;
765 char *p, *pattern = ex->pattern;
766 const char *strings[16]; /* more than enough */
767 const char *name = fname + (*fname == '/');
772 if (!(name_flags & NAME_IS_XATTR) ^ !(ex->rflags & FILTRULE_XATTR))
775 if (!ex->u.slash_cnt && !(ex->rflags & FILTRULE_WILD2)) {
776 /* If the pattern does not have any slashes AND it does
777 * not have a "**" (which could match a slash), then we
778 * just match the name portion of the path. */
779 if ((p = strrchr(name,'/')) != NULL)
781 } else if (ex->rflags & FILTRULE_ABS_PATH && *fname != '/'
782 && curr_dir_len > module_dirlen + 1) {
783 /* If we're matching against an absolute-path pattern,
784 * we need to prepend our full path info. */
785 strings[str_cnt++] = curr_dir + module_dirlen + 1;
786 strings[str_cnt++] = "/";
787 } else if (ex->rflags & FILTRULE_WILD2_PREFIX && *fname != '/') {
788 /* Allow "**"+"/" to match at the start of the string. */
789 strings[str_cnt++] = "/";
791 strings[str_cnt++] = name;
792 if (name_flags & NAME_IS_DIR) {
793 /* Allow a trailing "/"+"***" to match the directory. */
794 if (ex->rflags & FILTRULE_WILD3_SUFFIX)
795 strings[str_cnt++] = "/";
796 } else if (ex->rflags & FILTRULE_DIRECTORY)
798 strings[str_cnt] = NULL;
800 if (*pattern == '/') {
805 if (!anchored_match && ex->u.slash_cnt
806 && !(ex->rflags & FILTRULE_WILD2)) {
807 /* A non-anchored match with an infix slash and no "**"
808 * needs to match the last slash_cnt+1 name elements. */
809 slash_handling = ex->u.slash_cnt + 1;
810 } else if (!anchored_match && !(ex->rflags & FILTRULE_WILD2_PREFIX)
811 && ex->rflags & FILTRULE_WILD2) {
812 /* A non-anchored match with an infix or trailing "**" (but not
813 * a prefixed "**") needs to try matching after every slash. */
816 /* The pattern matches only at the start of the path or name. */
820 if (ex->rflags & FILTRULE_WILD) {
821 if (wildmatch_array(pattern, strings, slash_handling))
823 } else if (str_cnt > 1) {
824 if (litmatch_array(pattern, strings, slash_handling))
826 } else if (anchored_match) {
827 if (strcmp(name, pattern) == 0)
830 int l1 = strlen(name);
831 int l2 = strlen(pattern);
833 strcmp(name+(l1-l2),pattern) == 0 &&
834 (l1==l2 || name[l1-(l2+1)] == '/')) {
842 static void report_filter_result(enum logcode code, char const *name,
843 filter_rule const *ent,
844 int name_flags, const char *type)
846 int log_level = am_sender || am_generator ? 1 : 3;
848 /* If a trailing slash is present to match only directories,
849 * then it is stripped out by add_rule(). So as a special
850 * case we add it back in the log output. */
851 if (DEBUG_GTE(FILTER, log_level)) {
852 static char *actions[2][2]
853 = { {"show", "hid"}, {"risk", "protect"} };
854 const char *w = who_am_i();
855 const char *t = name_flags & NAME_IS_XATTR ? "xattr"
856 : name_flags & NAME_IS_DIR ? "directory"
858 rprintf(code, "[%s] %sing %s %s because of pattern %s%s%s\n",
859 w, actions[*w=='g'][!(ent->rflags & FILTRULE_INCLUDE)],
860 t, name, ent->pattern,
861 ent->rflags & FILTRULE_DIRECTORY ? "/" : "", type);
865 /* This function is used to check if a file should be included/excluded
866 * from the list of files based on its name and type etc. The value of
867 * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
868 int name_is_excluded(const char *fname, int name_flags, int filter_level)
870 if (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, name_flags) < 0) {
871 if (!(name_flags & NAME_IS_XATTR))
876 if (filter_level != ALL_FILTERS)
879 if (filter_list.head && check_filter(&filter_list, FINFO, fname, name_flags) < 0)
885 /* Return -1 if file "name" is defined to be excluded by the specified
886 * exclude list, 1 if it is included, and 0 if it was not matched. */
887 int check_filter(filter_rule_list *listp, enum logcode code,
888 const char *name, int name_flags)
892 for (ent = listp->head; ent; ent = ent->next) {
893 if (ignore_perishable && ent->rflags & FILTRULE_PERISHABLE)
895 if (ent->rflags & FILTRULE_PERDIR_MERGE) {
896 int rc = check_filter(ent->u.mergelist, code, name, name_flags);
901 if (ent->rflags & FILTRULE_CVS_IGNORE) {
902 int rc = check_filter(&cvs_filter_list, code, name, name_flags);
907 if (rule_matches(name, ent, name_flags)) {
908 report_filter_result(code, name, ent, name_flags, listp->debug_type);
909 return ent->rflags & FILTRULE_INCLUDE ? 1 : -1;
916 #define RULE_STRCMP(s,r) rule_strcmp((s), (r), sizeof (r) - 1)
918 static const uchar *rule_strcmp(const uchar *str, const char *rule, int rule_len)
920 if (strncmp((char*)str, rule, rule_len) != 0)
922 if (isspace(str[rule_len]) || str[rule_len] == '_' || !str[rule_len])
923 return str + rule_len - 1;
924 if (str[rule_len] == ',')
925 return str + rule_len;
929 #define FILTRULES_FROM_CONTAINER (FILTRULE_ABS_PATH | FILTRULE_INCLUDE \
930 | FILTRULE_DIRECTORY | FILTRULE_NEGATE \
931 | FILTRULE_PERISHABLE)
933 /* Gets the next include/exclude rule from *rulestr_ptr and advances
934 * *rulestr_ptr to point beyond it. Stores the pattern's start (within
935 * *rulestr_ptr) and length in *pat_ptr and *pat_len_ptr, and returns a newly
936 * allocated filter_rule containing the rest of the information. Returns
937 * NULL if there are no more rules in the input.
939 * The template provides defaults for the new rule to inherit, and the
940 * template rflags and the xflags additionally affect parsing. */
941 static filter_rule *parse_rule_tok(const char **rulestr_ptr,
942 const filter_rule *template, int xflags,
943 const char **pat_ptr, unsigned int *pat_len_ptr)
945 const uchar *s = (const uchar *)*rulestr_ptr;
949 if (template->rflags & FILTRULE_WORD_SPLIT) {
950 /* Skip over any initial whitespace. */
953 /* Update to point to real start of rule. */
954 *rulestr_ptr = (const char *)s;
959 rule = new0(filter_rule);
961 /* Inherit from the template. Don't inherit FILTRULES_SIDES; we check
963 rule->rflags = template->rflags & FILTRULES_FROM_CONTAINER;
965 /* Figure out what kind of a filter rule "s" is pointing at. Note
966 * that if FILTRULE_NO_PREFIXES is set, the rule is either an include
967 * or an exclude based on the inheritance of the FILTRULE_INCLUDE
968 * flag (above). XFLG_OLD_PREFIXES indicates a compatibility mode
969 * for old include/exclude patterns where just "+ " and "- " are
970 * allowed as optional prefixes. */
971 if (template->rflags & FILTRULE_NO_PREFIXES) {
972 if (*s == '!' && template->rflags & FILTRULE_CVS_IGNORE)
973 rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
974 } else if (xflags & XFLG_OLD_PREFIXES) {
975 if (*s == '-' && s[1] == ' ') {
976 rule->rflags &= ~FILTRULE_INCLUDE;
978 } else if (*s == '+' && s[1] == ' ') {
979 rule->rflags |= FILTRULE_INCLUDE;
981 } else if (*s == '!')
982 rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
985 BOOL prefix_specifies_side = False;
988 if ((s = RULE_STRCMP(s, "clear")) != NULL)
992 if ((s = RULE_STRCMP(s, "dir-merge")) != NULL)
996 if ((s = RULE_STRCMP(s, "exclude")) != NULL)
1000 if ((s = RULE_STRCMP(s, "hide")) != NULL)
1004 if ((s = RULE_STRCMP(s, "include")) != NULL)
1008 if ((s = RULE_STRCMP(s, "merge")) != NULL)
1012 if ((s = RULE_STRCMP(s, "protect")) != NULL)
1016 if ((s = RULE_STRCMP(s, "risk")) != NULL)
1020 if ((s = RULE_STRCMP(s, "show")) != NULL)
1031 trust_sender_filter = 1;
1032 rule->rflags |= FILTRULE_PERDIR_MERGE
1033 | FILTRULE_FINISH_SETUP;
1036 rule->rflags |= FILTRULE_MERGE_FILE;
1039 rule->rflags |= FILTRULE_INCLUDE;
1044 rule->rflags |= FILTRULE_INCLUDE;
1047 rule->rflags |= FILTRULE_SENDER_SIDE;
1048 prefix_specifies_side = True;
1051 rule->rflags |= FILTRULE_INCLUDE;
1054 rule->rflags |= FILTRULE_RECEIVER_SIDE;
1055 prefix_specifies_side = True;
1058 rule->rflags |= FILTRULE_CLEAR_LIST;
1061 rprintf(FERROR, "Unknown filter rule: `%s'\n", *rulestr_ptr);
1062 exit_cleanup(RERR_SYNTAX);
1064 while (ch != '!' && *++s && *s != ' ' && *s != '_') {
1065 if (template->rflags & FILTRULE_WORD_SPLIT && isspace(*s)) {
1073 "invalid modifier '%c' at position %d in filter rule: %s\n",
1074 *s, (int)(s - (const uchar *)*rulestr_ptr), *rulestr_ptr);
1075 exit_cleanup(RERR_SYNTAX);
1077 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
1079 rule->rflags |= FILTRULE_NO_PREFIXES;
1082 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
1084 rule->rflags |= FILTRULE_NO_PREFIXES
1088 rule->rflags |= FILTRULE_ABS_PATH;
1091 /* Negation really goes with the pattern, so it
1092 * isn't useful as a merge-file default. */
1093 if (rule->rflags & FILTRULE_MERGE_FILE)
1095 rule->rflags |= FILTRULE_NEGATE;
1098 if (rule->rflags & FILTRULE_NO_PREFIXES || prefix_specifies_side)
1100 rule->rflags |= FILTRULE_NO_PREFIXES
1101 | FILTRULE_WORD_SPLIT
1102 | FILTRULE_NO_INHERIT
1103 | FILTRULE_CVS_IGNORE;
1106 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1108 rule->rflags |= FILTRULE_EXCLUDE_SELF;
1111 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1113 rule->rflags |= FILTRULE_NO_INHERIT;
1116 rule->rflags |= FILTRULE_PERISHABLE;
1119 if (prefix_specifies_side)
1121 rule->rflags |= FILTRULE_RECEIVER_SIDE;
1124 if (prefix_specifies_side)
1126 rule->rflags |= FILTRULE_SENDER_SIDE;
1129 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1131 rule->rflags |= FILTRULE_WORD_SPLIT;
1134 rule->rflags |= FILTRULE_XATTR;
1135 saw_xattr_filter = 1;
1142 if (template->rflags & FILTRULES_SIDES) {
1143 if (rule->rflags & FILTRULES_SIDES) {
1144 /* The filter and template both specify side(s). This
1145 * is dodgy (and won't work correctly if the template is
1146 * a one-sided per-dir merge rule), so reject it. */
1148 "specified-side merge file contains specified-side filter: %s\n",
1150 exit_cleanup(RERR_SYNTAX);
1152 rule->rflags |= template->rflags & FILTRULES_SIDES;
1155 if (template->rflags & FILTRULE_WORD_SPLIT) {
1156 const uchar *cp = s;
1157 /* Token ends at whitespace or the end of the string. */
1158 while (!isspace(*cp) && *cp != '\0')
1162 len = strlen((char*)s);
1164 if (rule->rflags & FILTRULE_CLEAR_LIST) {
1165 if (!(rule->rflags & FILTRULE_NO_PREFIXES)
1166 && !(xflags & XFLG_OLD_PREFIXES) && len) {
1168 "'!' rule has trailing characters: %s\n", *rulestr_ptr);
1169 exit_cleanup(RERR_SYNTAX);
1172 rule->rflags &= ~FILTRULE_CLEAR_LIST;
1173 } else if (!len && !(rule->rflags & FILTRULE_CVS_IGNORE)) {
1174 rprintf(FERROR, "unexpected end of filter rule: %s\n", *rulestr_ptr);
1175 exit_cleanup(RERR_SYNTAX);
1178 /* --delete-excluded turns an un-modified include/exclude into a sender-side rule. */
1180 && !(rule->rflags & (FILTRULES_SIDES|FILTRULE_MERGE_FILE|FILTRULE_PERDIR_MERGE)))
1181 rule->rflags |= FILTRULE_SENDER_SIDE;
1183 *pat_ptr = (const char *)s;
1185 *rulestr_ptr = *pat_ptr + len;
1189 static void get_cvs_excludes(uint32 rflags)
1191 static int initialized = 0;
1192 char *p, fname[MAXPATHLEN];
1198 parse_filter_str(&cvs_filter_list, default_cvsignore(),
1199 rule_template(rflags | (protocol_version >= 30 ? FILTRULE_PERISHABLE : 0)),
1202 p = module_id >= 0 && lp_use_chroot(module_id) ? "/" : getenv("HOME");
1203 if (p && pathjoin(fname, MAXPATHLEN, p, ".cvsignore") < MAXPATHLEN)
1204 parse_filter_file(&cvs_filter_list, fname, rule_template(rflags), 0);
1206 parse_filter_str(&cvs_filter_list, getenv("CVSIGNORE"), rule_template(rflags), 0);
1209 const filter_rule *rule_template(uint32 rflags)
1211 static filter_rule template; /* zero-initialized */
1212 template.rflags = rflags;
1216 void parse_filter_str(filter_rule_list *listp, const char *rulestr,
1217 const filter_rule *template, int xflags)
1221 unsigned int pat_len;
1229 /* Remember that the returned string is NOT '\0' terminated! */
1230 if (!(rule = parse_rule_tok(&rulestr, template, xflags, &pat, &pat_len)))
1233 if (pat_len >= MAXPATHLEN) {
1234 rprintf(FERROR, "discarding over-long filter: %.*s\n",
1241 new_rflags = rule->rflags;
1242 if (new_rflags & FILTRULE_CLEAR_LIST) {
1243 if (DEBUG_GTE(FILTER, 2)) {
1245 "[%s] clearing filter list%s\n",
1246 who_am_i(), listp->debug_type);
1248 pop_filter_list(listp);
1253 if (new_rflags & FILTRULE_MERGE_FILE) {
1258 if (new_rflags & FILTRULE_EXCLUDE_SELF) {
1260 filter_rule *excl_self;
1262 excl_self = new0(filter_rule);
1263 /* Find the beginning of the basename and add an exclude for it. */
1264 for (name = pat + pat_len; name > pat && name[-1] != '/'; name--) {}
1265 add_rule(listp, name, (pat + pat_len) - name, excl_self, 0);
1266 rule->rflags &= ~FILTRULE_EXCLUDE_SELF;
1268 if (new_rflags & FILTRULE_PERDIR_MERGE) {
1269 if (parent_dirscan) {
1271 unsigned int len = pat_len;
1272 if ((p = parse_merge_name(pat, &len, module_dirlen)))
1273 add_rule(listp, p, len, rule, 0);
1280 unsigned int len = pat_len;
1281 if ((p = parse_merge_name(pat, &len, 0)))
1282 parse_filter_file(listp, p, rule, XFLG_FATAL_ERRORS);
1288 add_rule(listp, pat, pat_len, rule, xflags);
1290 if (new_rflags & FILTRULE_CVS_IGNORE
1291 && !(new_rflags & FILTRULE_MERGE_FILE))
1292 get_cvs_excludes(new_rflags);
1296 void parse_filter_file(filter_rule_list *listp, const char *fname, const filter_rule *template, int xflags)
1299 char line[BIGPATHBUFLEN];
1300 char *eob = line + sizeof line - 1;
1301 BOOL word_split = (template->rflags & FILTRULE_WORD_SPLIT) != 0;
1303 if (!fname || !*fname)
1306 if (*fname != '-' || fname[1] || am_server) {
1307 if (daemon_filter_list.head) {
1308 strlcpy(line, fname, sizeof line);
1309 clean_fname(line, CFN_COLLAPSE_DOT_DOT_DIRS);
1310 if (check_filter(&daemon_filter_list, FLOG, line, 0) < 0)
1313 fp = fopen(line, "rb");
1315 fp = fopen(fname, "rb");
1319 if (DEBUG_GTE(FILTER, 2)) {
1320 rprintf(FINFO, "[%s] parse_filter_file(%s,%x,%x)%s\n",
1321 who_am_i(), fname, template->rflags, xflags,
1322 fp ? "" : " [not found]");
1326 if (xflags & XFLG_FATAL_ERRORS) {
1327 rsyserr(FERROR, errno,
1328 "failed to open %sclude file %s",
1329 template->rflags & FILTRULE_INCLUDE ? "in" : "ex",
1331 exit_cleanup(RERR_FILEIO);
1335 dirbuf[dirbuf_len] = '\0';
1339 int ch, overflow = 0;
1341 if ((ch = getc(fp)) == EOF) {
1342 if (ferror(fp) && errno == EINTR) {
1348 if (word_split && isspace(ch))
1350 if (eol_nulls? !ch : (ch == '\n' || ch == '\r'))
1358 rprintf(FERROR, "discarding over-long filter: %s...\n", line);
1362 /* Skip an empty token and (when line parsing) comments. */
1363 if (*line && (word_split || (*line != ';' && *line != '#')))
1364 parse_filter_str(listp, line, template, xflags);
1371 /* If the "for_xfer" flag is set, the prefix is made compatible with the
1372 * current protocol_version (if possible) or a NULL is returned (if not
1374 char *get_rule_prefix(filter_rule *rule, const char *pat, int for_xfer,
1375 unsigned int *plen_ptr)
1377 static char buf[MAX_RULE_PREFIX+1];
1379 int legal_len = for_xfer && protocol_version < 29 ? 1 : MAX_RULE_PREFIX-1;
1381 if (rule->rflags & FILTRULE_PERDIR_MERGE) {
1385 } else if (rule->rflags & FILTRULE_INCLUDE)
1387 else if (legal_len != 1
1388 || ((*pat == '-' || *pat == '+') && pat[1] == ' '))
1393 if (rule->rflags & FILTRULE_ABS_PATH)
1395 if (rule->rflags & FILTRULE_NEGATE)
1397 if (rule->rflags & FILTRULE_CVS_IGNORE)
1400 if (rule->rflags & FILTRULE_NO_INHERIT)
1402 if (rule->rflags & FILTRULE_WORD_SPLIT)
1404 if (rule->rflags & FILTRULE_NO_PREFIXES) {
1405 if (rule->rflags & FILTRULE_INCLUDE)
1411 if (rule->rflags & FILTRULE_EXCLUDE_SELF)
1413 if (rule->rflags & FILTRULE_XATTR)
1415 if (rule->rflags & FILTRULE_SENDER_SIDE
1416 && (!for_xfer || protocol_version >= 29))
1418 if (rule->rflags & FILTRULE_RECEIVER_SIDE
1419 && (!for_xfer || protocol_version >= 29
1420 || (delete_excluded && am_sender)))
1422 if (rule->rflags & FILTRULE_PERISHABLE) {
1423 if (!for_xfer || protocol_version >= 30)
1428 if (op - buf > legal_len)
1434 *plen_ptr = op - buf;
1438 static void send_rules(int f_out, filter_rule_list *flp)
1440 filter_rule *ent, *prev = NULL;
1442 for (ent = flp->head; ent; ent = ent->next) {
1443 unsigned int len, plen, dlen;
1447 /* Note we need to check delete_excluded here in addition to
1448 * the code in parse_rule_tok() because some rules may have
1449 * been added before we found the --delete-excluded option.
1450 * We must also elide any CVS merge-file rules to avoid a
1451 * backward compatibility problem, and we elide any no-prefix
1452 * merge files as an optimization (since they can only have
1453 * include/exclude rules). */
1454 if (ent->rflags & FILTRULE_SENDER_SIDE)
1455 elide = am_sender ? 1 : -1;
1456 if (ent->rflags & FILTRULE_RECEIVER_SIDE)
1457 elide = elide ? 0 : am_sender ? -1 : 1;
1458 else if (delete_excluded && !elide
1459 && (!(ent->rflags & FILTRULE_PERDIR_MERGE)
1460 || ent->rflags & FILTRULE_NO_PREFIXES))
1461 elide = am_sender ? 1 : -1;
1464 prev->next = ent->next;
1466 flp->head = ent->next;
1471 if (ent->rflags & FILTRULE_CVS_IGNORE
1472 && !(ent->rflags & FILTRULE_MERGE_FILE)) {
1473 int f = am_sender || protocol_version < 29 ? f_out : -2;
1474 send_rules(f, &cvs_filter_list);
1478 p = get_rule_prefix(ent, ent->pattern, 1, &plen);
1481 "filter rules are too modern for remote rsync.\n");
1482 exit_cleanup(RERR_PROTOCOL);
1486 len = strlen(ent->pattern);
1487 dlen = ent->rflags & FILTRULE_DIRECTORY ? 1 : 0;
1488 if (!(plen + len + dlen))
1490 write_int(f_out, plen + len + dlen);
1492 write_buf(f_out, p, plen);
1493 write_buf(f_out, ent->pattern, len);
1495 write_byte(f_out, '/');
1500 /* This is only called by the client. */
1501 void send_filter_list(int f_out)
1503 int receiver_wants_list = prune_empty_dirs
1504 || (delete_mode && (!delete_excluded || protocol_version >= 29));
1506 if (local_server || (am_sender && !receiver_wants_list))
1508 if (cvs_exclude && am_sender) {
1509 if (protocol_version >= 29)
1510 parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1511 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1514 send_rules(f_out, &filter_list);
1517 write_int(f_out, 0);
1520 if (!am_sender || protocol_version < 29)
1521 parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1523 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1527 /* This is only called by the server. */
1528 void recv_filter_list(int f_in)
1530 char line[BIGPATHBUFLEN];
1531 int xflags = protocol_version >= 29 ? 0 : XFLG_OLD_PREFIXES;
1532 int receiver_wants_list = prune_empty_dirs
1533 || (delete_mode && (!delete_excluded || protocol_version >= 29));
1536 if (!local_server && (am_sender || receiver_wants_list)) {
1537 while ((len = read_int(f_in)) != 0) {
1538 if (len >= sizeof line)
1539 overflow_exit("recv_rules");
1540 read_sbuf(f_in, line, len);
1541 parse_filter_str(&filter_list, line, rule_template(0), xflags);
1546 if (local_server || am_sender || protocol_version < 29)
1547 parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1548 if (local_server || am_sender)
1549 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1552 if (local_server) /* filter out any rules that aren't for us. */
1553 send_rules(-1, &filter_list);