Preparing for release of 3.2.7pre1
[rsync.git] / exclude.c
blobffe55b167edfdbe1325bcfdbe178f8b7b7017504
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-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.
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 strlcpy(save, y, MAXPATHLEN);
724 *y = '\0';
725 dirbuf_len = y - dirbuf;
726 strlcpy(x, ex->pattern, MAXPATHLEN - (x - buf));
727 parse_filter_file(lp, buf, ex, XFLG_ANCHORED2ABS);
728 if (ex->rflags & FILTRULE_NO_INHERIT) {
729 /* Free the undesired rules to clean up any per-dir
730 * mergelists they defined. Otherwise pop_local_filters
731 * may crash trying to restore nonexistent state for
732 * those mergelists. */
733 free_filters(lp->head);
734 lp->head = NULL;
736 lp->tail = NULL;
737 strlcpy(y, save, MAXPATHLEN);
738 while ((*x++ = *y++) != '/') {}
740 parent_dirscan = False;
741 if (DEBUG_GTE(FILTER, 2)) {
742 rprintf(FINFO, "[%s] completed parent_dirscan for mergelist #%d%s\n",
743 who_am_i(), mergelist_num, lp->debug_type);
745 free(pat);
746 return 1;
749 struct local_filter_state {
750 int mergelist_cnt;
751 filter_rule_list mergelists[1];
754 /* Each time rsync changes to a new directory it call this function to
755 * handle all the per-dir merge-files. The "dir" value is the current path
756 * relative to curr_dir (which might not be null-terminated). We copy it
757 * into dirbuf so that we can easily append a file name on the end. */
758 void *push_local_filters(const char *dir, unsigned int dirlen)
760 struct local_filter_state *push;
761 int i;
763 set_filter_dir(dir, dirlen);
764 if (DEBUG_GTE(FILTER, 2)) {
765 rprintf(FINFO, "[%s] pushing local filters for %s\n",
766 who_am_i(), dirbuf);
769 if (!mergelist_cnt) {
770 /* No old state to save and no new merge files to push. */
771 return NULL;
774 push = (struct local_filter_state *)new_array(char,
775 sizeof (struct local_filter_state)
776 + (mergelist_cnt-1) * sizeof (filter_rule_list));
778 push->mergelist_cnt = mergelist_cnt;
779 for (i = 0; i < mergelist_cnt; i++) {
780 filter_rule *ex = mergelist_parents[i];
781 if (!ex)
782 continue;
783 memcpy(&push->mergelists[i], ex->u.mergelist, sizeof (filter_rule_list));
786 /* Note: parse_filter_file() might increase mergelist_cnt, so keep
787 * this loop separate from the above loop. */
788 for (i = 0; i < mergelist_cnt; i++) {
789 filter_rule *ex = mergelist_parents[i];
790 filter_rule_list *lp;
791 if (!ex)
792 continue;
793 lp = ex->u.mergelist;
795 if (DEBUG_GTE(FILTER, 2)) {
796 rprintf(FINFO, "[%s] pushing mergelist #%d%s\n",
797 who_am_i(), i, lp->debug_type);
800 lp->tail = NULL; /* Switch any local rules to inherited. */
801 if (ex->rflags & FILTRULE_NO_INHERIT)
802 lp->head = NULL;
804 if (ex->rflags & FILTRULE_FINISH_SETUP) {
805 ex->rflags &= ~FILTRULE_FINISH_SETUP;
806 if (setup_merge_file(i, ex, lp))
807 set_filter_dir(dir, dirlen);
810 if (strlcpy(dirbuf + dirbuf_len, ex->pattern,
811 MAXPATHLEN - dirbuf_len) < MAXPATHLEN - dirbuf_len) {
812 parse_filter_file(lp, dirbuf, ex,
813 XFLG_ANCHORED2ABS);
814 } else {
815 io_error |= IOERR_GENERAL;
816 rprintf(FERROR,
817 "cannot add local filter rules in long-named directory: %s\n",
818 full_fname(dirbuf));
820 dirbuf[dirbuf_len] = '\0';
823 return (void*)push;
826 void pop_local_filters(void *mem)
828 struct local_filter_state *pop = (struct local_filter_state *)mem;
829 int i;
830 int old_mergelist_cnt = pop ? pop->mergelist_cnt : 0;
832 if (DEBUG_GTE(FILTER, 2))
833 rprintf(FINFO, "[%s] popping local filters\n", who_am_i());
835 for (i = mergelist_cnt; i-- > 0; ) {
836 filter_rule *ex = mergelist_parents[i];
837 filter_rule_list *lp;
838 if (!ex)
839 continue;
840 lp = ex->u.mergelist;
842 if (DEBUG_GTE(FILTER, 2)) {
843 rprintf(FINFO, "[%s] popping mergelist #%d%s\n",
844 who_am_i(), i, lp->debug_type);
847 pop_filter_list(lp);
848 if (i >= old_mergelist_cnt && lp->head) {
849 /* This mergelist does not exist in the state to be restored, but it
850 * still has inherited rules. This can sometimes happen if a per-dir
851 * merge file calls setup_merge_file() in push_local_filters() and that
852 * leaves some inherited rules that aren't in the pushed list state. */
853 if (DEBUG_GTE(FILTER, 2)) {
854 rprintf(FINFO, "[%s] freeing parent_dirscan filters of mergelist #%d%s\n",
855 who_am_i(), i, ex->u.mergelist->debug_type);
857 pop_filter_list(lp);
861 if (!pop)
862 return; /* No state to restore. */
864 for (i = 0; i < old_mergelist_cnt; i++) {
865 filter_rule *ex = mergelist_parents[i];
866 if (!ex)
867 continue;
868 memcpy(ex->u.mergelist, &pop->mergelists[i], sizeof (filter_rule_list));
871 free(pop);
874 void change_local_filter_dir(const char *dname, int dlen, int dir_depth)
876 static int cur_depth = -1;
877 static void *filt_array[MAXPATHLEN/2+1];
879 if (!dname) {
880 for ( ; cur_depth >= 0; cur_depth--) {
881 if (filt_array[cur_depth]) {
882 pop_local_filters(filt_array[cur_depth]);
883 filt_array[cur_depth] = NULL;
886 return;
889 assert(dir_depth < MAXPATHLEN/2+1);
891 for ( ; cur_depth >= dir_depth; cur_depth--) {
892 if (filt_array[cur_depth]) {
893 pop_local_filters(filt_array[cur_depth]);
894 filt_array[cur_depth] = NULL;
898 cur_depth = dir_depth;
899 filt_array[cur_depth] = push_local_filters(dname, dlen);
902 static int rule_matches(const char *fname, filter_rule *ex, int name_flags)
904 int slash_handling, str_cnt = 0, anchored_match = 0;
905 int ret_match = ex->rflags & FILTRULE_NEGATE ? 0 : 1;
906 char *p, *pattern = ex->pattern;
907 const char *strings[16]; /* more than enough */
908 const char *name = fname + (*fname == '/');
910 if (!*name || ex->elide == cur_elide_value)
911 return 0;
913 if (!(name_flags & NAME_IS_XATTR) ^ !(ex->rflags & FILTRULE_XATTR))
914 return 0;
916 if (!ex->u.slash_cnt && !(ex->rflags & FILTRULE_WILD2)) {
917 /* If the pattern does not have any slashes AND it does
918 * not have a "**" (which could match a slash), then we
919 * just match the name portion of the path. */
920 if ((p = strrchr(name,'/')) != NULL)
921 name = p+1;
922 } else if (ex->rflags & FILTRULE_ABS_PATH && *fname != '/'
923 && curr_dir_len > module_dirlen + 1) {
924 /* If we're matching against an absolute-path pattern,
925 * we need to prepend our full path info. */
926 strings[str_cnt++] = curr_dir + module_dirlen + 1;
927 strings[str_cnt++] = "/";
928 } else if (ex->rflags & FILTRULE_WILD2_PREFIX && *fname != '/') {
929 /* Allow "**"+"/" to match at the start of the string. */
930 strings[str_cnt++] = "/";
932 strings[str_cnt++] = name;
933 if (name_flags & NAME_IS_DIR) {
934 /* Allow a trailing "/"+"***" to match the directory. */
935 if (ex->rflags & FILTRULE_WILD3_SUFFIX)
936 strings[str_cnt++] = "/";
937 } else if (ex->rflags & FILTRULE_DIRECTORY)
938 return !ret_match;
939 strings[str_cnt] = NULL;
941 if (*pattern == '/') {
942 anchored_match = 1;
943 pattern++;
946 if (!anchored_match && ex->u.slash_cnt
947 && !(ex->rflags & FILTRULE_WILD2)) {
948 /* A non-anchored match with an infix slash and no "**"
949 * needs to match the last slash_cnt+1 name elements. */
950 slash_handling = ex->u.slash_cnt + 1;
951 } else if (!anchored_match && !(ex->rflags & FILTRULE_WILD2_PREFIX)
952 && ex->rflags & FILTRULE_WILD2) {
953 /* A non-anchored match with an infix or trailing "**" (but not
954 * a prefixed "**") needs to try matching after every slash. */
955 slash_handling = -1;
956 } else {
957 /* The pattern matches only at the start of the path or name. */
958 slash_handling = 0;
961 if (ex->rflags & FILTRULE_WILD) {
962 if (wildmatch_array(pattern, strings, slash_handling))
963 return ret_match;
964 } else if (str_cnt > 1) {
965 if (litmatch_array(pattern, strings, slash_handling))
966 return ret_match;
967 } else if (anchored_match) {
968 if (strcmp(name, pattern) == 0)
969 return ret_match;
970 } else {
971 int l1 = strlen(name);
972 int l2 = strlen(pattern);
973 if (l2 <= l1 &&
974 strcmp(name+(l1-l2),pattern) == 0 &&
975 (l1==l2 || name[l1-(l2+1)] == '/')) {
976 return ret_match;
980 return !ret_match;
983 static void report_filter_result(enum logcode code, char const *name,
984 filter_rule const *ent,
985 int name_flags, const char *type)
987 int log_level = am_sender || am_generator ? 1 : 3;
989 /* If a trailing slash is present to match only directories,
990 * then it is stripped out by add_rule(). So as a special
991 * case we add it back in the log output. */
992 if (DEBUG_GTE(FILTER, log_level)) {
993 static char *actions[2][2]
994 = { {"show", "hid"}, {"risk", "protect"} };
995 const char *w = who_am_i();
996 const char *t = name_flags & NAME_IS_XATTR ? "xattr"
997 : name_flags & NAME_IS_DIR ? "directory"
998 : "file";
999 rprintf(code, "[%s] %sing %s %s because of pattern %s%s%s\n",
1000 w, actions[*w=='g'][!(ent->rflags & FILTRULE_INCLUDE)],
1001 t, name, ent->pattern,
1002 ent->rflags & FILTRULE_DIRECTORY ? "/" : "", type);
1006 /* This function is used to check if a file should be included/excluded
1007 * from the list of files based on its name and type etc. The value of
1008 * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
1009 int name_is_excluded(const char *fname, int name_flags, int filter_level)
1011 if (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, name_flags) < 0) {
1012 if (!(name_flags & NAME_IS_XATTR))
1013 errno = ENOENT;
1014 return 1;
1017 if (filter_level != ALL_FILTERS)
1018 return 0;
1020 if (filter_list.head && check_filter(&filter_list, FINFO, fname, name_flags) < 0)
1021 return 1;
1023 return 0;
1026 int check_server_filter(filter_rule_list *listp, enum logcode code, const char *name, int name_flags)
1028 int ret;
1029 cur_elide_value = LOCAL_RULE;
1030 ret = check_filter(listp, code, name, name_flags);
1031 cur_elide_value = REMOTE_RULE;
1032 return ret;
1035 /* Return -1 if file "name" is defined to be excluded by the specified
1036 * exclude list, 1 if it is included, and 0 if it was not matched. */
1037 int check_filter(filter_rule_list *listp, enum logcode code,
1038 const char *name, int name_flags)
1040 filter_rule *ent;
1042 for (ent = listp->head; ent; ent = ent->next) {
1043 if (ignore_perishable && ent->rflags & FILTRULE_PERISHABLE)
1044 continue;
1045 if (ent->rflags & FILTRULE_PERDIR_MERGE) {
1046 int rc = check_filter(ent->u.mergelist, code, name, name_flags);
1047 if (rc)
1048 return rc;
1049 continue;
1051 if (ent->rflags & FILTRULE_CVS_IGNORE) {
1052 int rc = check_filter(&cvs_filter_list, code, name, name_flags);
1053 if (rc)
1054 return rc;
1055 continue;
1057 if (rule_matches(name, ent, name_flags)) {
1058 report_filter_result(code, name, ent, name_flags, listp->debug_type);
1059 return ent->rflags & FILTRULE_INCLUDE ? 1 : -1;
1063 return 0;
1066 #define RULE_STRCMP(s,r) rule_strcmp((s), (r), sizeof (r) - 1)
1068 static const uchar *rule_strcmp(const uchar *str, const char *rule, int rule_len)
1070 if (strncmp((char*)str, rule, rule_len) != 0)
1071 return NULL;
1072 if (isspace(str[rule_len]) || str[rule_len] == '_' || !str[rule_len])
1073 return str + rule_len - 1;
1074 if (str[rule_len] == ',')
1075 return str + rule_len;
1076 return NULL;
1079 #define FILTRULES_FROM_CONTAINER (FILTRULE_ABS_PATH | FILTRULE_INCLUDE \
1080 | FILTRULE_DIRECTORY | FILTRULE_NEGATE \
1081 | FILTRULE_PERISHABLE)
1083 /* Gets the next include/exclude rule from *rulestr_ptr and advances
1084 * *rulestr_ptr to point beyond it. Stores the pattern's start (within
1085 * *rulestr_ptr) and length in *pat_ptr and *pat_len_ptr, and returns a newly
1086 * allocated filter_rule containing the rest of the information. Returns
1087 * NULL if there are no more rules in the input.
1089 * The template provides defaults for the new rule to inherit, and the
1090 * template rflags and the xflags additionally affect parsing. */
1091 static filter_rule *parse_rule_tok(const char **rulestr_ptr,
1092 const filter_rule *template, int xflags,
1093 const char **pat_ptr, unsigned int *pat_len_ptr)
1095 const uchar *s = (const uchar *)*rulestr_ptr;
1096 filter_rule *rule;
1097 unsigned int len;
1099 if (template->rflags & FILTRULE_WORD_SPLIT) {
1100 /* Skip over any initial whitespace. */
1101 while (isspace(*s))
1102 s++;
1103 /* Update to point to real start of rule. */
1104 *rulestr_ptr = (const char *)s;
1106 if (!*s)
1107 return NULL;
1109 rule = new0(filter_rule);
1111 /* Inherit from the template. Don't inherit FILTRULES_SIDES; we check
1112 * that later. */
1113 rule->rflags = template->rflags & FILTRULES_FROM_CONTAINER;
1115 /* Figure out what kind of a filter rule "s" is pointing at. Note
1116 * that if FILTRULE_NO_PREFIXES is set, the rule is either an include
1117 * or an exclude based on the inheritance of the FILTRULE_INCLUDE
1118 * flag (above). XFLG_OLD_PREFIXES indicates a compatibility mode
1119 * for old include/exclude patterns where just "+ " and "- " are
1120 * allowed as optional prefixes. */
1121 if (template->rflags & FILTRULE_NO_PREFIXES) {
1122 if (*s == '!' && template->rflags & FILTRULE_CVS_IGNORE)
1123 rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
1124 } else if (xflags & XFLG_OLD_PREFIXES) {
1125 if (*s == '-' && s[1] == ' ') {
1126 rule->rflags &= ~FILTRULE_INCLUDE;
1127 s += 2;
1128 } else if (*s == '+' && s[1] == ' ') {
1129 rule->rflags |= FILTRULE_INCLUDE;
1130 s += 2;
1131 } else if (*s == '!')
1132 rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
1133 } else {
1134 char ch = 0;
1135 BOOL prefix_specifies_side = False;
1136 switch (*s) {
1137 case 'c':
1138 if ((s = RULE_STRCMP(s, "clear")) != NULL)
1139 ch = '!';
1140 break;
1141 case 'd':
1142 if ((s = RULE_STRCMP(s, "dir-merge")) != NULL)
1143 ch = ':';
1144 break;
1145 case 'e':
1146 if ((s = RULE_STRCMP(s, "exclude")) != NULL)
1147 ch = '-';
1148 break;
1149 case 'h':
1150 if ((s = RULE_STRCMP(s, "hide")) != NULL)
1151 ch = 'H';
1152 break;
1153 case 'i':
1154 if ((s = RULE_STRCMP(s, "include")) != NULL)
1155 ch = '+';
1156 break;
1157 case 'm':
1158 if ((s = RULE_STRCMP(s, "merge")) != NULL)
1159 ch = '.';
1160 break;
1161 case 'p':
1162 if ((s = RULE_STRCMP(s, "protect")) != NULL)
1163 ch = 'P';
1164 break;
1165 case 'r':
1166 if ((s = RULE_STRCMP(s, "risk")) != NULL)
1167 ch = 'R';
1168 break;
1169 case 's':
1170 if ((s = RULE_STRCMP(s, "show")) != NULL)
1171 ch = 'S';
1172 break;
1173 default:
1174 ch = *s;
1175 if (s[1] == ',')
1176 s++;
1177 break;
1179 switch (ch) {
1180 case ':':
1181 trust_sender_filter = 1;
1182 rule->rflags |= FILTRULE_PERDIR_MERGE
1183 | FILTRULE_FINISH_SETUP;
1184 /* FALL THROUGH */
1185 case '.':
1186 rule->rflags |= FILTRULE_MERGE_FILE;
1187 break;
1188 case '+':
1189 rule->rflags |= FILTRULE_INCLUDE;
1190 break;
1191 case '-':
1192 break;
1193 case 'S':
1194 rule->rflags |= FILTRULE_INCLUDE;
1195 /* FALL THROUGH */
1196 case 'H':
1197 rule->rflags |= FILTRULE_SENDER_SIDE;
1198 prefix_specifies_side = True;
1199 break;
1200 case 'R':
1201 rule->rflags |= FILTRULE_INCLUDE;
1202 /* FALL THROUGH */
1203 case 'P':
1204 rule->rflags |= FILTRULE_RECEIVER_SIDE;
1205 prefix_specifies_side = True;
1206 break;
1207 case '!':
1208 rule->rflags |= FILTRULE_CLEAR_LIST;
1209 break;
1210 default:
1211 rprintf(FERROR, "Unknown filter rule: `%s'\n", *rulestr_ptr);
1212 exit_cleanup(RERR_SYNTAX);
1214 while (ch != '!' && *++s && *s != ' ' && *s != '_') {
1215 if (template->rflags & FILTRULE_WORD_SPLIT && isspace(*s)) {
1216 s--;
1217 break;
1219 switch (*s) {
1220 default:
1221 invalid:
1222 rprintf(FERROR,
1223 "invalid modifier '%c' at position %d in filter rule: %s\n",
1224 *s, (int)(s - (const uchar *)*rulestr_ptr), *rulestr_ptr);
1225 exit_cleanup(RERR_SYNTAX);
1226 case '-':
1227 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
1228 goto invalid;
1229 rule->rflags |= FILTRULE_NO_PREFIXES;
1230 break;
1231 case '+':
1232 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
1233 goto invalid;
1234 rule->rflags |= FILTRULE_NO_PREFIXES
1235 | FILTRULE_INCLUDE;
1236 break;
1237 case '/':
1238 rule->rflags |= FILTRULE_ABS_PATH;
1239 break;
1240 case '!':
1241 /* Negation really goes with the pattern, so it
1242 * isn't useful as a merge-file default. */
1243 if (rule->rflags & FILTRULE_MERGE_FILE)
1244 goto invalid;
1245 rule->rflags |= FILTRULE_NEGATE;
1246 break;
1247 case 'C':
1248 if (rule->rflags & FILTRULE_NO_PREFIXES || prefix_specifies_side)
1249 goto invalid;
1250 rule->rflags |= FILTRULE_NO_PREFIXES
1251 | FILTRULE_WORD_SPLIT
1252 | FILTRULE_NO_INHERIT
1253 | FILTRULE_CVS_IGNORE;
1254 break;
1255 case 'e':
1256 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1257 goto invalid;
1258 rule->rflags |= FILTRULE_EXCLUDE_SELF;
1259 break;
1260 case 'n':
1261 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1262 goto invalid;
1263 rule->rflags |= FILTRULE_NO_INHERIT;
1264 break;
1265 case 'p':
1266 rule->rflags |= FILTRULE_PERISHABLE;
1267 break;
1268 case 'r':
1269 if (prefix_specifies_side)
1270 goto invalid;
1271 rule->rflags |= FILTRULE_RECEIVER_SIDE;
1272 break;
1273 case 's':
1274 if (prefix_specifies_side)
1275 goto invalid;
1276 rule->rflags |= FILTRULE_SENDER_SIDE;
1277 break;
1278 case 'w':
1279 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1280 goto invalid;
1281 rule->rflags |= FILTRULE_WORD_SPLIT;
1282 break;
1283 case 'x':
1284 rule->rflags |= FILTRULE_XATTR;
1285 saw_xattr_filter = 1;
1286 break;
1289 if (*s)
1290 s++;
1292 if (template->rflags & FILTRULES_SIDES) {
1293 if (rule->rflags & FILTRULES_SIDES) {
1294 /* The filter and template both specify side(s). This
1295 * is dodgy (and won't work correctly if the template is
1296 * a one-sided per-dir merge rule), so reject it. */
1297 rprintf(FERROR,
1298 "specified-side merge file contains specified-side filter: %s\n",
1299 *rulestr_ptr);
1300 exit_cleanup(RERR_SYNTAX);
1302 rule->rflags |= template->rflags & FILTRULES_SIDES;
1305 if (template->rflags & FILTRULE_WORD_SPLIT) {
1306 const uchar *cp = s;
1307 /* Token ends at whitespace or the end of the string. */
1308 while (!isspace(*cp) && *cp != '\0')
1309 cp++;
1310 len = cp - s;
1311 } else
1312 len = strlen((char*)s);
1314 if (rule->rflags & FILTRULE_CLEAR_LIST) {
1315 if (!(rule->rflags & FILTRULE_NO_PREFIXES)
1316 && !(xflags & XFLG_OLD_PREFIXES) && len) {
1317 rprintf(FERROR,
1318 "'!' rule has trailing characters: %s\n", *rulestr_ptr);
1319 exit_cleanup(RERR_SYNTAX);
1321 if (len > 1)
1322 rule->rflags &= ~FILTRULE_CLEAR_LIST;
1323 } else if (!len && !(rule->rflags & FILTRULE_CVS_IGNORE)) {
1324 rprintf(FERROR, "unexpected end of filter rule: %s\n", *rulestr_ptr);
1325 exit_cleanup(RERR_SYNTAX);
1328 /* --delete-excluded turns an un-modified include/exclude into a sender-side rule. */
1329 if (delete_excluded
1330 && !(rule->rflags & (FILTRULES_SIDES|FILTRULE_MERGE_FILE|FILTRULE_PERDIR_MERGE)))
1331 rule->rflags |= FILTRULE_SENDER_SIDE;
1333 *pat_ptr = (const char *)s;
1334 *pat_len_ptr = len;
1335 *rulestr_ptr = *pat_ptr + len;
1336 return rule;
1339 static void get_cvs_excludes(uint32 rflags)
1341 static int initialized = 0;
1342 char *p, fname[MAXPATHLEN];
1344 if (initialized)
1345 return;
1346 initialized = 1;
1348 parse_filter_str(&cvs_filter_list, default_cvsignore(),
1349 rule_template(rflags | (protocol_version >= 30 ? FILTRULE_PERISHABLE : 0)),
1352 p = module_id >= 0 && lp_use_chroot(module_id) ? "/" : getenv("HOME");
1353 if (p && pathjoin(fname, MAXPATHLEN, p, ".cvsignore") < MAXPATHLEN)
1354 parse_filter_file(&cvs_filter_list, fname, rule_template(rflags), 0);
1356 parse_filter_str(&cvs_filter_list, getenv("CVSIGNORE"), rule_template(rflags), 0);
1359 const filter_rule *rule_template(uint32 rflags)
1361 static filter_rule template; /* zero-initialized */
1362 template.rflags = rflags;
1363 return &template;
1366 void parse_filter_str(filter_rule_list *listp, const char *rulestr,
1367 const filter_rule *template, int xflags)
1369 filter_rule *rule;
1370 const char *pat;
1371 unsigned int pat_len;
1373 if (!rulestr)
1374 return;
1376 while (1) {
1377 uint32 new_rflags;
1379 /* Remember that the returned string is NOT '\0' terminated! */
1380 if (!(rule = parse_rule_tok(&rulestr, template, xflags, &pat, &pat_len)))
1381 break;
1383 if (pat_len >= MAXPATHLEN) {
1384 rprintf(FERROR, "discarding over-long filter: %.*s\n",
1385 (int)pat_len, pat);
1386 free_continue:
1387 free_filter(rule);
1388 continue;
1391 new_rflags = rule->rflags;
1392 if (new_rflags & FILTRULE_CLEAR_LIST) {
1393 if (DEBUG_GTE(FILTER, 2)) {
1394 rprintf(FINFO,
1395 "[%s] clearing filter list%s\n",
1396 who_am_i(), listp->debug_type);
1398 pop_filter_list(listp);
1399 listp->head = NULL;
1400 goto free_continue;
1403 if (new_rflags & FILTRULE_MERGE_FILE) {
1404 if (!pat_len) {
1405 pat = ".cvsignore";
1406 pat_len = 10;
1408 if (new_rflags & FILTRULE_EXCLUDE_SELF) {
1409 const char *name;
1410 filter_rule *excl_self;
1412 excl_self = new0(filter_rule);
1413 /* Find the beginning of the basename and add an exclude for it. */
1414 for (name = pat + pat_len; name > pat && name[-1] != '/'; name--) {}
1415 add_rule(listp, name, (pat + pat_len) - name, excl_self, 0);
1416 rule->rflags &= ~FILTRULE_EXCLUDE_SELF;
1418 if (new_rflags & FILTRULE_PERDIR_MERGE) {
1419 if (parent_dirscan) {
1420 const char *p;
1421 unsigned int len = pat_len;
1422 if ((p = parse_merge_name(pat, &len, module_dirlen)))
1423 add_rule(listp, p, len, rule, 0);
1424 else
1425 free_filter(rule);
1426 continue;
1428 } else {
1429 const char *p;
1430 unsigned int len = pat_len;
1431 if ((p = parse_merge_name(pat, &len, 0)))
1432 parse_filter_file(listp, p, rule, XFLG_FATAL_ERRORS);
1433 free_filter(rule);
1434 continue;
1438 add_rule(listp, pat, pat_len, rule, xflags);
1440 if (new_rflags & FILTRULE_CVS_IGNORE
1441 && !(new_rflags & FILTRULE_MERGE_FILE))
1442 get_cvs_excludes(new_rflags);
1446 void parse_filter_file(filter_rule_list *listp, const char *fname, const filter_rule *template, int xflags)
1448 FILE *fp;
1449 char line[BIGPATHBUFLEN];
1450 char *eob = line + sizeof line - 1;
1451 BOOL word_split = (template->rflags & FILTRULE_WORD_SPLIT) != 0;
1453 if (!fname || !*fname)
1454 return;
1456 if (*fname != '-' || fname[1] || am_server) {
1457 if (daemon_filter_list.head) {
1458 strlcpy(line, fname, sizeof line);
1459 clean_fname(line, CFN_COLLAPSE_DOT_DOT_DIRS);
1460 if (check_filter(&daemon_filter_list, FLOG, line, 0) < 0)
1461 fp = NULL;
1462 else
1463 fp = fopen(line, "rb");
1464 } else
1465 fp = fopen(fname, "rb");
1466 } else
1467 fp = stdin;
1469 if (DEBUG_GTE(FILTER, 2)) {
1470 rprintf(FINFO, "[%s] parse_filter_file(%s,%x,%x)%s\n",
1471 who_am_i(), fname, template->rflags, xflags,
1472 fp ? "" : " [not found]");
1475 if (!fp) {
1476 if (xflags & XFLG_FATAL_ERRORS) {
1477 rsyserr(FERROR, errno,
1478 "failed to open %sclude file %s",
1479 template->rflags & FILTRULE_INCLUDE ? "in" : "ex",
1480 fname);
1481 exit_cleanup(RERR_FILEIO);
1483 return;
1485 dirbuf[dirbuf_len] = '\0';
1487 while (1) {
1488 char *s = line;
1489 int ch, overflow = 0;
1490 while (1) {
1491 if ((ch = getc(fp)) == EOF) {
1492 if (ferror(fp) && errno == EINTR) {
1493 clearerr(fp);
1494 continue;
1496 break;
1498 if (word_split && isspace(ch))
1499 break;
1500 if (eol_nulls? !ch : (ch == '\n' || ch == '\r'))
1501 break;
1502 if (s < eob)
1503 *s++ = ch;
1504 else
1505 overflow = 1;
1507 if (overflow) {
1508 rprintf(FERROR, "discarding over-long filter: %s...\n", line);
1509 s = line;
1511 *s = '\0';
1512 /* Skip an empty token and (when line parsing) comments. */
1513 if (*line && (word_split || (*line != ';' && *line != '#')))
1514 parse_filter_str(listp, line, template, xflags);
1515 if (ch == EOF)
1516 break;
1518 fclose(fp);
1521 /* If the "for_xfer" flag is set, the prefix is made compatible with the
1522 * current protocol_version (if possible) or a NULL is returned (if not
1523 * possible). */
1524 char *get_rule_prefix(filter_rule *rule, const char *pat, int for_xfer,
1525 unsigned int *plen_ptr)
1527 static char buf[MAX_RULE_PREFIX+1];
1528 char *op = buf;
1529 int legal_len = for_xfer && protocol_version < 29 ? 1 : MAX_RULE_PREFIX-1;
1531 if (rule->rflags & FILTRULE_PERDIR_MERGE) {
1532 if (legal_len == 1)
1533 return NULL;
1534 *op++ = ':';
1535 } else if (rule->rflags & FILTRULE_INCLUDE)
1536 *op++ = '+';
1537 else if (legal_len != 1
1538 || ((*pat == '-' || *pat == '+') && pat[1] == ' '))
1539 *op++ = '-';
1540 else
1541 legal_len = 0;
1543 if (rule->rflags & FILTRULE_ABS_PATH)
1544 *op++ = '/';
1545 if (rule->rflags & FILTRULE_NEGATE)
1546 *op++ = '!';
1547 if (rule->rflags & FILTRULE_CVS_IGNORE)
1548 *op++ = 'C';
1549 else {
1550 if (rule->rflags & FILTRULE_NO_INHERIT)
1551 *op++ = 'n';
1552 if (rule->rflags & FILTRULE_WORD_SPLIT)
1553 *op++ = 'w';
1554 if (rule->rflags & FILTRULE_NO_PREFIXES) {
1555 if (rule->rflags & FILTRULE_INCLUDE)
1556 *op++ = '+';
1557 else
1558 *op++ = '-';
1561 if (rule->rflags & FILTRULE_EXCLUDE_SELF)
1562 *op++ = 'e';
1563 if (rule->rflags & FILTRULE_XATTR)
1564 *op++ = 'x';
1565 if (rule->rflags & FILTRULE_SENDER_SIDE
1566 && (!for_xfer || protocol_version >= 29))
1567 *op++ = 's';
1568 if (rule->rflags & FILTRULE_RECEIVER_SIDE
1569 && (!for_xfer || protocol_version >= 29
1570 || (delete_excluded && am_sender)))
1571 *op++ = 'r';
1572 if (rule->rflags & FILTRULE_PERISHABLE) {
1573 if (!for_xfer || protocol_version >= 30)
1574 *op++ = 'p';
1575 else if (am_sender)
1576 return NULL;
1578 if (op - buf > legal_len)
1579 return NULL;
1580 if (legal_len)
1581 *op++ = ' ';
1582 *op = '\0';
1583 if (plen_ptr)
1584 *plen_ptr = op - buf;
1585 return buf;
1588 static void send_rules(int f_out, filter_rule_list *flp)
1590 filter_rule *ent;
1592 for (ent = flp->head; ent; ent = ent->next) {
1593 unsigned int len, plen, dlen;
1594 int elide = 0;
1595 char *p;
1597 /* Note we need to check delete_excluded here in addition to
1598 * the code in parse_rule_tok() because some rules may have
1599 * been added before we found the --delete-excluded option.
1600 * We must also elide any CVS merge-file rules to avoid a
1601 * backward compatibility problem, and we elide any no-prefix
1602 * merge files as an optimization (since they can only have
1603 * include/exclude rules). */
1604 if (ent->rflags & FILTRULE_SENDER_SIDE)
1605 elide = am_sender ? LOCAL_RULE : REMOTE_RULE;
1606 if (ent->rflags & FILTRULE_RECEIVER_SIDE)
1607 elide = elide ? 0 : am_sender ? REMOTE_RULE : LOCAL_RULE;
1608 else if (delete_excluded && !elide
1609 && (!(ent->rflags & FILTRULE_PERDIR_MERGE)
1610 || ent->rflags & FILTRULE_NO_PREFIXES))
1611 elide = am_sender ? LOCAL_RULE : REMOTE_RULE;
1612 ent->elide = elide;
1613 if (elide == LOCAL_RULE)
1614 continue;
1615 if (ent->rflags & FILTRULE_CVS_IGNORE
1616 && !(ent->rflags & FILTRULE_MERGE_FILE)) {
1617 int f = am_sender || protocol_version < 29 ? f_out : -2;
1618 send_rules(f, &cvs_filter_list);
1619 if (f == f_out)
1620 continue;
1622 p = get_rule_prefix(ent, ent->pattern, 1, &plen);
1623 if (!p) {
1624 rprintf(FERROR,
1625 "filter rules are too modern for remote rsync.\n");
1626 exit_cleanup(RERR_PROTOCOL);
1628 if (f_out < 0)
1629 continue;
1630 len = strlen(ent->pattern);
1631 dlen = ent->rflags & FILTRULE_DIRECTORY ? 1 : 0;
1632 if (!(plen + len + dlen))
1633 continue;
1634 write_int(f_out, plen + len + dlen);
1635 if (plen)
1636 write_buf(f_out, p, plen);
1637 write_buf(f_out, ent->pattern, len);
1638 if (dlen)
1639 write_byte(f_out, '/');
1643 /* This is only called by the client. */
1644 void send_filter_list(int f_out)
1646 int receiver_wants_list = prune_empty_dirs
1647 || (delete_mode && (!delete_excluded || protocol_version >= 29));
1649 if (local_server || (am_sender && !receiver_wants_list))
1650 f_out = -1;
1651 if (cvs_exclude && am_sender) {
1652 if (protocol_version >= 29)
1653 parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1654 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1657 send_rules(f_out, &filter_list);
1659 if (f_out >= 0)
1660 write_int(f_out, 0);
1662 if (cvs_exclude) {
1663 if (!am_sender || protocol_version < 29)
1664 parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1665 if (!am_sender)
1666 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1670 /* This is only called by the server. */
1671 void recv_filter_list(int f_in)
1673 char line[BIGPATHBUFLEN];
1674 int xflags = protocol_version >= 29 ? 0 : XFLG_OLD_PREFIXES;
1675 int receiver_wants_list = prune_empty_dirs
1676 || (delete_mode && (!delete_excluded || protocol_version >= 29));
1677 unsigned int len;
1679 if (!local_server && (am_sender || receiver_wants_list)) {
1680 while ((len = read_int(f_in)) != 0) {
1681 if (len >= sizeof line)
1682 overflow_exit("recv_rules");
1683 read_sbuf(f_in, line, len);
1684 parse_filter_str(&filter_list, line, rule_template(0), xflags);
1688 if (cvs_exclude) {
1689 if (local_server || am_sender || protocol_version < 29)
1690 parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1691 if (local_server || am_sender)
1692 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1695 if (local_server) /* filter out any rules that aren't for us. */
1696 send_rules(-1, &filter_list);