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