Debian Codegraph @

exclude.c

raw symbols SCIP
1 /*
2 * The filter include/exclude routines.
3 *
4 * Copyright (C) 1996-2001 Andrew Tridgell <[email protected]>
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2002 Martin Pool
7 * Copyright (C) 2003-2024 Wayne Davison
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, visit the http://fsf.org website.
21 */
22
23 #include "rsync.h"
24 #include "ifuncs.h"
25
26 extern int am_server;
27 extern int am_sender;
28 extern int am_generator;
29 extern int eol_nulls;
30 extern int io_error;
31 extern int xfer_dirs;
32 extern int recurse;
33 extern int local_server;
34 extern int prune_empty_dirs;
35 extern int ignore_perishable;
36 extern int relative_paths;
37 extern int delete_mode;
38 extern int delete_excluded;
39 extern int cvs_exclude;
40 extern int sanitize_paths;
41 extern int protocol_version;
42 extern int trust_sender_args;
43 extern int module_id;
44 extern int operator_path_resolve;
45
46 /* Set while the daemon loads its own filter parameters; see parse_filter_file(). */
47 int daemon_config_filter_file = 0;
48
49 /* Where the rule text now being parsed came from, when that is a file's
50 * CONTENTS rather than an argument. A rule that fails to parse used to be
51 * echoed back verbatim, and the peer chooses which file gets merged (a
52 * per-directory merge rule travels over the protocol, so no argument of ours
53 * ever names it), which made the filter parser a read-any-line oracle: any
54 * line that is not valid filter syntax came straight back in the error.
55 * Report where the bad rule is, not what it says. */
56 static int rule_src_in_file = 0; /* parsing a file's contents right now */
57 static const char *rule_src_file = NULL; /* ...and its name is safe to show */
58 static int rule_src_line = 0;
59 /* Where a file whose own name we must NOT print was named, which is a location
60 * we CAN print: it keeps the diagnostic useful without echoing the pathname a
61 * merge rule supplied. */
62 static const char *rule_src_named_at = NULL;
63
64 /* True while the text we are handling came out of a file's contents: either we
65 * are parsing that file right now, or this is a deferred per-dir merge whose
66 * NAME came from one and which carries the provenance on the rule. */
67 #define TEXT_FROM_FILE(template) \
68 (rule_src_in_file \
69 || ((template) && (template)->rflags & FILTRULE_FROM_FILE))
70
71 /* "FILE line N", or just "FILE" when the count is not a line count. */
72 static const char *rule_src_where(void)
73 {
74 static char buf[MAXPATHLEN + 32];
75
76 if (!rule_src_file) {
77 if (!rule_src_named_at)
78 return "a file read earlier"; /* origin not retained */
79 snprintf(buf, sizeof buf, "a file named at %s", rule_src_named_at);
80 return buf;
81 }
82 if (rule_src_line < 0)
83 return rule_src_file;
84 snprintf(buf, sizeof buf, "%s line %d", rule_src_file, rule_src_line);
85 return buf;
86 }
87
88 /* THE chokepoint. Every diagnostic string that is, or is built from, a filter
89 * rule's own text -- a pattern, a merge-file name, a path composed from one --
90 * must be passed through rule_text() on its way to rprintf(). When the rule
91 * came from an argument the text is returned unchanged, because it is the
92 * user's own and hiding it only makes typos harder to fix. When it came from
93 * a FILE's contents it is replaced by a description of where it came from,
94 * because the peer chooses which file gets merged and any line of it that
95 * reaches a message is a line the peer can read back.
96 *
97 * Doing it here rather than at each site is the point: a message added later
98 * cannot reintroduce the leak by forgetting to check, and there is one place
99 * to audit. `template' is the rule the text belongs to, or NULL when the only
100 * thing that matters is whether we are parsing a file right now.
101 *
102 * The returned buffer is rotated, so two calls in one rprintf() are safe. */
103 static const char *rule_text_len(const filter_rule *template,
104 const char *text, int len)
105 {
106 static char buf[2][BIGPATHBUFLEN];
107 static int which = 0;
108 char *b = buf[which];
109
110 which ^= 1;
111 if (!TEXT_FROM_FILE(template)) {
112 if (len < 0)
113 return text;
114 snprintf(b, sizeof buf[0], "%.*s", len, text);
115 return b;
116 }
117 snprintf(b, sizeof buf[0], "<rule from %s>", rule_src_where());
118 return b;
119 }
120
121 static const char *rule_text(const filter_rule *template, const char *text)
122 {
123 return rule_text_len(template, text, -1);
124 }
125
126 /* For the extra detail some messages add ABOUT the text -- a character of it,
127 * an offset into it. Dropped along with the text it describes. */
128 static const char *rule_detail(const filter_rule *template, const char *detail)
129 {
130 return TEXT_FROM_FILE(template) ? "" : detail;
131 }
132
133 static void filter_rule_err(const char *msg, const char *rulestr)
134 {
135 rprintf(FERROR, "%s: %s\n", msg, rule_text(NULL, rulestr));
136 exit_cleanup(RERR_SYNTAX);
137 }
138
139 extern char curr_dir[MAXPATHLEN];
140 extern unsigned int curr_dir_len;
141 extern unsigned int module_dirlen;
142
143 filter_rule_list filter_list = { .debug_type = "" };
144 filter_rule_list cvs_filter_list = { .debug_type = " [global CVS]" };
145 filter_rule_list daemon_filter_list = { .debug_type = " [daemon]" };
146 filter_rule_list implied_filter_list = { .debug_type = " [implied]" };
147
148 int saw_xattr_filter = 0;
149 int trust_sender_args = 0;
150 int trust_sender_filter = 0;
151
152 /* Need room enough for ":MODS " prefix plus some room to grow. */
153 #define MAX_RULE_PREFIX (16)
154
155 #define SLASH_WILD3_SUFFIX "/***"
156
157 /* The dirbuf is set by push_local_filters() to the current subdirectory
158 * relative to curr_dir that is being processed. The path always has a
159 * trailing slash appended, and the variable dirbuf_len contains the length
160 * of this path prefix. The path is always absolute. */
161 static char dirbuf[MAXPATHLEN+1];
162 static unsigned int dirbuf_len = 0;
163 static int dirbuf_depth;
164
165 /* This is True when we're scanning parent dirs for per-dir merge-files. */
166 static BOOL parent_dirscan = False;
167
168 #define MAX_MERGE_DEPTH 32
169 static int merge_depth = 0;
170
171 /* This array contains a list of all the currently active per-dir merge
172 * files. This makes it easier to save the appropriate values when we
173 * "push" down into each subdirectory. */
174 static filter_rule **mergelist_parents;
175 static int mergelist_cnt = 0;
176 static int mergelist_size = 0;
177
178 #define LOCAL_RULE 1
179 #define REMOTE_RULE 2
180 static uchar cur_elide_value = REMOTE_RULE;
181
182 /* Each filter_list_struct describes a singly-linked list by keeping track
183 * of both the head and tail pointers. The list is slightly unusual in that
184 * a parent-dir's content can be appended to the end of the local list in a
185 * special way: the last item in the local list has its "next" pointer set
186 * to point to the inherited list, but the local list's tail pointer points
187 * at the end of the local list. Thus, if the local list is empty, the head
188 * will be pointing at the inherited content but the tail will be NULL. To
189 * help you visualize this, here are the possible list arrangements:
190 *
191 * Completely Empty Local Content Only
192 * ================================== ====================================
193 * head -> NULL head -> Local1 -> Local2 -> NULL
194 * tail -> NULL tail -------------^
195 *
196 * Inherited Content Only Both Local and Inherited Content
197 * ================================== ====================================
198 * head -> Parent1 -> Parent2 -> NULL head -> L1 -> L2 -> P1 -> P2 -> NULL
199 * tail -> NULL tail ---------^
200 *
201 * This means that anyone wanting to traverse the whole list to use it just
202 * needs to start at the head and use the "next" pointers until it goes
203 * NULL. To add new local content, we insert the item after the tail item
204 * and update the tail (obviously, if "tail" was NULL, we insert it at the
205 * head). To clear the local list, WE MUST NOT FREE THE INHERITED CONTENT
206 * because it is shared between the current list and our parent list(s).
207 * The easiest way to handle this is to simply truncate the list after the
208 * tail item and then free the local list from the head. When inheriting
209 * the list for a new local dir, we just save off the filter_list_struct
210 * values (so we can pop back to them later) and set the tail to NULL.
211 */
212
213 static void teardown_mergelist(filter_rule *ex)
214 {
215 int j;
216
217 if (!ex->u.mergelist)
218 return;
219
220 if (DEBUG_GTE(FILTER, 2)) {
221 rprintf(FINFO, "[%s] deactivating mergelist #%d%s\n",
222 who_am_i(), mergelist_cnt - 1,
223 ex->u.mergelist->debug_type);
224 }
225
226 free(ex->u.mergelist->debug_type);
227 free(ex->u.mergelist);
228
229 for (j = 0; j < mergelist_cnt; j++) {
230 if (mergelist_parents[j] == ex) {
231 mergelist_parents[j] = NULL;
232 break;
233 }
234 }
235 while (mergelist_cnt && mergelist_parents[mergelist_cnt-1] == NULL)
236 mergelist_cnt--;
237 }
238
239 static void free_filter(filter_rule *ex)
240 {
241 if (ex->rflags & FILTRULE_PERDIR_MERGE)
242 teardown_mergelist(ex);
243 free(ex->pattern);
244 free(ex);
245 }
246
247 static void free_filters(filter_rule *ent)
248 {
249 while (ent) {
250 filter_rule *next = ent->next;
251 free_filter(ent);
252 ent = next;
253 }
254 }
255
256 /* Build a filter structure given a filter pattern. The value in "pat"
257 * is not null-terminated. "rule" is either held or freed, so the
258 * caller should not free it. */
259 static void add_rule(filter_rule_list *listp, const char *pat, unsigned int pat_len,
260 filter_rule *rule, int xflags)
261 {
262 const char *cp;
263 unsigned int pre_len, suf_len, slash_cnt = 0;
264 char *mention_rule_suffix;
265
266 if (DEBUG_GTE(FILTER, 1) && pat_len && (pat[pat_len-1] == ' ' || pat[pat_len-1] == '\t'))
267 mention_rule_suffix = " -- CAUTION: trailing whitespace!";
268 else
269 mention_rule_suffix = DEBUG_GTE(FILTER, 2) ? "" : NULL;
270 if (mention_rule_suffix) {
271 rprintf(FINFO, "[%s] add_rule(%s%s)%s%s\n",
272 who_am_i(), rule_detail(rule, get_rule_prefix(rule, pat, 0, NULL)),
273 rule_text_len(rule, pat, (int)pat_len),
274 listp->debug_type, rule_detail(rule, mention_rule_suffix));
275 }
276
277 /* These flags also indicate that we're reading a list that
278 * needs to be filtered now, not post-filtered later. */
279 if (xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH)
280 && (rule->rflags & FILTRULES_SIDES)
281 == (am_sender ? FILTRULE_RECEIVER_SIDE : FILTRULE_SENDER_SIDE)) {
282 /* This filter applies only to the other side. Drop it. */
283 free_filter(rule);
284 return;
285 }
286
287 if (pat_len > 1 && pat[pat_len-1] == '/') {
288 pat_len--;
289 rule->rflags |= FILTRULE_DIRECTORY;
290 }
291
292 for (cp = pat; cp < pat + pat_len; cp++) {
293 if (*cp == '/')
294 slash_cnt++;
295 }
296
297 if (!(rule->rflags & (FILTRULE_ABS_PATH | FILTRULE_MERGE_FILE))
298 && ((xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH) && *pat == '/')
299 || (xflags & XFLG_ABS_IF_SLASH && slash_cnt))) {
300 rule->rflags |= FILTRULE_ABS_PATH;
301 if (*pat == '/')
302 pre_len = dirbuf_len - module_dirlen - 1;
303 else
304 pre_len = 0;
305 } else
306 pre_len = 0;
307
308 /* The daemon wants dir-exclude rules to get an appended "/" + "***". */
309 if (xflags & XFLG_DIR2WILD3
310 && BITS_SETnUNSET(rule->rflags, FILTRULE_DIRECTORY, FILTRULE_INCLUDE)) {
311 rule->rflags &= ~FILTRULE_DIRECTORY;
312 suf_len = sizeof SLASH_WILD3_SUFFIX - 1;
313 } else
314 suf_len = 0;
315
316 rule->pattern = new_array(char, pre_len + pat_len + suf_len + 1);
317 if (pre_len) {
318 memcpy(rule->pattern, dirbuf + module_dirlen, pre_len);
319 for (cp = rule->pattern; cp < rule->pattern + pre_len; cp++) {
320 if (*cp == '/')
321 slash_cnt++;
322 }
323 }
324 rule->elide = 0;
325 strlcpy(rule->pattern + pre_len, pat, pat_len + 1);
326 pat_len += pre_len;
327 if (suf_len) {
328 memcpy(rule->pattern + pat_len, SLASH_WILD3_SUFFIX, suf_len+1);
329 pat_len += suf_len;
330 slash_cnt++;
331 }
332
333 if (strpbrk(rule->pattern, "*[?")) {
334 rule->rflags |= FILTRULE_WILD;
335 if ((cp = strstr(rule->pattern, "**")) != NULL) {
336 rule->rflags |= FILTRULE_WILD2;
337 /* If the pattern starts with **, note that. */
338 if (cp == rule->pattern)
339 rule->rflags |= FILTRULE_WILD2_PREFIX;
340 /* If the pattern ends with ***, note that. */
341 if (pat_len >= 3
342 && rule->pattern[pat_len-3] == '*'
343 && rule->pattern[pat_len-2] == '*'
344 && rule->pattern[pat_len-1] == '*')
345 rule->rflags |= FILTRULE_WILD3_SUFFIX;
346 }
347 }
348
349 if (rule->rflags & FILTRULE_PERDIR_MERGE) {
350 filter_rule_list *lp;
351 unsigned int len;
352 int i;
353
354 if ((cp = strrchr(rule->pattern, '/')) != NULL)
355 cp++;
356 else
357 cp = rule->pattern;
358
359 /* If the local merge file was already mentioned, don't
360 * add it again. */
361 for (i = 0; i < mergelist_cnt; i++) {
362 filter_rule *ex = mergelist_parents[i];
363 const char *s;
364 if (!ex)
365 continue;
366 s = strrchr(ex->pattern, '/');
367 if (s)
368 s++;
369 else
370 s = ex->pattern;
371 len = strlen(s);
372 if (len == pat_len - (cp - rule->pattern) && memcmp(s, cp, len) == 0) {
373 free_filter(rule);
374 return;
375 }
376 }
377
378 lp = new_array0(filter_rule_list, 1);
379 if (asprintf(&lp->debug_type, " [per-dir %s]", rule_text(rule, cp)) < 0)
380 out_of_memory("add_rule");
381 rule->u.mergelist = lp;
382
383 if (mergelist_cnt == mergelist_size) {
384 mergelist_size += 5;
385 mergelist_parents = realloc_array(mergelist_parents, filter_rule *, mergelist_size);
386 }
387 if (DEBUG_GTE(FILTER, 2)) {
388 rprintf(FINFO, "[%s] activating mergelist #%d%s\n",
389 who_am_i(), mergelist_cnt, lp->debug_type);
390 }
391 mergelist_parents[mergelist_cnt++] = rule;
392 } else
393 rule->u.slash_cnt = slash_cnt;
394
395 if (!listp->tail) {
396 rule->next = listp->head;
397 listp->head = listp->tail = rule;
398 } else {
399 rule->next = listp->tail->next;
400 listp->tail->next = rule;
401 listp->tail = rule;
402 }
403 }
404
405 /* If the wildcards failed, the remote shell might give us a file matching the literal
406 * wildcards. Since "*" & "?" already match themselves, this just needs to deal with
407 * failed "[foo]" idioms.
408 */
409 static void maybe_add_literal_brackets_rule(filter_rule const *based_on, int arg_len)
410 {
411 filter_rule *rule;
412 const char *arg = based_on->pattern, *cp;
413 char *p;
414 int cnt = 0;
415
416 if (arg_len < 0)
417 arg_len = strlen(arg);
418
419 for (cp = arg; *cp; cp++) {
420 if (*cp == '\\' && cp[1]) {
421 cp++;
422 } else if (*cp == '[')
423 cnt++;
424 }
425 if (!cnt)
426 return;
427
428 rule = new0(filter_rule);
429 rule->rflags = based_on->rflags;
430 rule->u.slash_cnt = based_on->u.slash_cnt;
431 p = rule->pattern = new_array(char, arg_len + cnt + 1);
432 for (cp = arg; *cp; ) {
433 if (*cp == '\\' && cp[1]) {
434 *p++ = *cp++;
435 } else if (*cp == '[')
436 *p++ = '\\';
437 *p++ = *cp++;
438 }
439 *p++ = '\0';
440
441 rule->next = implied_filter_list.head;
442 implied_filter_list.head = rule;
443 if (DEBUG_GTE(FILTER, 3)) {
444 rprintf(FINFO, "[%s] add_implied_include(%s%s)\n", who_am_i(), rule->pattern,
445 rule->rflags & FILTRULE_DIRECTORY ? "/" : "");
446 }
447 }
448
449 static char *partial_string_buf = NULL;
450 static int partial_string_len = 0;
451 void implied_include_partial_string(const char *s_start, const char *s_end)
452 {
453 partial_string_len = s_end - s_start;
454 if (partial_string_len <= 0 || partial_string_len >= MAXPATHLEN) { /* too-large should be impossible... */
455 partial_string_len = 0;
456 return;
457 }
458 if (!partial_string_buf)
459 partial_string_buf = new_array(char, MAXPATHLEN);
460 memcpy(partial_string_buf, s_start, partial_string_len);
461 }
462
463 void free_implied_include_partial_string()
464 {
465 if (partial_string_buf) {
466 if (partial_string_len)
467 add_implied_include("", 0);
468 free(partial_string_buf);
469 partial_string_buf = NULL;
470 }
471 partial_string_len = 0; /* paranoia */
472 }
473
474 /* Each arg the client sends to the remote sender turns into an implied include
475 * that the receiver uses to validate the file list from the sender. */
476 void add_implied_include(const char *arg, int skip_daemon_module)
477 {
478 int arg_len, saw_wild = 0, saw_live_open_brkt = 0, backslash_cnt = 0;
479 int slash_cnt = 0;
480 const char *cp;
481 char *p;
482 if (trust_sender_args)
483 return;
484 if (partial_string_len) {
485 arg_len = strlen(arg);
486 if (partial_string_len + arg_len >= MAXPATHLEN) {
487 partial_string_len = 0;
488 return; /* Should be impossible... */
489 }
490 memcpy(partial_string_buf + partial_string_len, arg, arg_len + 1);
491 partial_string_len = 0;
492 arg = partial_string_buf;
493 }
494 if (skip_daemon_module) {
495 if ((cp = strchr(arg, '/')) != NULL)
496 arg = cp + 1;
497 else
498 arg = "";
499 }
500 if (relative_paths) {
501 if ((cp = strstr(arg, "/./")) != NULL)
502 arg = cp + 3;
503 } else if ((cp = strrchr(arg, '/')) != NULL) {
504 arg = cp + 1;
505 }
506 if (*arg == '.' && arg[1] == '\0')
507 arg++;
508 arg_len = strlen(arg);
509 if (arg_len) {
510 char *new_pat;
511 if (strpbrk(arg, "*[?")) {
512 /* We need to add room to escape backslashes if wildcard chars are present. */
513 for (cp = arg; (cp = strchr(cp, '\\')) != NULL; cp++)
514 arg_len++;
515 saw_wild = 1;
516 }
517 arg_len++; /* Leave room for the prefixed slash */
518 p = new_pat = new_array(char, arg_len + 1);
519 *p++ = '/';
520 slash_cnt++;
521 for (cp = arg; *cp; ) {
522 switch (*cp) {
523 case '\\':
524 if (cp[1] == ']') {
525 if (!saw_wild)
526 cp++; /* A \] in a non-wild filter causes a problem, so drop the \ . */
527 } else if (!cp[1] || !strchr("*[?", cp[1])) {
528 backslash_cnt++;
529 if (saw_wild)
530 *p++ = '\\';
531 }
532 *p++ = *cp++;
533 break;
534 case '/':
535 if (p[-1] == '/') { /* This is safe because of the initial slash. */
536 if (*++cp == '\0') {
537 slash_cnt--;
538 p--;
539 }
540 } else if (cp[1] == '\0') {
541 cp++;
542 } else {
543 slash_cnt++;
544 *p++ = *cp++;
545 }
546 break;
547 case '.':
548 if (p[-1] == '/') {
549 if (cp[1] == '/') {
550 cp += 2;
551 if (!*cp) {
552 slash_cnt--;
553 p--;
554 }
555 } else if (cp[1] == '\0') {
556 cp++;
557 slash_cnt--;
558 p--;
559 } else
560 *p++ = *cp++;
561 } else
562 *p++ = *cp++;
563 break;
564 case '[':
565 saw_live_open_brkt = 1;
566 *p++ = *cp++;
567 break;
568 default:
569 *p++ = *cp++;
570 break;
571 }
572 }
573 *p = '\0';
574 arg_len = p - new_pat;
575 if (!arg_len)
576 free(new_pat);
577 else {
578 filter_rule *rule = new0(filter_rule);
579 rule->rflags = FILTRULE_INCLUDE + (saw_wild ? FILTRULE_WILD : 0);
580 rule->u.slash_cnt = slash_cnt;
581 arg = rule->pattern = new_pat;
582 if (!implied_filter_list.head)
583 implied_filter_list.head = implied_filter_list.tail = rule;
584 else {
585 rule->next = implied_filter_list.head;
586 implied_filter_list.head = rule;
587 }
588 if (DEBUG_GTE(FILTER, 3))
589 rprintf(FINFO, "[%s] add_implied_include(%s)\n", who_am_i(), arg);
590 if (saw_live_open_brkt)
591 maybe_add_literal_brackets_rule(rule, arg_len);
592 if (relative_paths && slash_cnt) {
593 int sub_slash_cnt = slash_cnt;
594 while ((p = strrchr(new_pat, '/')) != NULL && p != new_pat) {
595 filter_rule const *ent;
596 filter_rule *R_rule;
597 int found = 0;
598 *p = '\0';
599 for (ent = implied_filter_list.head; ent; ent = ent->next) {
600 if (ent != rule && strcmp(ent->pattern, new_pat) == 0) {
601 found = 1;
602 break;
603 }
604 }
605 if (found) {
606 *p = '/';
607 break; /* We added all parent dirs already */
608 }
609 R_rule = new0(filter_rule);
610 R_rule->rflags = FILTRULE_INCLUDE | FILTRULE_DIRECTORY;
611 /* Check if our sub-path has wildcards or escaped backslashes */
612 if (saw_wild && strpbrk(new_pat, "*[?\\"))
613 R_rule->rflags |= FILTRULE_WILD;
614 R_rule->pattern = strdup(new_pat);
615 R_rule->u.slash_cnt = --sub_slash_cnt;
616 R_rule->next = implied_filter_list.head;
617 implied_filter_list.head = R_rule;
618 if (DEBUG_GTE(FILTER, 3)) {
619 rprintf(FINFO, "[%s] add_implied_include(%s/)\n",
620 who_am_i(), R_rule->pattern);
621 }
622 if (saw_live_open_brkt)
623 maybe_add_literal_brackets_rule(R_rule, -1);
624 }
625 for (p = new_pat; sub_slash_cnt < slash_cnt; sub_slash_cnt++) {
626 p += strlen(p);
627 *p = '/';
628 }
629 }
630 }
631 }
632
633 if (recurse || xfer_dirs) {
634 /* Now create a rule with an added "/" & "**" or "*" at the end */
635 filter_rule *rule = new0(filter_rule);
636 rule->rflags = FILTRULE_INCLUDE | FILTRULE_WILD;
637 if (recurse)
638 rule->rflags |= FILTRULE_WILD2;
639 /* We must leave enough room for / * * \0. */
640 if (!saw_wild && backslash_cnt) {
641 /* We are appending a wildcard, so now the backslashes need to be escaped. */
642 p = rule->pattern = new_array(char, arg_len + backslash_cnt + 3 + 1);
643 for (cp = arg; *cp; ) { /* Note that arg_len != 0 because backslash_cnt > 0 */
644 if (*cp == '\\')
645 *p++ = '\\';
646 *p++ = *cp++;
647 }
648 } else {
649 p = rule->pattern = new_array(char, arg_len + 3 + 1);
650 if (arg_len) {
651 memcpy(p, arg, arg_len);
652 p += arg_len;
653 }
654 }
655 *p++ = '/';
656 *p++ = '*';
657 if (recurse)
658 *p++ = '*';
659 *p = '\0';
660 rule->u.slash_cnt = slash_cnt + 1;
661 rule->next = implied_filter_list.head;
662 implied_filter_list.head = rule;
663 if (DEBUG_GTE(FILTER, 3))
664 rprintf(FINFO, "[%s] add_implied_include(%s)\n", who_am_i(), rule->pattern);
665 if (saw_live_open_brkt)
666 maybe_add_literal_brackets_rule(rule, p - rule->pattern);
667 }
668 }
669
670 /* This frees any non-inherited items, leaving just inherited items on the list. */
671 static void pop_filter_list(filter_rule_list *listp)
672 {
673 filter_rule *inherited;
674
675 if (!listp->tail)
676 return;
677
678 inherited = listp->tail->next;
679
680 /* Truncate any inherited items from the local list. */
681 listp->tail->next = NULL;
682 /* Now free everything that is left. */
683 free_filters(listp->head);
684
685 listp->head = inherited;
686 listp->tail = NULL;
687 }
688
689 /* This returns an expanded (absolute) filename for the merge-file name if
690 * the name has any slashes in it OR if the parent_dirscan var is True;
691 * otherwise it returns the original merge_file name. If the len_ptr value
692 * is non-NULL the merge_file name is limited by the referenced length
693 * value and will be updated with the length of the resulting name. We
694 * always return a name that is null terminated, even if the merge_file
695 * name was not. */
696 static char *parse_merge_name(const filter_rule *template,
697 const char *merge_file, unsigned int *len_ptr,
698 unsigned int prefix_skip)
699 {
700 static char buf[MAXPATHLEN];
701 char *fn, tmpbuf[MAXPATHLEN];
702 unsigned int fn_len;
703
704 if (!parent_dirscan && *merge_file != '/') {
705 /* Return the name unchanged it doesn't have any slashes. */
706 if (len_ptr) {
707 const char *p = merge_file + *len_ptr;
708 while (--p > merge_file && *p != '/') {}
709 if (p == merge_file) {
710 strlcpy(buf, merge_file, *len_ptr + 1);
711 return buf;
712 }
713 } else if (strchr(merge_file, '/') == NULL)
714 return (char *)merge_file;
715 }
716
717 fn = *merge_file == '/' ? buf : tmpbuf;
718 if (sanitize_paths) {
719 const char *r = prefix_skip ? "/" : NULL;
720 /* null-terminate the name if it isn't already */
721 if (len_ptr && merge_file[*len_ptr]) {
722 char *to = fn == buf ? tmpbuf : buf;
723 strlcpy(to, merge_file, *len_ptr + 1);
724 merge_file = to;
725 }
726 if (!sanitize_path(fn, merge_file, r, dirbuf_depth, SP_DEFAULT)) {
727 rprintf(FERROR, "merge-file name overflows: %s\n",
728 rule_text(template, merge_file));
729 return NULL;
730 }
731 fn_len = strlen(fn);
732 } else {
733 strlcpy(fn, merge_file, len_ptr ? *len_ptr + 1 : MAXPATHLEN);
734 fn_len = clean_fname(fn, CFN_COLLAPSE_DOT_DOT_DIRS);
735 }
736
737 /* If the name isn't in buf yet, it wasn't absolute. */
738 if (fn != buf) {
739 int d_len = dirbuf_len - prefix_skip;
740 if (d_len + fn_len >= MAXPATHLEN) {
741 rprintf(FERROR, "merge-file name overflows: %s\n",
742 rule_text(template, fn));
743 return NULL;
744 }
745 memcpy(buf, dirbuf + prefix_skip, d_len);
746 memcpy(buf + d_len, fn, fn_len + 1);
747 fn_len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
748 }
749
750 if (len_ptr)
751 *len_ptr = fn_len;
752 return buf;
753 }
754
755 /* Sets the dirbuf and dirbuf_len values. */
756 void set_filter_dir(const char *dir, unsigned int dirlen)
757 {
758 unsigned int len;
759 if (*dir != '/') {
760 memcpy(dirbuf, curr_dir, curr_dir_len);
761 dirbuf[curr_dir_len] = '/';
762 len = curr_dir_len + 1;
763 if (len + dirlen >= MAXPATHLEN)
764 dirlen = 0;
765 } else
766 len = 0;
767 memcpy(dirbuf + len, dir, dirlen);
768 dirbuf[dirlen + len] = '\0';
769 dirbuf_len = clean_fname(dirbuf, CFN_COLLAPSE_DOT_DOT_DIRS);
770 if (dirbuf_len > 1 && dirbuf[dirbuf_len-1] == '.'
771 && dirbuf[dirbuf_len-2] == '/')
772 dirbuf_len -= 2;
773 if (dirbuf_len != 1)
774 dirbuf[dirbuf_len++] = '/';
775 dirbuf[dirbuf_len] = '\0';
776 if (sanitize_paths)
777 dirbuf_depth = count_dir_elements(dirbuf + module_dirlen);
778 }
779
780 /* This routine takes a per-dir merge-file entry and finishes its setup.
781 * If the name has a path portion then we check to see if it refers to a
782 * parent directory of the first transfer dir. If it does, we scan all the
783 * dirs from that point through the parent dir of the transfer dir looking
784 * for the per-dir merge-file in each one. */
785 static BOOL setup_merge_file(int mergelist_num, filter_rule *ex,
786 filter_rule_list *lp)
787 {
788 char buf[MAXPATHLEN];
789 char *x, *y, *pat = ex->pattern;
790 unsigned int len;
791
792 if (!(x = parse_merge_name(ex, pat, NULL, 0)) || *x != '/')
793 return 0;
794
795 if (DEBUG_GTE(FILTER, 2)) {
796 rprintf(FINFO, "[%s] performing parent_dirscan for mergelist #%d%s\n",
797 who_am_i(), mergelist_num, lp->debug_type);
798 }
799 y = strrchr(x, '/');
800 *y = '\0';
801 ex->pattern = strdup(y+1);
802 if (!*x)
803 x = "/";
804 if (*x == '/')
805 strlcpy(buf, x, MAXPATHLEN);
806 else
807 pathjoin(buf, MAXPATHLEN, dirbuf, x);
808
809 len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
810 if (len != 1 && len < MAXPATHLEN-1) {
811 buf[len++] = '/';
812 buf[len] = '\0';
813 }
814 /* This ensures that the specified dir is a parent of the transfer. */
815 for (x = buf, y = dirbuf; *x && *x == *y; x++, y++) {}
816 if (*x)
817 y += strlen(y); /* nope -- skip the scan */
818
819 parent_dirscan = True;
820 while (*y) {
821 char save[MAXPATHLEN];
822 /* copylen is strlen(y) which is < MAXPATHLEN. +1 for \0 */
823 size_t copylen = strlcpy(save, y, MAXPATHLEN) + 1;
824 *y = '\0';
825 dirbuf_len = y - dirbuf;
826 strlcpy(x, ex->pattern, MAXPATHLEN - (x - buf));
827 parse_filter_file(lp, buf, ex, XFLG_ANCHORED2ABS);
828 if (ex->rflags & FILTRULE_NO_INHERIT) {
829 /* Free the undesired rules to clean up any per-dir
830 * mergelists they defined. Otherwise pop_local_filters
831 * may crash trying to restore nonexistent state for
832 * those mergelists. */
833 free_filters(lp->head);
834 lp->head = NULL;
835 }
836 lp->tail = NULL;
837 strlcpy(y, save, copylen);
838 while ((*x++ = *y++) != '/') {}
839 }
840 parent_dirscan = False;
841 if (DEBUG_GTE(FILTER, 2)) {
842 rprintf(FINFO, "[%s] completed parent_dirscan for mergelist #%d%s\n",
843 who_am_i(), mergelist_num, lp->debug_type);
844 }
845 free(pat);
846 return 1;
847 }
848
849 struct local_filter_state {
850 int mergelist_cnt;
851 filter_rule_list mergelists[1];
852 };
853
854 /* Each time rsync changes to a new directory it call this function to
855 * handle all the per-dir merge-files. The "dir" value is the current path
856 * relative to curr_dir (which might not be null-terminated). We copy it
857 * into dirbuf so that we can easily append a file name on the end. */
858 void *push_local_filters(const char *dir, unsigned int dirlen)
859 {
860 struct local_filter_state *push;
861 int i;
862
863 set_filter_dir(dir, dirlen);
864 if (DEBUG_GTE(FILTER, 2)) {
865 rprintf(FINFO, "[%s] pushing local filters for %s\n",
866 who_am_i(), dirbuf);
867 }
868
869 if (!mergelist_cnt) {
870 /* No old state to save and no new merge files to push. */
871 return NULL;
872 }
873
874 push = (struct local_filter_state *)new_array(char,
875 sizeof (struct local_filter_state)
876 + (mergelist_cnt-1) * sizeof (filter_rule_list));
877
878 push->mergelist_cnt = mergelist_cnt;
879 for (i = 0; i < mergelist_cnt; i++) {
880 filter_rule *ex = mergelist_parents[i];
881 if (!ex)
882 continue;
883 memcpy(&push->mergelists[i], ex->u.mergelist, sizeof (filter_rule_list));
884 }
885
886 /* Note: parse_filter_file() might increase mergelist_cnt, so keep
887 * this loop separate from the above loop. */
888 for (i = 0; i < mergelist_cnt; i++) {
889 filter_rule *ex = mergelist_parents[i];
890 filter_rule_list *lp;
891 if (!ex)
892 continue;
893 lp = ex->u.mergelist;
894
895 if (DEBUG_GTE(FILTER, 2)) {
896 rprintf(FINFO, "[%s] pushing mergelist #%d%s\n",
897 who_am_i(), i, lp->debug_type);
898 }
899
900 lp->tail = NULL; /* Switch any local rules to inherited. */
901 if (ex->rflags & FILTRULE_NO_INHERIT)
902 lp->head = NULL;
903
904 if (ex->rflags & FILTRULE_FINISH_SETUP) {
905 ex->rflags &= ~FILTRULE_FINISH_SETUP;
906 if (setup_merge_file(i, ex, lp))
907 set_filter_dir(dir, dirlen);
908 }
909
910 if (strlcpy(dirbuf + dirbuf_len, ex->pattern,
911 MAXPATHLEN - dirbuf_len) < MAXPATHLEN - dirbuf_len) {
912 parse_filter_file(lp, dirbuf, ex,
913 XFLG_ANCHORED2ABS);
914 } else {
915 io_error |= IOERR_GENERAL;
916 rprintf(FERROR,
917 "cannot add local filter rules in long-named directory: %s\n",
918 rule_text(ex, full_fname(dirbuf)));
919 }
920 dirbuf[dirbuf_len] = '\0';
921 }
922
923 return (void*)push;
924 }
925
926 void pop_local_filters(void *mem)
927 {
928 struct local_filter_state *pop = (struct local_filter_state *)mem;
929 int i;
930 int old_mergelist_cnt = pop ? pop->mergelist_cnt : 0;
931
932 if (DEBUG_GTE(FILTER, 2))
933 rprintf(FINFO, "[%s] popping local filters\n", who_am_i());
934
935 for (i = mergelist_cnt; i-- > 0; ) {
936 filter_rule *ex = mergelist_parents[i];
937 filter_rule_list *lp;
938 if (!ex)
939 continue;
940 lp = ex->u.mergelist;
941
942 if (DEBUG_GTE(FILTER, 2)) {
943 rprintf(FINFO, "[%s] popping mergelist #%d%s\n",
944 who_am_i(), i, lp->debug_type);
945 }
946
947 pop_filter_list(lp);
948 if (i >= old_mergelist_cnt && lp->head) {
949 /* This mergelist does not exist in the state to be restored, but it
950 * still has inherited rules. This can sometimes happen if a per-dir
951 * merge file calls setup_merge_file() in push_local_filters() and that
952 * leaves some inherited rules that aren't in the pushed list state. */
953 if (DEBUG_GTE(FILTER, 2)) {
954 rprintf(FINFO, "[%s] freeing parent_dirscan filters of mergelist #%d%s\n",
955 who_am_i(), i, ex->u.mergelist->debug_type);
956 }
957 pop_filter_list(lp);
958 }
959 }
960
961 if (!pop)
962 return; /* No state to restore. */
963
964 for (i = 0; i < old_mergelist_cnt; i++) {
965 filter_rule *ex = mergelist_parents[i];
966 if (!ex)
967 continue;
968 memcpy(ex->u.mergelist, &pop->mergelists[i], sizeof (filter_rule_list));
969 }
970
971 free(pop);
972 }
973
974 void change_local_filter_dir(const char *dname, int dlen, int dir_depth)
975 {
976 static int cur_depth = -1;
977 static void *filt_array[MAXPATHLEN/2+1];
978
979 if (!dname) {
980 for ( ; cur_depth >= 0; cur_depth--) {
981 if (filt_array[cur_depth]) {
982 pop_local_filters(filt_array[cur_depth]);
983 filt_array[cur_depth] = NULL;
984 }
985 }
986 return;
987 }
988
989 assert(dir_depth < MAXPATHLEN/2+1);
990
991 for ( ; cur_depth >= dir_depth; cur_depth--) {
992 if (filt_array[cur_depth]) {
993 pop_local_filters(filt_array[cur_depth]);
994 filt_array[cur_depth] = NULL;
995 }
996 }
997
998 cur_depth = dir_depth;
999 filt_array[cur_depth] = push_local_filters(dname, dlen);
1000 }
1001
1002 static int rule_matches(const char *fname, filter_rule *ex, int name_flags)
1003 {
1004 int slash_handling, str_cnt = 0, anchored_match = 0;
1005 int ret_match = ex->rflags & FILTRULE_NEGATE ? 0 : 1;
1006 const char *p, *pattern = ex->pattern;
1007 const char *strings[16]; /* more than enough */
1008 const char *name = fname + (*fname == '/');
1009
1010 if (!*name || ex->elide == cur_elide_value)
1011 return 0;
1012
1013 if (!(name_flags & NAME_IS_XATTR) ^ !(ex->rflags & FILTRULE_XATTR))
1014 return 0;
1015
1016 if (!ex->u.slash_cnt && !(ex->rflags & FILTRULE_WILD2)) {
1017 /* If the pattern does not have any slashes AND it does
1018 * not have a "**" (which could match a slash), then we
1019 * just match the name portion of the path. */
1020 if ((p = strrchr(name,'/')) != NULL)
1021 name = p+1;
1022 } else if (ex->rflags & FILTRULE_ABS_PATH && *fname != '/'
1023 && curr_dir_len > module_dirlen + 1) {
1024 /* If we're matching against an absolute-path pattern,
1025 * we need to prepend our full path info. */
1026 strings[str_cnt++] = curr_dir + module_dirlen + 1;
1027 strings[str_cnt++] = "/";
1028 } else if (ex->rflags & FILTRULE_WILD2_PREFIX && *fname != '/') {
1029 /* Allow "**"+"/" to match at the start of the string. */
1030 strings[str_cnt++] = "/";
1031 }
1032 strings[str_cnt++] = name;
1033 if (name_flags & NAME_IS_DIR) {
1034 /* Allow a trailing "/"+"***" to match the directory. */
1035 if (ex->rflags & FILTRULE_WILD3_SUFFIX)
1036 strings[str_cnt++] = "/";
1037 } else if (ex->rflags & FILTRULE_DIRECTORY)
1038 return !ret_match;
1039 strings[str_cnt] = NULL;
1040
1041 if (*pattern == '/') {
1042 anchored_match = 1;
1043 pattern++;
1044 }
1045
1046 if (!anchored_match && ex->u.slash_cnt
1047 && !(ex->rflags & FILTRULE_WILD2)) {
1048 /* A non-anchored match with an infix slash and no "**"
1049 * needs to match the last slash_cnt+1 name elements. */
1050 slash_handling = ex->u.slash_cnt + 1;
1051 } else if (!anchored_match && !(ex->rflags & FILTRULE_WILD2_PREFIX)
1052 && ex->rflags & FILTRULE_WILD2) {
1053 /* A non-anchored match with an infix or trailing "**" (but not
1054 * a prefixed "**") needs to try matching after every slash. */
1055 slash_handling = -1;
1056 } else {
1057 /* The pattern matches only at the start of the path or name. */
1058 slash_handling = 0;
1059 }
1060
1061 if (ex->rflags & FILTRULE_WILD) {
1062 if (wildmatch_array(pattern, strings, slash_handling))
1063 return ret_match;
1064 } else if (str_cnt > 1) {
1065 if (litmatch_array(pattern, strings, slash_handling))
1066 return ret_match;
1067 } else if (anchored_match) {
1068 if (strcmp(name, pattern) == 0)
1069 return ret_match;
1070 } else {
1071 int l1 = strlen(name);
1072 int l2 = strlen(pattern);
1073 if (l2 <= l1 &&
1074 strcmp(name+(l1-l2),pattern) == 0 &&
1075 (l1==l2 || name[l1-(l2+1)] == '/')) {
1076 return ret_match;
1077 }
1078 }
1079
1080 return !ret_match;
1081 }
1082
1083 static void report_filter_result(enum logcode code, char const *name,
1084 filter_rule const *ent,
1085 int name_flags, const char *type)
1086 {
1087 int log_level = am_sender || am_generator ? 1 : 3;
1088
1089 /* If a trailing slash is present to match only directories,
1090 * then it is stripped out by add_rule(). So as a special
1091 * case we add it back in the log output. */
1092 if (DEBUG_GTE(FILTER, log_level)) {
1093 static char *actions[2][2]
1094 = { {"show", "hid"}, {"risk", "protect"} };
1095 const char *w = who_am_i();
1096 const char *t = name_flags & NAME_IS_XATTR ? "xattr"
1097 : name_flags & NAME_IS_DIR ? "directory"
1098 : "file";
1099 rprintf(code, "[%s] %sing %s %s because of pattern %s%s%s\n",
1100 w, actions[*w=='g'][!(ent->rflags & FILTRULE_INCLUDE)],
1101 t, name, rule_text(ent, ent->pattern),
1102 rule_detail(ent, ent->rflags & FILTRULE_DIRECTORY ? "/" : ""), type);
1103 }
1104 }
1105
1106 /* This function is used to check if a file should be included/excluded
1107 * from the list of files based on its name and type etc. The value of
1108 * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
1109 int name_is_excluded(const char *fname, int name_flags, int filter_level)
1110 {
1111 if (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, name_flags) < 0) {
1112 if (!(name_flags & NAME_IS_XATTR))
1113 errno = ENOENT;
1114 return 1;
1115 }
1116
1117 if (filter_level != ALL_FILTERS)
1118 return 0;
1119
1120 if (filter_list.head && check_filter(&filter_list, FINFO, fname, name_flags) < 0)
1121 return 1;
1122
1123 return 0;
1124 }
1125
1126 int check_server_filter(filter_rule_list *listp, enum logcode code, const char *name, int name_flags)
1127 {
1128 int ret;
1129 cur_elide_value = LOCAL_RULE;
1130 ret = check_filter(listp, code, name, name_flags);
1131 cur_elide_value = REMOTE_RULE;
1132 return ret;
1133 }
1134
1135 /* Returns 1 if `name` matches an implied-parent rule (a directory component
1136 * seeded by add_implied_include() with FILTRULE_DIRECTORY) but not a leaf
1137 * rule -- i.e. the client asked for something under the dir, never the dir
1138 * itself as content.
1139 *
1140 * The receiver uses this to refuse a malicious sender that sets XMIT_TOP_DIR
1141 * without XMIT_NO_CONTENT_DIR on such a dir: the honest encoding is both flags
1142 * (flist.c send path), so otherwise the receiver would set FLAG_CONTENT_DIR
1143 * and delete_in_dir() could sweep pre-existing siblings under --delete. */
1144 int is_implied_parent_dir(const char *name)
1145 {
1146 filter_rule *ent;
1147 int parent_match = 0;
1148
1149 if (!implied_filter_list.head)
1150 return 0;
1151
1152 /* The receiver exempts its synthetic transfer-root entry from the
1153 * requested-name filter. Treat it as parent-only unless an empty/root
1154 * source argument added the root-content rule. */
1155 if ((name[0] == '.' && name[1] == '\0')
1156 || (name[0] == '/' && name[1] == '.' && name[2] == '\0')) {
1157 for (ent = implied_filter_list.head; ent; ent = ent->next) {
1158 if (!(ent->rflags & FILTRULE_INCLUDE))
1159 continue;
1160 if (strcmp(ent->pattern, "/**") == 0
1161 || strcmp(ent->pattern, "/*") == 0)
1162 return 0;
1163 }
1164 return 1;
1165 }
1166
1167 for (ent = implied_filter_list.head; ent; ent = ent->next) {
1168 if (ent->rflags & (FILTRULE_PERDIR_MERGE | FILTRULE_CVS_IGNORE))
1169 continue;
1170 if (!rule_matches(name, ent, NAME_IS_DIR))
1171 continue;
1172 if (!(ent->rflags & FILTRULE_INCLUDE))
1173 continue;
1174 if (ent->rflags & FILTRULE_DIRECTORY) {
1175 parent_match = 1;
1176 continue;
1177 }
1178 /* A non-DIRECTORY include rule = a leaf the client asked for, so
1179 * the dir is legitimately in the list, not parent-only. */
1180 return 0;
1181 }
1182 return parent_match;
1183 }
1184
1185 /* Return -1 if file "name" is defined to be excluded by the specified
1186 * exclude list, 1 if it is included, and 0 if it was not matched. */
1187 int check_filter(filter_rule_list *listp, enum logcode code,
1188 const char *name, int name_flags)
1189 {
1190 filter_rule *ent;
1191
1192 for (ent = listp->head; ent; ent = ent->next) {
1193 if (ignore_perishable && ent->rflags & FILTRULE_PERISHABLE)
1194 continue;
1195 if (ent->rflags & FILTRULE_PERDIR_MERGE) {
1196 int rc = check_filter(ent->u.mergelist, code, name, name_flags);
1197 if (rc)
1198 return rc;
1199 continue;
1200 }
1201 if (ent->rflags & FILTRULE_CVS_IGNORE) {
1202 int rc = check_filter(&cvs_filter_list, code, name, name_flags);
1203 if (rc)
1204 return rc;
1205 continue;
1206 }
1207 if (rule_matches(name, ent, name_flags)) {
1208 report_filter_result(code, name, ent, name_flags, listp->debug_type);
1209 return ent->rflags & FILTRULE_INCLUDE ? 1 : -1;
1210 }
1211 }
1212
1213 return 0;
1214 }
1215
1216 #define RULE_STRCMP(s,r) rule_strcmp((s), (r), sizeof (r) - 1)
1217
1218 static const uchar *rule_strcmp(const uchar *str, const char *rule, int rule_len)
1219 {
1220 if (strncmp((char*)str, rule, rule_len) != 0)
1221 return NULL;
1222 if (isspace(str[rule_len]) || str[rule_len] == '_' || !str[rule_len])
1223 return str + rule_len - 1;
1224 if (str[rule_len] == ',')
1225 return str + rule_len;
1226 return NULL;
1227 }
1228
1229 #define FILTRULES_FROM_CONTAINER (FILTRULE_ABS_PATH | FILTRULE_INCLUDE \
1230 | FILTRULE_DIRECTORY | FILTRULE_NEGATE \
1231 | FILTRULE_PERISHABLE)
1232
1233 /* Gets the next include/exclude rule from *rulestr_ptr and advances
1234 * *rulestr_ptr to point beyond it. Stores the pattern's start (within
1235 * *rulestr_ptr) and length in *pat_ptr and *pat_len_ptr, and returns a newly
1236 * allocated filter_rule containing the rest of the information. Returns
1237 * NULL if there are no more rules in the input.
1238 *
1239 * The template provides defaults for the new rule to inherit, and the
1240 * template rflags and the xflags additionally affect parsing. */
1241 static filter_rule *parse_rule_tok(const char **rulestr_ptr,
1242 const filter_rule *template, int xflags,
1243 const char **pat_ptr, unsigned int *pat_len_ptr)
1244 {
1245 const uchar *s = (const uchar *)*rulestr_ptr;
1246 filter_rule *rule;
1247 unsigned int len;
1248
1249 if (template->rflags & FILTRULE_WORD_SPLIT) {
1250 /* Skip over any initial whitespace. */
1251 while (isspace(*s))
1252 s++;
1253 /* Update to point to real start of rule. */
1254 *rulestr_ptr = (const char *)s;
1255 }
1256 if (!*s)
1257 return NULL;
1258
1259 rule = new0(filter_rule);
1260
1261 /* Inherit from the template. Don't inherit FILTRULES_SIDES; we check
1262 * that later. */
1263 rule->rflags = template->rflags & FILTRULES_FROM_CONTAINER;
1264 if (rule_src_in_file)
1265 rule->rflags |= FILTRULE_FROM_FILE; /* before parse_merge_name() */
1266
1267 /* Figure out what kind of a filter rule "s" is pointing at. Note
1268 * that if FILTRULE_NO_PREFIXES is set, the rule is either an include
1269 * or an exclude based on the inheritance of the FILTRULE_INCLUDE
1270 * flag (above). XFLG_OLD_PREFIXES indicates a compatibility mode
1271 * for old include/exclude patterns where just "+ " and "- " are
1272 * allowed as optional prefixes. */
1273 if (template->rflags & FILTRULE_NO_PREFIXES) {
1274 if (*s == '!' && template->rflags & FILTRULE_CVS_IGNORE)
1275 rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
1276 } else if (xflags & XFLG_OLD_PREFIXES) {
1277 if (*s == '-' && s[1] == ' ') {
1278 rule->rflags &= ~FILTRULE_INCLUDE;
1279 s += 2;
1280 } else if (*s == '+' && s[1] == ' ') {
1281 rule->rflags |= FILTRULE_INCLUDE;
1282 s += 2;
1283 } else if (*s == '!')
1284 rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
1285 } else {
1286 char ch = 0;
1287 BOOL prefix_specifies_side = False;
1288 switch (*s) {
1289 case 'c':
1290 if ((s = RULE_STRCMP(s, "clear")) != NULL)
1291 ch = '!';
1292 break;
1293 case 'd':
1294 if ((s = RULE_STRCMP(s, "dir-merge")) != NULL)
1295 ch = ':';
1296 break;
1297 case 'e':
1298 if ((s = RULE_STRCMP(s, "exclude")) != NULL)
1299 ch = '-';
1300 break;
1301 case 'h':
1302 if ((s = RULE_STRCMP(s, "hide")) != NULL)
1303 ch = 'H';
1304 break;
1305 case 'i':
1306 if ((s = RULE_STRCMP(s, "include")) != NULL)
1307 ch = '+';
1308 break;
1309 case 'm':
1310 if ((s = RULE_STRCMP(s, "merge")) != NULL)
1311 ch = '.';
1312 break;
1313 case 'p':
1314 if ((s = RULE_STRCMP(s, "protect")) != NULL)
1315 ch = 'P';
1316 break;
1317 case 'r':
1318 if ((s = RULE_STRCMP(s, "risk")) != NULL)
1319 ch = 'R';
1320 break;
1321 case 's':
1322 if ((s = RULE_STRCMP(s, "show")) != NULL)
1323 ch = 'S';
1324 break;
1325 default:
1326 ch = *s;
1327 if (s[1] == ',')
1328 s++;
1329 break;
1330 }
1331 switch (ch) {
1332 case ':':
1333 trust_sender_filter = 1;
1334 rule->rflags |= FILTRULE_PERDIR_MERGE
1335 | FILTRULE_FINISH_SETUP;
1336 /* FALL THROUGH */
1337 case '.':
1338 rule->rflags |= FILTRULE_MERGE_FILE;
1339 break;
1340 case '+':
1341 rule->rflags |= FILTRULE_INCLUDE;
1342 break;
1343 case '-':
1344 break;
1345 case 'S':
1346 rule->rflags |= FILTRULE_INCLUDE;
1347 /* FALL THROUGH */
1348 case 'H':
1349 rule->rflags |= FILTRULE_SENDER_SIDE;
1350 prefix_specifies_side = True;
1351 break;
1352 case 'R':
1353 rule->rflags |= FILTRULE_INCLUDE;
1354 /* FALL THROUGH */
1355 case 'P':
1356 rule->rflags |= FILTRULE_RECEIVER_SIDE;
1357 prefix_specifies_side = True;
1358 break;
1359 case '!':
1360 rule->rflags |= FILTRULE_CLEAR_LIST;
1361 break;
1362 default:
1363 filter_rule_err("Unknown filter rule", *rulestr_ptr);
1364 }
1365 while (ch != '!' && *++s && *s != ' ' && *s != '_') {
1366 if (template->rflags & FILTRULE_WORD_SPLIT && isspace(*s)) {
1367 s--;
1368 break;
1369 }
1370 switch (*s) {
1371 default:
1372 invalid: {
1373 char where[32];
1374 snprintf(where, sizeof where, " '%c' at position %d",
1375 *s, (int)(s - (const uchar *)*rulestr_ptr));
1376 rprintf(FERROR, "invalid modifier%s in filter rule: %s\n",
1377 rule_detail(NULL, where),
1378 rule_text(NULL, *rulestr_ptr));
1379 exit_cleanup(RERR_SYNTAX);
1380 }
1381 case '-':
1382 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
1383 goto invalid;
1384 rule->rflags |= FILTRULE_NO_PREFIXES;
1385 break;
1386 case '+':
1387 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
1388 goto invalid;
1389 rule->rflags |= FILTRULE_NO_PREFIXES
1390 | FILTRULE_INCLUDE;
1391 break;
1392 case '/':
1393 rule->rflags |= FILTRULE_ABS_PATH;
1394 break;
1395 case '!':
1396 /* Negation really goes with the pattern, so it
1397 * isn't useful as a merge-file default. */
1398 if (rule->rflags & FILTRULE_MERGE_FILE)
1399 goto invalid;
1400 rule->rflags |= FILTRULE_NEGATE;
1401 break;
1402 case 'C':
1403 if (rule->rflags & FILTRULE_NO_PREFIXES || prefix_specifies_side)
1404 goto invalid;
1405 rule->rflags |= FILTRULE_NO_PREFIXES
1406 | FILTRULE_WORD_SPLIT
1407 | FILTRULE_NO_INHERIT
1408 | FILTRULE_CVS_IGNORE;
1409 break;
1410 case 'e':
1411 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1412 goto invalid;
1413 rule->rflags |= FILTRULE_EXCLUDE_SELF;
1414 break;
1415 case 'n':
1416 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1417 goto invalid;
1418 rule->rflags |= FILTRULE_NO_INHERIT;
1419 break;
1420 case 'p':
1421 rule->rflags |= FILTRULE_PERISHABLE;
1422 break;
1423 case 'r':
1424 if (prefix_specifies_side)
1425 goto invalid;
1426 rule->rflags |= FILTRULE_RECEIVER_SIDE;
1427 break;
1428 case 's':
1429 if (prefix_specifies_side)
1430 goto invalid;
1431 rule->rflags |= FILTRULE_SENDER_SIDE;
1432 break;
1433 case 'w':
1434 if (!(rule->rflags & FILTRULE_MERGE_FILE))
1435 goto invalid;
1436 rule->rflags |= FILTRULE_WORD_SPLIT;
1437 break;
1438 case 'x':
1439 rule->rflags |= FILTRULE_XATTR;
1440 saw_xattr_filter = 1;
1441 break;
1442 }
1443 }
1444 if (*s)
1445 s++;
1446 }
1447 if (template->rflags & FILTRULES_SIDES) {
1448 if (rule->rflags & FILTRULES_SIDES) {
1449 /* The filter and template both specify side(s). This
1450 * is dodgy (and won't work correctly if the template is
1451 * a one-sided per-dir merge rule), so reject it. */
1452 filter_rule_err("specified-side merge file contains specified-side filter",
1453 *rulestr_ptr);
1454 }
1455 rule->rflags |= template->rflags & FILTRULES_SIDES;
1456 }
1457
1458 if (template->rflags & FILTRULE_WORD_SPLIT) {
1459 const uchar *cp = s;
1460 /* Token ends at whitespace or the end of the string. */
1461 while (!isspace(*cp) && *cp != '\0')
1462 cp++;
1463 len = cp - s;
1464 } else
1465 len = strlen((char*)s);
1466
1467 if (rule->rflags & FILTRULE_CLEAR_LIST) {
1468 if (!(template->rflags & FILTRULE_NO_PREFIXES)
1469 && !(xflags & XFLG_OLD_PREFIXES) && len) {
1470 filter_rule_err("'!' rule has trailing characters", *rulestr_ptr);
1471 }
1472 if (len > 1)
1473 rule->rflags &= ~FILTRULE_CLEAR_LIST;
1474 } else if (!len && !(rule->rflags & FILTRULE_CVS_IGNORE)) {
1475 filter_rule_err("unexpected end of filter rule", *rulestr_ptr);
1476 }
1477
1478 /* --delete-excluded turns an un-modified include/exclude into a sender-side rule. */
1479 if (delete_excluded
1480 && !(rule->rflags & (FILTRULES_SIDES|FILTRULE_MERGE_FILE|FILTRULE_PERDIR_MERGE)))
1481 rule->rflags |= FILTRULE_SENDER_SIDE;
1482
1483 *pat_ptr = (const char *)s;
1484 *pat_len_ptr = len;
1485 *rulestr_ptr = *pat_ptr + len;
1486 return rule;
1487 }
1488
1489 static void get_cvs_excludes(uint32 rflags)
1490 {
1491 static int initialized = 0;
1492 char *p, fname[MAXPATHLEN];
1493
1494 if (initialized)
1495 return;
1496 initialized = 1;
1497
1498 parse_filter_str(&cvs_filter_list, default_cvsignore(),
1499 rule_template(rflags | (protocol_version >= 30 ? FILTRULE_PERISHABLE : 0)),
1500 0);
1501
1502 p = module_id >= 0 && lp_use_chroot(module_id) ? "/" : getenv("HOME");
1503 if (p && pathjoin(fname, MAXPATHLEN, p, ".cvsignore") < MAXPATHLEN)
1504 parse_filter_file(&cvs_filter_list, fname, rule_template(rflags), 0);
1505
1506 parse_filter_str(&cvs_filter_list, getenv("CVSIGNORE"), rule_template(rflags), 0);
1507 }
1508
1509 const filter_rule *rule_template(uint32 rflags)
1510 {
1511 static filter_rule template; /* zero-initialized */
1512 template.rflags = rflags;
1513 return &template;
1514 }
1515
1516 void parse_filter_str(filter_rule_list *listp, const char *rulestr,
1517 const filter_rule *template, int xflags)
1518 {
1519 filter_rule *rule;
1520 const char *pat;
1521 unsigned int pat_len;
1522
1523 if (!rulestr)
1524 return;
1525
1526 while (1) {
1527 uint32 new_rflags;
1528
1529 /* Remember that the returned string is NOT '\0' terminated! */
1530 if (!(rule = parse_rule_tok(&rulestr, template, xflags, &pat, &pat_len)))
1531 break;
1532
1533 if (pat_len >= MAXPATHLEN) {
1534 rprintf(FERROR, "discarding over-long filter: %s\n",
1535 rule_text_len(NULL, pat, (int)pat_len));
1536 free_continue:
1537 free_filter(rule);
1538 continue;
1539 }
1540
1541 new_rflags = rule->rflags;
1542 if (new_rflags & FILTRULE_CLEAR_LIST) {
1543 if (DEBUG_GTE(FILTER, 2)) {
1544 rprintf(FINFO,
1545 "[%s] clearing filter list%s\n",
1546 who_am_i(), listp->debug_type);
1547 }
1548 pop_filter_list(listp);
1549 listp->head = NULL;
1550 goto free_continue;
1551 }
1552
1553 if (new_rflags & FILTRULE_MERGE_FILE) {
1554 if (!pat_len) {
1555 pat = ".cvsignore";
1556 pat_len = 10;
1557 }
1558 if (new_rflags & FILTRULE_EXCLUDE_SELF) {
1559 const char *name;
1560 filter_rule *excl_self;
1561
1562 excl_self = new0(filter_rule);
1563 /* The pattern below is the merge rule's own text, so it
1564 * inherits that rule's provenance. Built by hand, this
1565 * rule looked argument-origin once parsing finished and
1566 * the match trace echoed a merge file's contents at -vv. */
1567 excl_self->rflags = rule->rflags & FILTRULE_FROM_FILE;
1568 /* Find the beginning of the basename and add an exclude for it. */
1569 for (name = pat + pat_len; name > pat && name[-1] != '/'; name--) {}
1570 add_rule(listp, name, (pat + pat_len) - name, excl_self, 0);
1571 rule->rflags &= ~FILTRULE_EXCLUDE_SELF;
1572 }
1573 if (new_rflags & FILTRULE_PERDIR_MERGE) {
1574 if (parent_dirscan) {
1575 const char *p;
1576 unsigned int len = pat_len;
1577 if ((p = parse_merge_name(rule, pat, &len, module_dirlen)))
1578 add_rule(listp, p, len, rule, 0);
1579 else
1580 free_filter(rule);
1581 continue;
1582 }
1583 } else {
1584 const char *p;
1585 unsigned int len = pat_len;
1586 if ((p = parse_merge_name(rule, pat, &len, 0)))
1587 parse_filter_file(listp, p, rule, XFLG_FATAL_ERRORS);
1588 free_filter(rule);
1589 continue;
1590 }
1591 }
1592
1593 add_rule(listp, pat, pat_len, rule, xflags);
1594
1595 if (new_rflags & FILTRULE_CVS_IGNORE
1596 && !(new_rflags & FILTRULE_MERGE_FILE))
1597 get_cvs_excludes(new_rflags);
1598 }
1599 }
1600
1601 void parse_filter_file(filter_rule_list *listp, const char *fname, const filter_rule *template, int xflags)
1602 {
1603 FILE *fp;
1604 char line[BIGPATHBUFLEN];
1605 char *eob = line + sizeof line - 1;
1606 BOOL word_split = (template->rflags & FILTRULE_WORD_SPLIT) != 0;
1607 const char *save_src_file, *save_src_named_at;
1608 int save_src_line, save_src_in_file;
1609 int named_by_file;
1610 int pending = EOF;
1611 char named_at[MAXPATHLEN + 32];
1612 /* Our own copy: fname may point into parse_merge_name()'s static buffer,
1613 * which a merge rule inside THIS file overwrites while we still need it. */
1614 char src_name[MAXPATHLEN];
1615
1616 if (!fname || !*fname)
1617 return;
1618
1619 if (merge_depth >= MAX_MERGE_DEPTH) {
1620 rprintf(FERROR,
1621 "[%s] merge-file include depth limit (%d) exceeded at %s\n",
1622 who_am_i(), MAX_MERGE_DEPTH, rule_text(template, fname));
1623 /* Match the failed-open path below: abort under a fatal
1624 * (operator-supplied) merge, otherwise drop the rule. */
1625 if (xflags & XFLG_FATAL_ERRORS)
1626 exit_cleanup(RERR_FILEIO);
1627 return;
1628 }
1629 merge_depth++;
1630
1631 if (*fname != '-' || fname[1] || am_server) {
1632 /* This path is operator- and (via per-directory merge files like
1633 * .cvsignore) sender-controlled: a planted symlink could leak a
1634 * root-readable file through the filter parser, or redirect an
1635 * --exclude-from open via a planted parent. Refuse symlinks not
1636 * owned by uid 0 or our euid. */
1637 const char *open_path;
1638 int fd;
1639 if (daemon_filter_list.head) {
1640 char *dir;
1641 strlcpy(line, fname, sizeof line);
1642 /* parse_merge_name() prepends module_dir for absolute paths,
1643 * so strip module_dirlen back off before the check or the
1644 * anchored module-relative daemon rule won't match (as
1645 * options.c does for --exclude-from/--include-from). The
1646 * original absolute path is still used for the open below. */
1647 dir = line + (*line == '/' ? module_dirlen : 0);
1648 clean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);
1649 if (check_filter(&daemon_filter_list, FLOG, dir, 0) < 0) {
1650 /* Hidden by the daemon filter: treat the merge file as
1651 * non-existent rather than tripping XFLG_FATAL_ERRORS
1652 * below, so it neither errors out nor leaks a
1653 * fatal-vs-silent oracle. */
1654 if (DEBUG_GTE(FILTER, 2)) {
1655 /* Same rule as everywhere else: the name is
1656 * file content when a rule we read named it,
1657 * and so is "the daemon filter hides it". */
1658 rprintf(FINFO, "[%s] parse_filter_file(%s)%s\n",
1659 who_am_i(), rule_text(template, fname),
1660 rule_detail(template, " hidden by daemon filter"));
1661 }
1662 merge_depth--;
1663 return;
1664 }
1665 open_path = line;
1666 } else
1667 open_path = fname;
1668
1669 /* Confine the open to the module root. The ownership walk on its own
1670 * is not enough for a peer-driven merge file: a non-chrooted daemon
1671 * writes --backup-dir entries as root, so a raced backup symlink is
1672 * ROOT-owned -- exactly what open_no_attacker_symlinks() treats as
1673 * trusted -- and naming it in a dir-merge rule would read an
1674 * out-of-module file in as filter rules (their text comes back to the
1675 * peer in "Unknown filter rule" errors).
1676 *
1677 * The daemon's own "filter"/"include from"/"exclude from" parameters
1678 * are exempt: those are operator-configured and legitimately live
1679 * outside the module (/etc/rsync/excludes and the like). */
1680 int save_opr = operator_path_resolve;
1681 if (!daemon_config_filter_file)
1682 operator_path_resolve = 1;
1683 fd = open_no_attacker_symlinks(open_path, O_RDONLY, 0);
1684 operator_path_resolve = save_opr;
1685
1686 if (fd < 0)
1687 fp = NULL;
1688 else if (!(fp = fdopen(fd, "rb")))
1689 close(fd);
1690 } else
1691 fp = stdin;
1692
1693 if (DEBUG_GTE(FILTER, 2)) {
1694 /* The name is file CONTENT when a rule we read named it, and a
1695 * word-split per-dir merge turns every word of a file into one
1696 * of these -- so the trace would echo what the syntax errors no
1697 * longer do. Say where it came from instead. */
1698 rprintf(FINFO, "[%s] parse_filter_file(%s,%x,%x)%s\n",
1699 who_am_i(), rule_text(template, fname), template->rflags, xflags,
1700 rule_detail(template, fp ? "" : " [not found]"));
1701 }
1702
1703 if (!fp) {
1704 if (xflags & XFLG_FATAL_ERRORS) {
1705 /* rule_src_file is still the PARENT's context here: when it
1706 * is set, this name came out of a file we read, so neither
1707 * the name nor errno (an existence oracle) may be shown. */
1708 if (TEXT_FROM_FILE(template)) {
1709 /* errno too: it answers "does this path exist". */
1710 rprintf(FERROR, "failed to open %sclude file %s\n",
1711 template->rflags & FILTRULE_INCLUDE ? "in" : "ex",
1712 rule_text(template, fname));
1713 } else {
1714 rsyserr(FERROR, errno,
1715 "failed to open %sclude file %s",
1716 template->rflags & FILTRULE_INCLUDE ? "in" : "ex",
1717 fname);
1718 }
1719 exit_cleanup(RERR_FILEIO);
1720 }
1721 merge_depth--;
1722 return;
1723 }
1724 /* Before dirbuf is cut back: a per-directory fname points INTO dirbuf,
1725 * so truncating first leaves only the directory and the location we
1726 * report loses the filename. */
1727 strlcpy(src_name, fname, sizeof src_name);
1728 dirbuf[dirbuf_len] = '\0';
1729
1730 /* Rule text from here on is this file's contents, not an argument, so
1731 * a syntax error must not echo it. Saved and restored because a merge
1732 * rule inside this file can bring us back in for another file. */
1733 save_src_in_file = rule_src_in_file;
1734 save_src_file = rule_src_file;
1735 save_src_line = rule_src_line;
1736 /* If a rule we read named THIS file, our own path is file content too:
1737 * track the location for provenance but do not put it in a message. */
1738 named_by_file = TEXT_FROM_FILE(template);
1739 save_src_named_at = rule_src_named_at;
1740 if (named_by_file) {
1741 /* Snapshot where we were told to merge this, before that state
1742 * is replaced below (rule_src_where returns a static buffer).
1743 * A DEFERRED merge has no live location to point at -- the file
1744 * that named it was read and finished long ago -- so leave the
1745 * generic description rather than nesting two vague ones. */
1746 if (rule_src_in_file) {
1747 strlcpy(named_at, rule_src_where(), sizeof named_at);
1748 rule_src_named_at = named_at;
1749 } else
1750 rule_src_named_at = NULL;
1751 }
1752 rule_src_in_file = 1;
1753 rule_src_file = named_by_file ? NULL : src_name;
1754 rule_src_line = word_split ? -1 : 0; /* -1: tokens, not lines */
1755
1756 while (1) {
1757 char *s = line;
1758 int ch, overflow = 0;
1759 if (rule_src_line >= 0)
1760 rule_src_line++;
1761 while (1) {
1762 if (pending != EOF) { /* a CR lookahead we could not push back */
1763 ch = pending;
1764 pending = EOF;
1765 } else if ((ch = getc(fp)) == EOF) {
1766 if (ferror(fp) && errno == EINTR) {
1767 clearerr(fp);
1768 continue;
1769 }
1770 break;
1771 }
1772 if (word_split && isspace(ch))
1773 break;
1774 if (eol_nulls? !ch : (ch == '\n' || ch == '\r')) {
1775 if (ch == '\r') { /* CRLF is one line, not two */
1776 int nxt;
1777 while ((nxt = getc(fp)) == EOF
1778 && ferror(fp) && errno == EINTR)
1779 clearerr(fp);
1780 if (nxt == EOF) {
1781 if (!ferror(fp))
1782 ch = EOF; /* real end of file */
1783 } else if (nxt != '\n' && ungetc(nxt, fp) == EOF) {
1784 /* Pushback failed: hand it to the
1785 * NEXT rule, where it belongs --
1786 * appending it here would both
1787 * corrupt this rule and skip the
1788 * s < eob bound below. */
1789 pending = nxt;
1790 }
1791 }
1792 break;
1793 }
1794 if (s < eob)
1795 *s++ = ch;
1796 else
1797 overflow = 1;
1798 }
1799 if (overflow) {
1800 rprintf(FERROR, "discarding over-long filter: %s\n",
1801 rule_text_len(NULL, line, 0));
1802 s = line;
1803 }
1804 *s = '\0';
1805 /* Skip an empty token and (when line parsing) comments. */
1806 if (*line && (word_split || (*line != ';' && *line != '#'))) {
1807 rule_src_file = named_by_file ? NULL : src_name;
1808 parse_filter_str(listp, line, template, xflags);
1809 }
1810 if (ch == EOF)
1811 break;
1812 }
1813 rule_src_in_file = save_src_in_file;
1814 rule_src_file = save_src_file;
1815 rule_src_line = save_src_line;
1816 rule_src_named_at = save_src_named_at;
1817 fclose(fp);
1818 merge_depth--;
1819 }
1820
1821 /* If the "for_xfer" flag is set, the prefix is made compatible with the
1822 * current protocol_version (if possible) or a NULL is returned (if not
1823 * possible). */
1824 char *get_rule_prefix(filter_rule *rule, const char *pat, int for_xfer,
1825 unsigned int *plen_ptr)
1826 {
1827 static char buf[MAX_RULE_PREFIX+1];
1828 char *op = buf;
1829 int legal_len = for_xfer && protocol_version < 29 ? 1 : MAX_RULE_PREFIX-1;
1830
1831 if (rule->rflags & FILTRULE_PERDIR_MERGE) {
1832 if (legal_len == 1)
1833 return NULL;
1834 *op++ = ':';
1835 } else if (rule->rflags & FILTRULE_INCLUDE)
1836 *op++ = '+';
1837 else if (legal_len != 1
1838 || ((*pat == '-' || *pat == '+') && pat[1] == ' '))
1839 *op++ = '-';
1840 else
1841 legal_len = 0;
1842
1843 if (rule->rflags & FILTRULE_ABS_PATH)
1844 *op++ = '/';
1845 if (rule->rflags & FILTRULE_NEGATE)
1846 *op++ = '!';
1847 if (rule->rflags & FILTRULE_CVS_IGNORE)
1848 *op++ = 'C';
1849 else {
1850 if (rule->rflags & FILTRULE_NO_INHERIT)
1851 *op++ = 'n';
1852 if (rule->rflags & FILTRULE_WORD_SPLIT)
1853 *op++ = 'w';
1854 if (rule->rflags & FILTRULE_NO_PREFIXES) {
1855 if (rule->rflags & FILTRULE_INCLUDE)
1856 *op++ = '+';
1857 else
1858 *op++ = '-';
1859 }
1860 }
1861 if (rule->rflags & FILTRULE_EXCLUDE_SELF)
1862 *op++ = 'e';
1863 if (rule->rflags & FILTRULE_XATTR)
1864 *op++ = 'x';
1865 if (rule->rflags & FILTRULE_SENDER_SIDE
1866 && (!for_xfer || protocol_version >= 29))
1867 *op++ = 's';
1868 if (rule->rflags & FILTRULE_RECEIVER_SIDE
1869 && (!for_xfer || protocol_version >= 29
1870 || (delete_excluded && am_sender)))
1871 *op++ = 'r';
1872 if (rule->rflags & FILTRULE_PERISHABLE) {
1873 if (!for_xfer || protocol_version >= 30)
1874 *op++ = 'p';
1875 else if (am_sender)
1876 return NULL;
1877 }
1878 if (op - buf > legal_len)
1879 return NULL;
1880 if (legal_len)
1881 *op++ = ' ';
1882 *op = '\0';
1883 if (plen_ptr)
1884 *plen_ptr = op - buf;
1885 return buf;
1886 }
1887
1888 static void send_rules(int f_out, filter_rule_list *flp)
1889 {
1890 filter_rule *ent;
1891
1892 for (ent = flp->head; ent; ent = ent->next) {
1893 unsigned int len, plen, dlen;
1894 int elide = 0;
1895 char *p;
1896
1897 /* Note we need to check delete_excluded here in addition to
1898 * the code in parse_rule_tok() because some rules may have
1899 * been added before we found the --delete-excluded option.
1900 * We must also elide any CVS merge-file rules to avoid a
1901 * backward compatibility problem, and we elide any no-prefix
1902 * merge files as an optimization (since they can only have
1903 * include/exclude rules). */
1904 if (ent->rflags & FILTRULE_SENDER_SIDE)
1905 elide = am_sender ? LOCAL_RULE : REMOTE_RULE;
1906 if (ent->rflags & FILTRULE_RECEIVER_SIDE)
1907 elide = elide ? 0 : am_sender ? REMOTE_RULE : LOCAL_RULE;
1908 else if (delete_excluded && !elide
1909 && (!(ent->rflags & FILTRULE_PERDIR_MERGE)
1910 || ent->rflags & FILTRULE_NO_PREFIXES))
1911 elide = am_sender ? LOCAL_RULE : REMOTE_RULE;
1912 ent->elide = elide;
1913 if (elide == LOCAL_RULE)
1914 continue;
1915 if (ent->rflags & FILTRULE_CVS_IGNORE
1916 && !(ent->rflags & FILTRULE_MERGE_FILE)) {
1917 int f = am_sender || protocol_version < 29 ? f_out : -2;
1918 send_rules(f, &cvs_filter_list);
1919 if (f == f_out)
1920 continue;
1921 }
1922 p = get_rule_prefix(ent, ent->pattern, 1, &plen);
1923 if (!p) {
1924 rprintf(FERROR,
1925 "filter rules are too modern for remote rsync.\n");
1926 exit_cleanup(RERR_PROTOCOL);
1927 }
1928 if (f_out < 0)
1929 continue;
1930 len = strlen(ent->pattern);
1931 dlen = ent->rflags & FILTRULE_DIRECTORY ? 1 : 0;
1932 if (!(plen + len + dlen))
1933 continue;
1934 write_int(f_out, plen + len + dlen);
1935 if (plen)
1936 write_buf(f_out, p, plen);
1937 write_buf(f_out, ent->pattern, len);
1938 if (dlen)
1939 write_byte(f_out, '/');
1940 }
1941 }
1942
1943 /* This is only called by the client. */
1944 void send_filter_list(int f_out)
1945 {
1946 int receiver_wants_list = prune_empty_dirs
1947 || (delete_mode && (!delete_excluded || protocol_version >= 29));
1948
1949 if (local_server || (am_sender && !receiver_wants_list))
1950 f_out = -1;
1951 if (cvs_exclude && am_sender) {
1952 if (protocol_version >= 29)
1953 parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1954 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1955 }
1956
1957 send_rules(f_out, &filter_list);
1958
1959 if (f_out >= 0)
1960 write_int(f_out, 0);
1961
1962 if (cvs_exclude) {
1963 if (!am_sender || protocol_version < 29)
1964 parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1965 if (!am_sender)
1966 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1967 }
1968 }
1969
1970 /* This is only called by the server. */
1971 void recv_filter_list(int f_in)
1972 {
1973 char line[BIGPATHBUFLEN];
1974 int xflags = protocol_version >= 29 ? 0 : XFLG_OLD_PREFIXES;
1975 int receiver_wants_list = prune_empty_dirs
1976 || (delete_mode && (!delete_excluded || protocol_version >= 29));
1977 unsigned int len;
1978
1979 if (!local_server && (am_sender || receiver_wants_list)) {
1980 while ((len = read_int(f_in)) != 0) {
1981 if (len >= sizeof line)
1982 overflow_exit("recv_rules");
1983 read_sbuf(f_in, line, len);
1984 parse_filter_str(&filter_list, line, rule_template(0), xflags);
1985 }
1986 }
1987
1988 if (cvs_exclude) {
1989 if (local_server || am_sender || protocol_version < 29)
1990 parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1991 if (local_server || am_sender)
1992 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1993 }
1994
1995 if (local_server) /* filter out any rules that aren't for us. */
1996 send_rules(-1, &filter_list);
1997 }