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-2009 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.
29 extern int local_server;
30 extern int prune_empty_dirs;
31 extern int ignore_perishable;
32 extern int delete_mode;
33 extern int delete_excluded;
34 extern int cvs_exclude;
35 extern int sanitize_paths;
36 extern int protocol_version;
39 extern char curr_dir[MAXPATHLEN];
40 extern unsigned int curr_dir_len;
41 extern unsigned int module_dirlen;
43 struct filter_list_struct filter_list = { .debug_type = "" };
44 struct filter_list_struct cvs_filter_list = { .debug_type = " [global CVS]" };
45 struct filter_list_struct daemon_filter_list = { .debug_type = " [daemon]" };
47 struct filter_struct *last_hit_filter;
49 /* Need room enough for ":MODS " prefix, which can now include
50 * chmod/user/group values. */
51 #define MAX_RULE_PREFIX (256)
53 #define SLASH_WILD3_SUFFIX "/***"
55 /* The dirbuf is set by push_local_filters() to the current subdirectory
56 * relative to curr_dir that is being processed. The path always has a
57 * trailing slash appended, and the variable dirbuf_len contains the length
58 * of this path prefix. The path is always absolute. */
59 static char dirbuf[MAXPATHLEN+1];
60 static unsigned int dirbuf_len = 0;
61 static int dirbuf_depth;
63 /* This is True when we're scanning parent dirs for per-dir merge-files. */
64 static BOOL parent_dirscan = False;
66 /* This array contains a list of all the currently active per-dir merge
67 * files. This makes it easier to save the appropriate values when we
68 * "push" down into each subdirectory. */
69 static struct filter_struct **mergelist_parents;
70 static int mergelist_cnt = 0;
71 static int mergelist_size = 0;
73 /* Each filter_list_struct describes a singly-linked list by keeping track
74 * of both the head and tail pointers. The list is slightly unusual in that
75 * a parent-dir's content can be appended to the end of the local list in a
76 * special way: the last item in the local list has its "next" pointer set
77 * to point to the inherited list, but the local list's tail pointer points
78 * at the end of the local list. Thus, if the local list is empty, the head
79 * will be pointing at the inherited content but the tail will be NULL. To
80 * help you visualize this, here are the possible list arrangements:
82 * Completely Empty Local Content Only
83 * ================================== ====================================
84 * head -> NULL head -> Local1 -> Local2 -> NULL
85 * tail -> NULL tail -------------^
87 * Inherited Content Only Both Local and Inherited Content
88 * ================================== ====================================
89 * head -> Parent1 -> Parent2 -> NULL head -> L1 -> L2 -> P1 -> P2 -> NULL
90 * tail -> NULL tail ---------^
92 * This means that anyone wanting to traverse the whole list to use it just
93 * needs to start at the head and use the "next" pointers until it goes
94 * NULL. To add new local content, we insert the item after the tail item
95 * and update the tail (obviously, if "tail" was NULL, we insert it at the
96 * head). To clear the local list, WE MUST NOT FREE THE INHERITED CONTENT
97 * because it is shared between the current list and our parent list(s).
98 * The easiest way to handle this is to simply truncate the list after the
99 * tail item and then free the local list from the head. When inheriting
100 * the list for a new local dir, we just save off the filter_list_struct
101 * values (so we can pop back to them later) and set the tail to NULL.
104 static void teardown_mergelist(struct filter_struct *ex)
106 if (DEBUG_GTE(FILTER, 2)) {
107 rprintf(FINFO, "[%s] deactivating mergelist #%d%s\n",
108 who_am_i(), mergelist_cnt - 1,
109 ex->u.mergelist->debug_type);
112 /* We should deactivate mergelists in LIFO order. */
113 assert(mergelist_cnt > 0);
114 assert(ex == mergelist_parents[mergelist_cnt - 1]);
116 /* The parent_dirscan filters should have been freed. */
117 assert(ex->u.mergelist->parent_dirscan_head == NULL);
119 free(ex->u.mergelist->debug_type);
120 free(ex->u.mergelist);
124 static struct filter_chmod_struct *ref_filter_chmod(struct filter_chmod_struct *chmod)
127 assert(chmod->ref_cnt != 0); /* Catch overflow. */
131 static void unref_filter_chmod(struct filter_chmod_struct *chmod)
134 if (chmod->ref_cnt == 0) {
135 free(chmod->modestr);
136 free_chmod_mode(chmod->modes);
141 static void free_filter(struct filter_struct *ex)
143 if (ex->flags & MATCHFLG_CHMOD)
144 unref_filter_chmod(ex->chmod);
149 static void free_filters(struct filter_struct *head)
151 struct filter_struct *rev_head = NULL;
153 /* Reverse the list so we deactivate mergelists in the proper LIFO
156 struct filter_struct *next = head->next;
157 head->next = rev_head;
163 struct filter_struct *prev = rev_head->next;
164 /* Tear down mergelists here, not in free_filter, so that we
165 * affect only real filter lists and not temporarily allocated
167 if (rev_head->flags & MATCHFLG_PERDIR_MERGE)
168 teardown_mergelist(rev_head);
169 free_filter(rev_head);
174 /* Build a filter structure given a filter pattern. The value in "pat"
175 * is not null-terminated. "filter" is either held or freed, so the
176 * caller should not free it. */
177 static void add_rule(struct filter_list_struct *listp,
178 const char *pat, unsigned int pat_len,
179 struct filter_struct *filter, int xflags)
182 unsigned int pre_len, suf_len, slash_cnt = 0;
184 if (DEBUG_GTE(FILTER, 2)) {
185 rprintf(FINFO, "[%s] add_rule(%s%.*s%s)%s\n",
186 who_am_i(), get_rule_prefix(filter, pat, 0, NULL),
188 (filter->flags & MATCHFLG_DIRECTORY) ? "/" : "",
192 /* These flags also indicate that we're reading a list that
193 * needs to be filtered now, not post-filtered later. */
194 if (xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH)
195 && (filter->flags & MATCHFLGS_SIDES)
196 == (am_sender ? MATCHFLG_RECEIVER_SIDE : MATCHFLG_SENDER_SIDE)) {
197 /* This filter applies only to the other side. Drop it. */
202 if (pat_len > 1 && pat[pat_len-1] == '/') {
204 filter->flags |= MATCHFLG_DIRECTORY;
207 for (cp = pat; cp < pat + pat_len; cp++) {
212 if (!(filter->flags & (MATCHFLG_ABS_PATH | MATCHFLG_MERGE_FILE))
213 && ((xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH) && *pat == '/')
214 || (xflags & XFLG_ABS_IF_SLASH && slash_cnt))) {
215 filter->flags |= MATCHFLG_ABS_PATH;
217 pre_len = dirbuf_len - module_dirlen - 1;
223 /* The daemon wants dir-exclude rules to get an appended "/" + "***". */
224 if (xflags & XFLG_DIR2WILD3
225 && BITS_SETnUNSET(filter->flags, MATCHFLG_DIRECTORY, MATCHFLG_INCLUDE)) {
226 filter->flags &= ~MATCHFLG_DIRECTORY;
227 suf_len = sizeof SLASH_WILD3_SUFFIX - 1;
231 if (!(filter->pattern = new_array(char, pre_len + pat_len + suf_len + 1)))
232 out_of_memory("add_rule");
234 memcpy(filter->pattern, dirbuf + module_dirlen, pre_len);
235 for (cp = filter->pattern; cp < filter->pattern + pre_len; cp++) {
240 strlcpy(filter->pattern + pre_len, pat, pat_len + 1);
243 memcpy(filter->pattern + pat_len, SLASH_WILD3_SUFFIX, suf_len+1);
248 if (strpbrk(filter->pattern, "*[?")) {
249 filter->flags |= MATCHFLG_WILD;
250 if ((cp = strstr(filter->pattern, "**")) != NULL) {
251 filter->flags |= MATCHFLG_WILD2;
252 /* If the pattern starts with **, note that. */
253 if (cp == filter->pattern)
254 filter->flags |= MATCHFLG_WILD2_PREFIX;
255 /* If the pattern ends with ***, note that. */
257 && filter->pattern[pat_len-3] == '*'
258 && filter->pattern[pat_len-2] == '*'
259 && filter->pattern[pat_len-1] == '*')
260 filter->flags |= MATCHFLG_WILD3_SUFFIX;
264 if (filter->flags & MATCHFLG_PERDIR_MERGE) {
265 struct filter_list_struct *lp;
269 if ((cp = strrchr(filter->pattern, '/')) != NULL)
272 cp = filter->pattern;
274 /* If the local merge file was already mentioned, don't
276 for (i = 0; i < mergelist_cnt; i++) {
277 struct filter_struct *ex = mergelist_parents[i];
278 const char *s = strrchr(ex->pattern, '/');
284 if (len == pat_len - (cp - filter->pattern)
285 && memcmp(s, cp, len) == 0) {
291 if (!(lp = new_array(struct filter_list_struct, 1)))
292 out_of_memory("add_rule");
293 lp->head = lp->tail = lp->parent_dirscan_head = NULL;
294 if (asprintf(&lp->debug_type, " [per-dir %s]", cp) < 0)
295 out_of_memory("add_rule");
296 filter->u.mergelist = lp;
298 if (mergelist_cnt == mergelist_size) {
300 mergelist_parents = realloc_array(mergelist_parents,
301 struct filter_struct *,
303 if (!mergelist_parents)
304 out_of_memory("add_rule");
306 if (DEBUG_GTE(FILTER, 2)) {
307 rprintf(FINFO, "[%s] activating mergelist #%d%s\n",
308 who_am_i(), mergelist_cnt, lp->debug_type);
310 mergelist_parents[mergelist_cnt++] = filter;
312 filter->u.slash_cnt = slash_cnt;
315 filter->next = listp->head;
316 listp->head = listp->tail = filter;
318 filter->next = listp->tail->next;
319 listp->tail->next = filter;
320 listp->tail = filter;
324 static void clear_filter_list(struct filter_list_struct *listp)
327 /* Truncate any inherited items from the local list. */
328 listp->tail->next = NULL;
329 /* Now free everything that is left. */
330 free_filters(listp->head);
333 listp->head = listp->tail = NULL;
336 /* This returns an expanded (absolute) filename for the merge-file name if
337 * the name has any slashes in it OR if the parent_dirscan var is True;
338 * otherwise it returns the original merge_file name. If the len_ptr value
339 * is non-NULL the merge_file name is limited by the referenced length
340 * value and will be updated with the length of the resulting name. We
341 * always return a name that is null terminated, even if the merge_file
343 static char *parse_merge_name(const char *merge_file, unsigned int *len_ptr,
344 unsigned int prefix_skip)
346 static char buf[MAXPATHLEN];
347 char *fn, tmpbuf[MAXPATHLEN];
350 if (!parent_dirscan && *merge_file != '/') {
351 /* Return the name unchanged it doesn't have any slashes. */
353 const char *p = merge_file + *len_ptr;
354 while (--p > merge_file && *p != '/') {}
355 if (p == merge_file) {
356 strlcpy(buf, merge_file, *len_ptr + 1);
359 } else if (strchr(merge_file, '/') == NULL)
360 return (char *)merge_file;
363 fn = *merge_file == '/' ? buf : tmpbuf;
364 if (sanitize_paths) {
365 const char *r = prefix_skip ? "/" : NULL;
366 /* null-terminate the name if it isn't already */
367 if (len_ptr && merge_file[*len_ptr]) {
368 char *to = fn == buf ? tmpbuf : buf;
369 strlcpy(to, merge_file, *len_ptr + 1);
372 if (!sanitize_path(fn, merge_file, r, dirbuf_depth, SP_DEFAULT)) {
373 rprintf(FERROR, "merge-file name overflows: %s\n",
379 strlcpy(fn, merge_file, len_ptr ? *len_ptr + 1 : MAXPATHLEN);
380 fn_len = clean_fname(fn, CFN_COLLAPSE_DOT_DOT_DIRS);
383 /* If the name isn't in buf yet, it's wasn't absolute. */
385 int d_len = dirbuf_len - prefix_skip;
386 if (d_len + fn_len >= MAXPATHLEN) {
387 rprintf(FERROR, "merge-file name overflows: %s\n", fn);
390 memcpy(buf, dirbuf + prefix_skip, d_len);
391 memcpy(buf + d_len, fn, fn_len + 1);
392 fn_len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
400 /* Sets the dirbuf and dirbuf_len values. */
401 void set_filter_dir(const char *dir, unsigned int dirlen)
405 memcpy(dirbuf, curr_dir, curr_dir_len);
406 dirbuf[curr_dir_len] = '/';
407 len = curr_dir_len + 1;
408 if (len + dirlen >= MAXPATHLEN)
412 memcpy(dirbuf + len, dir, dirlen);
413 dirbuf[dirlen + len] = '\0';
414 dirbuf_len = clean_fname(dirbuf, CFN_COLLAPSE_DOT_DOT_DIRS);
415 if (dirbuf_len > 1 && dirbuf[dirbuf_len-1] == '.'
416 && dirbuf[dirbuf_len-2] == '/')
419 dirbuf[dirbuf_len++] = '/';
420 dirbuf[dirbuf_len] = '\0';
422 dirbuf_depth = count_dir_elements(dirbuf + module_dirlen);
425 /* This routine takes a per-dir merge-file entry and finishes its setup.
426 * If the name has a path portion then we check to see if it refers to a
427 * parent directory of the first transfer dir. If it does, we scan all the
428 * dirs from that point through the parent dir of the transfer dir looking
429 * for the per-dir merge-file in each one. */
430 static BOOL setup_merge_file(int mergelist_num, struct filter_struct *ex,
431 struct filter_list_struct *lp)
433 char buf[MAXPATHLEN];
434 char *x, *y, *pat = ex->pattern;
437 if (!(x = parse_merge_name(pat, NULL, 0)) || *x != '/')
440 if (DEBUG_GTE(FILTER, 2)) {
441 rprintf(FINFO, "[%s] performing parent_dirscan for mergelist #%d%s\n",
442 who_am_i(), mergelist_num, lp->debug_type);
446 ex->pattern = strdup(y+1);
450 strlcpy(buf, x, MAXPATHLEN);
452 pathjoin(buf, MAXPATHLEN, dirbuf, x);
454 len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
455 if (len != 1 && len < MAXPATHLEN-1) {
459 /* This ensures that the specified dir is a parent of the transfer. */
460 for (x = buf, y = dirbuf; *x && *x == *y; x++, y++) {}
462 y += strlen(y); /* nope -- skip the scan */
464 parent_dirscan = True;
466 char save[MAXPATHLEN];
467 strlcpy(save, y, MAXPATHLEN);
469 dirbuf_len = y - dirbuf;
470 strlcpy(x, ex->pattern, MAXPATHLEN - (x - buf));
471 load_filter_file(lp, buf, ex, XFLG_ANCHORED2ABS);
472 if (ex->flags & MATCHFLG_NO_INHERIT) {
473 /* Free the undesired rules to clean up any per-dir
474 * mergelists they defined. Otherwise pop_local_filters
475 * may crash trying to restore nonexistent state for
476 * those mergelists. */
477 free_filters(lp->head);
481 strlcpy(y, save, MAXPATHLEN);
482 while ((*x++ = *y++) != '/') {}
484 /* Save current head for freeing when the mergelist becomes inactive. */
485 lp->parent_dirscan_head = lp->head;
486 parent_dirscan = False;
487 if (DEBUG_GTE(FILTER, 2)) {
488 rprintf(FINFO, "[%s] completed parent_dirscan for mergelist #%d%s\n",
489 who_am_i(), mergelist_num, lp->debug_type);
495 struct local_filter_state {
497 struct filter_list_struct mergelists[1];
500 /* Each time rsync changes to a new directory it call this function to
501 * handle all the per-dir merge-files. The "dir" value is the current path
502 * relative to curr_dir (which might not be null-terminated). We copy it
503 * into dirbuf so that we can easily append a file name on the end. */
504 void *push_local_filters(const char *dir, unsigned int dirlen)
506 struct local_filter_state *push;
509 set_filter_dir(dir, dirlen);
510 if (DEBUG_GTE(FILTER, 2)) {
511 rprintf(FINFO, "[%s] pushing local filters for %s\n",
515 if (!mergelist_cnt) {
516 /* No old state to save and no new merge files to push. */
520 push = (struct local_filter_state *)new_array(char,
521 sizeof (struct local_filter_state)
522 + (mergelist_cnt-1) * sizeof (struct filter_list_struct));
524 out_of_memory("push_local_filters");
526 push->mergelist_cnt = mergelist_cnt;
527 for (i = 0; i < mergelist_cnt; i++) {
528 memcpy(&push->mergelists[i], mergelist_parents[i]->u.mergelist,
529 sizeof (struct filter_list_struct));
532 /* Note: load_filter_file() might increase mergelist_cnt, so keep
533 * this loop separate from the above loop. */
534 for (i = 0; i < mergelist_cnt; i++) {
535 struct filter_struct *ex = mergelist_parents[i];
536 struct filter_list_struct *lp = ex->u.mergelist;
538 if (DEBUG_GTE(FILTER, 2)) {
539 rprintf(FINFO, "[%s] pushing mergelist #%d%s\n",
540 who_am_i(), i, lp->debug_type);
543 lp->tail = NULL; /* Switch any local rules to inherited. */
544 if (ex->flags & MATCHFLG_NO_INHERIT)
547 if (ex->flags & MATCHFLG_FINISH_SETUP) {
548 ex->flags &= ~MATCHFLG_FINISH_SETUP;
549 if (setup_merge_file(i, ex, lp))
550 set_filter_dir(dir, dirlen);
553 if (strlcpy(dirbuf + dirbuf_len, ex->pattern,
554 MAXPATHLEN - dirbuf_len) < MAXPATHLEN - dirbuf_len) {
555 load_filter_file(lp, dirbuf, ex,
558 io_error |= IOERR_GENERAL;
560 "cannot add local filter rules in long-named directory: %s\n",
563 dirbuf[dirbuf_len] = '\0';
569 void pop_local_filters(void *mem)
571 struct local_filter_state *pop = (struct local_filter_state *)mem;
573 int old_mergelist_cnt = pop ? pop->mergelist_cnt : 0;
575 if (DEBUG_GTE(FILTER, 2))
576 rprintf(FINFO, "[%s] popping local filters\n", who_am_i());
578 for (i = mergelist_cnt; i-- > 0; ) {
579 struct filter_struct *ex = mergelist_parents[i];
580 struct filter_list_struct *lp = ex->u.mergelist;
582 if (DEBUG_GTE(FILTER, 2)) {
583 rprintf(FINFO, "[%s] popping mergelist #%d%s\n",
584 who_am_i(), i, lp->debug_type);
587 clear_filter_list(lp);
589 if (i >= old_mergelist_cnt) {
590 /* This mergelist does not exist in the state to be
591 * restored. Free its parent_dirscan list to clean up
592 * any per-dir mergelists defined there so we don't
593 * crash trying to restore nonexistent state for them
594 * below. (Counterpart to setup_merge_file call in
595 * push_local_filters. Must be done here, not in
596 * free_filter, for LIFO order.) */
597 if (DEBUG_GTE(FILTER, 2)) {
598 rprintf(FINFO, "[%s] freeing parent_dirscan filters of mergelist #%d%s\n",
599 who_am_i(), i, ex->u.mergelist->debug_type);
601 free_filters(lp->parent_dirscan_head);
602 lp->parent_dirscan_head = NULL;
606 /* If we cleaned things up properly, the only still-active mergelists
607 * should be those with a state to be restored. */
608 assert(mergelist_cnt == old_mergelist_cnt);
611 /* No state to restore. */
615 for (i = 0; i < mergelist_cnt; i++) {
616 memcpy(mergelist_parents[i]->u.mergelist, &pop->mergelists[i],
617 sizeof (struct filter_list_struct));
623 void change_local_filter_dir(const char *dname, int dlen, int dir_depth)
625 static int cur_depth = -1;
626 static void *filt_array[MAXPATHLEN/2+1];
629 for ( ; cur_depth >= 0; cur_depth--) {
630 if (filt_array[cur_depth]) {
631 pop_local_filters(filt_array[cur_depth]);
632 filt_array[cur_depth] = NULL;
638 assert(dir_depth < MAXPATHLEN/2+1);
640 for ( ; cur_depth >= dir_depth; cur_depth--) {
641 if (filt_array[cur_depth]) {
642 pop_local_filters(filt_array[cur_depth]);
643 filt_array[cur_depth] = NULL;
647 cur_depth = dir_depth;
648 filt_array[cur_depth] = push_local_filters(dname, dlen);
651 static int rule_matches(const char *fname, struct filter_struct *ex, int name_is_dir)
653 int slash_handling, str_cnt = 0, anchored_match = 0;
654 int ret_match = ex->flags & MATCHFLG_NEGATE ? 0 : 1;
655 char *p, *pattern = ex->pattern;
656 const char *strings[16]; /* more than enough */
657 const char *name = fname + (*fname == '/');
662 if (!ex->u.slash_cnt && !(ex->flags & MATCHFLG_WILD2)) {
663 /* If the pattern does not have any slashes AND it does
664 * not have a "**" (which could match a slash), then we
665 * just match the name portion of the path. */
666 if ((p = strrchr(name,'/')) != NULL)
668 } else if (ex->flags & MATCHFLG_ABS_PATH && *fname != '/'
669 && curr_dir_len > module_dirlen + 1) {
670 /* If we're matching against an absolute-path pattern,
671 * we need to prepend our full path info. */
672 strings[str_cnt++] = curr_dir + module_dirlen + 1;
673 strings[str_cnt++] = "/";
674 } else if (ex->flags & MATCHFLG_WILD2_PREFIX && *fname != '/') {
675 /* Allow "**"+"/" to match at the start of the string. */
676 strings[str_cnt++] = "/";
678 strings[str_cnt++] = name;
680 /* Allow a trailing "/"+"***" to match the directory. */
681 if (ex->flags & MATCHFLG_WILD3_SUFFIX)
682 strings[str_cnt++] = "/";
683 } else if (ex->flags & MATCHFLG_DIRECTORY)
685 strings[str_cnt] = NULL;
687 if (*pattern == '/') {
692 if (!anchored_match && ex->u.slash_cnt
693 && !(ex->flags & MATCHFLG_WILD2)) {
694 /* A non-anchored match with an infix slash and no "**"
695 * needs to match the last slash_cnt+1 name elements. */
696 slash_handling = ex->u.slash_cnt + 1;
697 } else if (!anchored_match && !(ex->flags & MATCHFLG_WILD2_PREFIX)
698 && ex->flags & MATCHFLG_WILD2) {
699 /* A non-anchored match with an infix or trailing "**" (but not
700 * a prefixed "**") needs to try matching after every slash. */
703 /* The pattern matches only at the start of the path or name. */
707 if (ex->flags & MATCHFLG_WILD) {
708 if (wildmatch_array(pattern, strings, slash_handling))
710 } else if (str_cnt > 1) {
711 if (litmatch_array(pattern, strings, slash_handling))
713 } else if (anchored_match) {
714 if (strcmp(name, pattern) == 0)
717 int l1 = strlen(name);
718 int l2 = strlen(pattern);
720 strcmp(name+(l1-l2),pattern) == 0 &&
721 (l1==l2 || name[l1-(l2+1)] == '/')) {
730 static void report_filter_result(enum logcode code, char const *name,
731 struct filter_struct const *ent,
732 int name_is_dir, const char *type)
734 /* If a trailing slash is present to match only directories,
735 * then it is stripped out by add_rule(). So as a special
736 * case we add it back in here. */
738 if (DEBUG_GTE(FILTER, 1)) {
739 static char *actions[2][2]
740 = { {"show", "hid"}, {"risk", "protect"} };
741 const char *w = who_am_i();
742 rprintf(code, "[%s] %sing %s %s because of pattern %s%s%s\n",
743 w, actions[*w!='s'][!(ent->flags&MATCHFLG_INCLUDE)],
744 name_is_dir ? "directory" : "file", name, ent->pattern,
745 ent->flags & MATCHFLG_DIRECTORY ? "/" : "", type);
751 * Return -1 if file "name" is defined to be excluded by the specified
752 * exclude list, 1 if it is included, and 0 if it was not matched.
753 * Sets last_hit_filter to the filter that was hit, or NULL if none.
755 int check_filter(struct filter_list_struct *listp, enum logcode code,
756 const char *name, int name_is_dir)
758 struct filter_struct *ent;
760 for (ent = listp->head; ent; ent = ent->next) {
761 if (ignore_perishable && ent->flags & MATCHFLG_PERISHABLE)
763 if (ent->flags & MATCHFLG_PERDIR_MERGE) {
764 int rc = check_filter(ent->u.mergelist, code, name,
770 if (ent->flags & MATCHFLG_CVS_IGNORE) {
771 int rc = check_filter(&cvs_filter_list, code, name,
777 if (rule_matches(name, ent, name_is_dir)) {
778 report_filter_result(code, name, ent, name_is_dir,
780 last_hit_filter = ent;
781 return ent->flags & MATCHFLG_INCLUDE ? 1 : -1;
785 last_hit_filter = NULL;
789 #define RULE_STRCMP(s,r) rule_strcmp((s), (r), sizeof (r) - 1)
791 static const uchar *rule_strcmp(const uchar *str, const char *rule, int rule_len)
793 if (strncmp((char*)str, rule, rule_len) != 0)
795 if (isspace(str[rule_len]) || str[rule_len] == '_' || !str[rule_len])
796 return str + rule_len - 1;
797 if (str[rule_len] == ',')
798 return str + rule_len;
802 static char *grab_paren_value(const uchar **s_ptr)
804 const uchar *start, *end;
808 if ((*s_ptr)[1] != '(')
810 start = (*s_ptr) + 2;
812 for (end = start; *end != ')'; end++)
813 if (!*end || *end == ' ' || *end == '_')
816 val_sz = end - start + 1;
817 val = new_array(char, val_sz);
818 strlcpy(val, (const char *)start, val_sz);
819 *s_ptr = end; /* remember ++s in parse_rule_tok */
823 static struct filter_chmod_struct *make_chmod_struct(char *modestr)
825 struct filter_chmod_struct *chmod;
826 struct chmod_mode_struct *modes = NULL;
828 if (!parse_chmod(modestr, &modes))
831 if (!(chmod = new(struct filter_chmod_struct)))
832 out_of_memory("make_chmod_struct");
834 chmod->modestr = modestr;
835 chmod->modes = modes;
839 #define MATCHFLGS_FROM_CONTAINER (MATCHFLG_ABS_PATH | MATCHFLG_INCLUDE \
840 | MATCHFLG_DIRECTORY | MATCHFLG_NEGATE \
841 | MATCHFLG_PERISHABLE | MATCHFLGS_ATTRS)
843 /* Gets the next include/exclude rule from *rulestr_ptr and advances
844 * *rulestr_ptr to point beyond it. Stores the pattern's start (within
845 * *rulestr_ptr) and length in *pat_ptr and *pat_len_ptr, and returns a newly
846 * allocated filter_struct containing the rest of the information. Returns
847 * NULL if there are no more rules in the input.
849 * The template provides defaults for the new rule to inherit, and the
850 * template mflags and the xflags additionally affect parsing. */
851 static struct filter_struct *parse_rule_tok(const char **rulestr_ptr,
852 struct filter_struct *template, int xflags,
853 const char **pat_ptr, unsigned int *pat_len_ptr)
855 const uchar *s = (const uchar *)*rulestr_ptr;
857 struct filter_struct *filter;
860 if (template->flags & MATCHFLG_WORD_SPLIT) {
861 /* Skip over any initial whitespace. */
864 /* Update to point to real start of rule. */
865 *rulestr_ptr = (const char *)s;
870 if (!(filter = new0(struct filter_struct)))
871 out_of_memory("parse_rule_tok");
873 /* Inherit from the template. Don't inherit MATCHFLGS_SIDES; we check
875 filter->flags = template->flags & MATCHFLGS_FROM_CONTAINER;
876 if (template->flags & MATCHFLG_CHMOD)
877 filter->chmod = ref_filter_chmod(template->chmod);
878 if (template->flags & MATCHFLG_FORCE_OWNER)
879 filter->force_uid = template->force_uid;
880 if (template->flags & MATCHFLG_FORCE_GROUP)
881 filter->force_gid = template->force_gid;
883 /* Figure out what kind of a filter rule "s" is pointing at. Note
884 * that if MATCHFLG_NO_PREFIXES is set, the rule is either an include
885 * or an exclude based on the inheritance of the MATCHFLG_INCLUDE
886 * flag (above). XFLG_OLD_PREFIXES indicates a compatibility mode
887 * for old include/exclude patterns where just "+ " and "- " are
888 * allowed as optional prefixes. */
889 if (template->flags & MATCHFLG_NO_PREFIXES) {
890 if (*s == '!' && template->flags & MATCHFLG_CVS_IGNORE)
891 filter->flags |= MATCHFLG_CLEAR_LIST; /* Tentative! */
892 } else if (xflags & XFLG_OLD_PREFIXES) {
893 if (*s == '-' && s[1] == ' ') {
894 filter->flags &= ~MATCHFLG_INCLUDE;
896 } else if (*s == '+' && s[1] == ' ') {
897 filter->flags |= MATCHFLG_INCLUDE;
899 } else if (*s == '!')
900 filter->flags |= MATCHFLG_CLEAR_LIST; /* Tentative! */
903 BOOL prefix_specifies_side = False;
906 if ((s = RULE_STRCMP(s, "clear")) != NULL)
910 if ((s = RULE_STRCMP(s, "dir-merge")) != NULL)
914 if ((s = RULE_STRCMP(s, "exclude")) != NULL)
918 if ((s = RULE_STRCMP(s, "hide")) != NULL)
922 if ((s = RULE_STRCMP(s, "include")) != NULL)
926 if ((s = RULE_STRCMP(s, "merge")) != NULL)
930 if ((s = RULE_STRCMP(s, "protect")) != NULL)
934 if ((s = RULE_STRCMP(s, "risk")) != NULL)
938 if ((s = RULE_STRCMP(s, "show")) != NULL)
949 filter->flags |= MATCHFLG_PERDIR_MERGE
950 | MATCHFLG_FINISH_SETUP;
953 filter->flags |= MATCHFLG_MERGE_FILE;
956 filter->flags |= MATCHFLG_INCLUDE;
961 filter->flags |= MATCHFLG_INCLUDE;
964 filter->flags |= MATCHFLG_SENDER_SIDE;
965 prefix_specifies_side = True;
968 filter->flags |= MATCHFLG_INCLUDE;
971 filter->flags |= MATCHFLG_RECEIVER_SIDE;
972 prefix_specifies_side = True;
975 filter->flags |= MATCHFLG_CLEAR_LIST;
978 rprintf(FERROR, "Unknown filter rule: `%s'\n", *rulestr_ptr);
979 exit_cleanup(RERR_SYNTAX);
981 while (ch != '!' && *++s && *s != ' ' && *s != '_') {
982 if (template->flags & MATCHFLG_WORD_SPLIT && isspace(*s)) {
990 "invalid modifier '%c' at position %d in filter rule: %s\n",
991 *s, s - (const uchar *)*rulestr_ptr, *rulestr_ptr);
992 exit_cleanup(RERR_SYNTAX);
994 if (!BITS_SETnUNSET(filter->flags, MATCHFLG_MERGE_FILE, MATCHFLG_NO_PREFIXES))
996 filter->flags |= MATCHFLG_NO_PREFIXES;
999 if (!BITS_SETnUNSET(filter->flags, MATCHFLG_MERGE_FILE, MATCHFLG_NO_PREFIXES))
1001 filter->flags |= MATCHFLG_NO_PREFIXES
1005 filter->flags |= MATCHFLG_ABS_PATH;
1008 /* Negation really goes with the pattern, so it
1009 * isn't useful as a merge-file default. */
1010 if (filter->flags & MATCHFLG_MERGE_FILE)
1012 filter->flags |= MATCHFLG_NEGATE;
1015 if (filter->flags & MATCHFLG_NO_PREFIXES || prefix_specifies_side)
1017 filter->flags |= MATCHFLG_NO_PREFIXES
1018 | MATCHFLG_WORD_SPLIT
1019 | MATCHFLG_NO_INHERIT
1020 | MATCHFLG_CVS_IGNORE;
1023 if (!(filter->flags & MATCHFLG_MERGE_FILE))
1025 filter->flags |= MATCHFLG_EXCLUDE_SELF;
1030 if (!(val = grab_paren_value(&s)))
1032 if (name_to_gid(val, &gid, True)) {
1033 filter->flags |= MATCHFLG_FORCE_GROUP;
1034 filter->force_gid = gid;
1037 "unknown group '%s' in filter rule: %s\n",
1039 exit_cleanup(RERR_SYNTAX);
1045 struct filter_chmod_struct *chmod;
1047 if (!(val = grab_paren_value(&s)))
1049 if ((chmod = make_chmod_struct(val))) {
1050 if (filter->flags & MATCHFLG_CHMOD)
1051 unref_filter_chmod(filter->chmod);
1052 filter->flags |= MATCHFLG_CHMOD;
1053 filter->chmod = chmod;
1056 "unparseable chmod string '%s' in filter rule: %s\n",
1058 exit_cleanup(RERR_SYNTAX);
1063 if (!(filter->flags & MATCHFLG_MERGE_FILE))
1065 filter->flags |= MATCHFLG_NO_INHERIT;
1070 if (!(val = grab_paren_value(&s)))
1072 if (name_to_uid(val, &uid, True)) {
1073 filter->flags |= MATCHFLG_FORCE_OWNER;
1074 filter->force_uid = uid;
1077 "unknown user '%s' in filter rule: %s\n",
1079 exit_cleanup(RERR_SYNTAX);
1085 filter->flags |= MATCHFLG_PERISHABLE;
1088 if (prefix_specifies_side)
1090 filter->flags |= MATCHFLG_RECEIVER_SIDE;
1093 if (prefix_specifies_side)
1095 filter->flags |= MATCHFLG_SENDER_SIDE;
1098 if (!(filter->flags & MATCHFLG_MERGE_FILE))
1100 filter->flags |= MATCHFLG_WORD_SPLIT;
1107 if (template->flags & MATCHFLGS_SIDES) {
1108 if (filter->flags & MATCHFLGS_SIDES) {
1109 /* The filter and template both specify side(s). This
1110 * is dodgy (and won't work correctly if the template is
1111 * a one-sided per-dir merge rule), so reject it. */
1113 "specified-side merge file contains specified-side filter: %s\n",
1115 exit_cleanup(RERR_SYNTAX);
1117 filter->flags |= template->flags & MATCHFLGS_SIDES;
1120 if (template->flags & MATCHFLG_WORD_SPLIT) {
1121 const uchar *cp = s;
1122 /* Token ends at whitespace or the end of the string. */
1123 while (!isspace(*cp) && *cp != '\0')
1127 len = strlen((char*)s);
1129 if (filter->flags & MATCHFLG_CLEAR_LIST) {
1130 if (!(filter->flags & MATCHFLG_NO_PREFIXES)
1131 && !(xflags & XFLG_OLD_PREFIXES) && len) {
1133 "'!' rule has trailing characters: %s\n", *rulestr_ptr);
1134 exit_cleanup(RERR_SYNTAX);
1137 filter->flags &= ~MATCHFLG_CLEAR_LIST;
1138 } else if (!len && !(filter->flags & MATCHFLG_CVS_IGNORE)) {
1139 rprintf(FERROR, "unexpected end of filter rule: %s\n", *rulestr_ptr);
1140 exit_cleanup(RERR_SYNTAX);
1143 /* --delete-excluded turns an un-modified include/exclude into a
1144 * sender-side rule. We also affect per-dir merge files that take
1145 * no prefixes as a simple optimization. */
1147 && !(filter->flags & MATCHFLGS_SIDES)
1148 && (!(filter->flags & MATCHFLG_PERDIR_MERGE)
1149 || filter->flags & MATCHFLG_NO_PREFIXES))
1150 filter->flags |= MATCHFLG_SENDER_SIDE;
1152 *pat_ptr = (const char *)s;
1154 *rulestr_ptr = *pat_ptr + len;
1159 static char default_cvsignore[] =
1160 /* These default ignored items come from the CVS manual. */
1161 "RCS SCCS CVS CVS.adm RCSLOG cvslog.* tags TAGS"
1162 " .make.state .nse_depinfo *~ #* .#* ,* _$* *$"
1163 " *.old *.bak *.BAK *.orig *.rej .del-*"
1164 " *.a *.olb *.o *.obj *.so *.exe"
1165 " *.Z *.elc *.ln core"
1166 /* The rest we added to suit ourself. */
1167 " .svn/ .git/ .bzr/";
1169 static void get_cvs_excludes(struct filter_struct *template)
1171 static int initialized = 0;
1172 char *p, fname[MAXPATHLEN];
1179 save_mflags = template->flags;
1180 if (protocol_version >= 30)
1181 template->flags |= MATCHFLG_PERISHABLE;
1182 load_filter_str(&cvs_filter_list, default_cvsignore, template, 0);
1183 template->flags = save_mflags;
1185 p = module_id >= 0 && lp_use_chroot(module_id) ? "/" : getenv("HOME");
1186 if (p && pathjoin(fname, MAXPATHLEN, p, ".cvsignore") < MAXPATHLEN)
1187 load_filter_file(&cvs_filter_list, fname, template, 0);
1189 load_filter_str(&cvs_filter_list, getenv("CVSIGNORE"), template, 0);
1193 struct filter_struct *filter_template(uint32 mflags)
1195 static struct filter_struct template; /* zero-initialized */
1196 template.flags = mflags;
1201 void load_filter_str(struct filter_list_struct *listp, const char *rulestr,
1202 struct filter_struct *template, int xflags)
1204 struct filter_struct *filter;
1206 unsigned int pat_len;
1212 /* Remember that the returned string is NOT '\0' terminated! */
1213 filter = parse_rule_tok(&rulestr, template, xflags,
1218 if (pat_len >= MAXPATHLEN) {
1219 rprintf(FERROR, "discarding over-long filter: %.*s\n",
1222 free_filter(filter);
1226 if (filter->flags & MATCHFLG_CLEAR_LIST) {
1227 if (DEBUG_GTE(FILTER, 2)) {
1229 "[%s] clearing filter list%s\n",
1230 who_am_i(), listp->debug_type);
1232 clear_filter_list(listp);
1236 if (filter->flags & MATCHFLG_MERGE_FILE) {
1241 if (filter->flags & MATCHFLG_EXCLUDE_SELF) {
1243 struct filter_struct *excl_self;
1245 if (!(excl_self = new0(struct filter_struct)))
1246 out_of_memory("load_filter_str");
1247 /* Find the beginning of the basename. */
1248 for (name = pat + pat_len; name > pat && name[-1] != '/'; name--)
1250 add_rule(listp, name, (pat + pat_len) - name, excl_self, 0);
1251 filter->flags &= ~MATCHFLG_EXCLUDE_SELF;
1253 if (filter->flags & MATCHFLG_PERDIR_MERGE) {
1254 if (parent_dirscan) {
1256 unsigned int len = pat_len;
1257 if ((p = parse_merge_name(pat, &len,
1259 add_rule(listp, p, len, filter, 0);
1261 free_filter(filter);
1266 unsigned int len = pat_len;
1267 if ((p = parse_merge_name(pat, &len, 0))) {
1268 load_filter_file(listp, p, filter,
1271 free_filter(filter);
1276 if (filter->flags & MATCHFLG_CVS_IGNORE
1277 && !(filter->flags & MATCHFLG_MERGE_FILE))
1278 get_cvs_excludes(filter);
1280 add_rule(listp, pat, pat_len, filter, xflags);
1285 void load_filter_file(struct filter_list_struct *listp, const char *fname,
1286 struct filter_struct *template, int xflags)
1289 char line[BIGPATHBUFLEN];
1290 char *eob = line + sizeof line - 1;
1291 BOOL word_split = (template->flags & MATCHFLG_WORD_SPLIT) != 0;
1293 if (!fname || !*fname)
1296 if (*fname != '-' || fname[1] || am_server) {
1297 if (daemon_filter_list.head) {
1298 strlcpy(line, fname, sizeof line);
1299 clean_fname(line, CFN_COLLAPSE_DOT_DOT_DIRS);
1300 if (check_filter(&daemon_filter_list, FLOG, line, 0) < 0)
1303 fp = fopen(line, "rb");
1305 fp = fopen(fname, "rb");
1309 if (DEBUG_GTE(FILTER, 2)) {
1310 rprintf(FINFO, "[%s] load_filter_file(%s,%x,%x)%s\n",
1311 who_am_i(), fname, template->flags, xflags,
1312 fp ? "" : " [not found]");
1316 if (xflags & XFLG_FATAL_ERRORS) {
1317 rsyserr(FERROR, errno,
1318 "failed to open %sclude file %s",
1319 template->flags & MATCHFLG_INCLUDE ? "in" : "ex",
1321 exit_cleanup(RERR_FILEIO);
1325 dirbuf[dirbuf_len] = '\0';
1329 int ch, overflow = 0;
1331 if ((ch = getc(fp)) == EOF) {
1332 if (ferror(fp) && errno == EINTR) {
1338 if (word_split && isspace(ch))
1340 if (eol_nulls? !ch : (ch == '\n' || ch == '\r'))
1348 rprintf(FERROR, "discarding over-long filter: %s...\n", line);
1352 /* Skip an empty token and (when line parsing) comments. */
1353 if (*line && (word_split || (*line != ';' && *line != '#')))
1354 load_filter_str(listp, line, template, xflags);
1361 /* If the "for_xfer" flag is set, the prefix is made compatible with the
1362 * current protocol_version (if possible) or a NULL is returned (if not
1364 char *get_rule_prefix(struct filter_struct *filter, const char *pat, int for_xfer,
1365 unsigned int *plen_ptr)
1367 static char buf[MAX_RULE_PREFIX+1];
1369 int legal_len = for_xfer && protocol_version < 29 ? 1 : MAX_RULE_PREFIX-1;
1371 if (filter->flags & MATCHFLG_PERDIR_MERGE) {
1375 } else if (filter->flags & MATCHFLG_INCLUDE)
1377 else if (legal_len != 1
1378 || ((*pat == '-' || *pat == '+') && pat[1] == ' '))
1383 if (filter->flags & MATCHFLG_ABS_PATH)
1385 if (filter->flags & MATCHFLG_NEGATE)
1387 if (filter->flags & MATCHFLG_CVS_IGNORE)
1390 if (filter->flags & MATCHFLG_NO_INHERIT)
1392 if (filter->flags & MATCHFLG_WORD_SPLIT)
1394 if (filter->flags & MATCHFLG_NO_PREFIXES) {
1395 if (filter->flags & MATCHFLG_INCLUDE)
1401 if (filter->flags & MATCHFLG_EXCLUDE_SELF)
1403 if (filter->flags & MATCHFLG_SENDER_SIDE
1404 && (!for_xfer || protocol_version >= 29))
1406 if (filter->flags & MATCHFLG_RECEIVER_SIDE
1407 && (!for_xfer || protocol_version >= 29
1408 || (delete_excluded && am_sender)))
1410 if (filter->flags & MATCHFLG_PERISHABLE) {
1411 if (!for_xfer || protocol_version >= 30)
1416 if (filter->flags & MATCHFLGS_ATTRS) {
1417 if (!for_xfer || protocol_version >= 31) {
1418 if (filter->flags & MATCHFLG_CHMOD)
1419 if (!snappendf(&op, (buf + sizeof buf) - op,
1420 "m(%s)", filter->chmod->modestr))
1422 if (filter->flags & MATCHFLG_FORCE_OWNER)
1423 if (!snappendf(&op, (buf + sizeof buf) - op,
1424 "o(%u)", (unsigned)filter->force_uid))
1426 if (filter->flags & MATCHFLG_FORCE_GROUP)
1427 if (!snappendf(&op, (buf + sizeof buf) - op,
1428 "g(%u)", (unsigned)filter->force_gid))
1430 } else if (!am_sender)
1433 if (op - buf > legal_len)
1439 *plen_ptr = op - buf;
1443 static void send_rules(int f_out, struct filter_list_struct *flp)
1445 struct filter_struct *ent, *prev = NULL;
1447 for (ent = flp->head; ent; ent = ent->next) {
1448 unsigned int len, plen, dlen;
1452 /* Note we need to check delete_excluded here in addition to
1453 * the code in parse_rule_tok() because some rules may have
1454 * been added before we found the --delete-excluded option.
1455 * We must also elide any CVS merge-file rules to avoid a
1456 * backward compatibility problem, and we elide any no-prefix
1457 * merge files as an optimization (since they can only have
1458 * include/exclude rules). */
1459 if (ent->flags & MATCHFLG_SENDER_SIDE)
1460 elide = am_sender ? 1 : -1;
1461 if (ent->flags & MATCHFLG_RECEIVER_SIDE)
1462 elide = elide ? 0 : am_sender ? -1 : 1;
1463 else if (delete_excluded && !elide
1464 && (!(ent->flags & MATCHFLG_PERDIR_MERGE)
1465 || ent->flags & MATCHFLG_NO_PREFIXES))
1466 elide = am_sender ? 1 : -1;
1469 prev->next = ent->next;
1471 flp->head = ent->next;
1476 if (ent->flags & MATCHFLG_CVS_IGNORE
1477 && !(ent->flags & MATCHFLG_MERGE_FILE)) {
1478 int f = am_sender || protocol_version < 29 ? f_out : -2;
1479 send_rules(f, &cvs_filter_list);
1483 p = get_rule_prefix(ent, ent->pattern, 1, &plen);
1486 "filter rules are too modern for remote rsync.\n");
1487 exit_cleanup(RERR_PROTOCOL);
1491 len = strlen(ent->pattern);
1492 dlen = ent->flags & MATCHFLG_DIRECTORY ? 1 : 0;
1493 if (!(plen + len + dlen))
1495 write_int(f_out, plen + len + dlen);
1497 write_buf(f_out, p, plen);
1498 write_buf(f_out, ent->pattern, len);
1500 write_byte(f_out, '/');
1505 /* This is only called by the client. */
1506 void send_filter_list(int f_out)
1508 int receiver_wants_list = prune_empty_dirs
1509 || (delete_mode && (!delete_excluded || protocol_version >= 29));
1511 if (local_server || (am_sender && !receiver_wants_list))
1513 if (cvs_exclude && am_sender) {
1514 if (protocol_version >= 29)
1515 load_filter_str(&filter_list, ":C", filter_template(0), 0);
1516 load_filter_str(&filter_list, "-C", filter_template(0), 0);
1519 send_rules(f_out, &filter_list);
1522 write_int(f_out, 0);
1525 if (!am_sender || protocol_version < 29)
1526 load_filter_str(&filter_list, ":C", filter_template(0), 0);
1528 load_filter_str(&filter_list, "-C", filter_template(0), 0);
1532 /* This is only called by the server. */
1533 void recv_filter_list(int f_in)
1535 char line[BIGPATHBUFLEN];
1536 int xflags = protocol_version >= 29 ? 0 : XFLG_OLD_PREFIXES;
1537 int receiver_wants_list = prune_empty_dirs
1539 && (!delete_excluded || protocol_version >= 29));
1542 if (!local_server && (am_sender || receiver_wants_list)) {
1543 while ((len = read_int(f_in)) != 0) {
1544 if (len >= sizeof line)
1545 overflow_exit("recv_rules");
1546 read_sbuf(f_in, line, len);
1547 load_filter_str(&filter_list, line, filter_template(0), xflags);
1552 if (local_server || am_sender || protocol_version < 29)
1553 load_filter_str(&filter_list, ":C", filter_template(0), 0);
1554 if (local_server || am_sender)
1555 load_filter_str(&filter_list, "-C", filter_template(0), 0);
1558 if (local_server) /* filter out any rules that aren't for us. */
1559 send_rules(-1, &filter_list);