Setup a macOS CI.
[rsync.git] / exclude.c
1 /*
2  * The filter include/exclude routines.
3  *
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-2020 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 "default-cvsignore.h"
25 #include "ifuncs.h"
26
27 extern int am_server;
28 extern int am_sender;
29 extern int eol_nulls;
30 extern int io_error;
31 extern int local_server;
32 extern int prune_empty_dirs;
33 extern int ignore_perishable;
34 extern int delete_mode;
35 extern int delete_excluded;
36 extern int cvs_exclude;
37 extern int sanitize_paths;
38 extern int protocol_version;
39 extern int module_id;
40
41 extern char curr_dir[MAXPATHLEN];
42 extern unsigned int curr_dir_len;
43 extern unsigned int module_dirlen;
44
45 filter_rule_list filter_list = { .debug_type = "" };
46 filter_rule_list cvs_filter_list = { .debug_type = " [global CVS]" };
47 filter_rule_list daemon_filter_list = { .debug_type = " [daemon]" };
48
49 int saw_xattr_filter = 0;
50
51 /* Need room enough for ":MODS " prefix plus some room to grow. */
52 #define MAX_RULE_PREFIX (16)
53
54 #define SLASH_WILD3_SUFFIX "/***"
55
56 /* The dirbuf is set by push_local_filters() to the current subdirectory
57  * relative to curr_dir that is being processed.  The path always has a
58  * trailing slash appended, and the variable dirbuf_len contains the length
59  * of this path prefix.  The path is always absolute. */
60 static char dirbuf[MAXPATHLEN+1];
61 static unsigned int dirbuf_len = 0;
62 static int dirbuf_depth;
63
64 /* This is True when we're scanning parent dirs for per-dir merge-files. */
65 static BOOL parent_dirscan = False;
66
67 /* This array contains a list of all the currently active per-dir merge
68  * files.  This makes it easier to save the appropriate values when we
69  * "push" down into each subdirectory. */
70 static filter_rule **mergelist_parents;
71 static int mergelist_cnt = 0;
72 static int mergelist_size = 0;
73
74 /* Each filter_list_struct describes a singly-linked list by keeping track
75  * of both the head and tail pointers.  The list is slightly unusual in that
76  * a parent-dir's content can be appended to the end of the local list in a
77  * special way:  the last item in the local list has its "next" pointer set
78  * to point to the inherited list, but the local list's tail pointer points
79  * at the end of the local list.  Thus, if the local list is empty, the head
80  * will be pointing at the inherited content but the tail will be NULL.  To
81  * help you visualize this, here are the possible list arrangements:
82  *
83  * Completely Empty                     Local Content Only
84  * ==================================   ====================================
85  * head -> NULL                         head -> Local1 -> Local2 -> NULL
86  * tail -> NULL                         tail -------------^
87  *
88  * Inherited Content Only               Both Local and Inherited Content
89  * ==================================   ====================================
90  * head -> Parent1 -> Parent2 -> NULL   head -> L1 -> L2 -> P1 -> P2 -> NULL
91  * tail -> NULL                         tail ---------^
92  *
93  * This means that anyone wanting to traverse the whole list to use it just
94  * needs to start at the head and use the "next" pointers until it goes
95  * NULL.  To add new local content, we insert the item after the tail item
96  * and update the tail (obviously, if "tail" was NULL, we insert it at the
97  * head).  To clear the local list, WE MUST NOT FREE THE INHERITED CONTENT
98  * because it is shared between the current list and our parent list(s).
99  * The easiest way to handle this is to simply truncate the list after the
100  * tail item and then free the local list from the head.  When inheriting
101  * the list for a new local dir, we just save off the filter_list_struct
102  * values (so we can pop back to them later) and set the tail to NULL.
103  */
104
105 static void teardown_mergelist(filter_rule *ex)
106 {
107         int j;
108
109         if (!ex->u.mergelist)
110                 return;
111
112         if (DEBUG_GTE(FILTER, 2)) {
113                 rprintf(FINFO, "[%s] deactivating mergelist #%d%s\n",
114                         who_am_i(), mergelist_cnt - 1,
115                         ex->u.mergelist->debug_type);
116         }
117
118         free(ex->u.mergelist->debug_type);
119         free(ex->u.mergelist);
120
121         for (j = 0; j < mergelist_cnt; j++) {
122                 if (mergelist_parents[j] == ex) {
123                         mergelist_parents[j] = NULL;
124                         break;
125                 }
126         }
127         while (mergelist_cnt && mergelist_parents[mergelist_cnt-1] == NULL)
128                 mergelist_cnt--;
129 }
130
131 static void free_filter(filter_rule *ex)
132 {
133         if (ex->rflags & FILTRULE_PERDIR_MERGE)
134                 teardown_mergelist(ex);
135         free(ex->pattern);
136         free(ex);
137 }
138
139 static void free_filters(filter_rule *ent)
140 {
141         while (ent) {
142                 filter_rule *next = ent->next;
143                 free_filter(ent);
144                 ent = next;
145         }
146 }
147
148 /* Build a filter structure given a filter pattern.  The value in "pat"
149  * is not null-terminated.  "rule" is either held or freed, so the
150  * caller should not free it. */
151 static void add_rule(filter_rule_list *listp, const char *pat, unsigned int pat_len,
152                      filter_rule *rule, int xflags)
153 {
154         const char *cp;
155         unsigned int pre_len, suf_len, slash_cnt = 0;
156
157         if (DEBUG_GTE(FILTER, 2)) {
158                 rprintf(FINFO, "[%s] add_rule(%s%.*s%s)%s\n",
159                         who_am_i(), get_rule_prefix(rule, pat, 0, NULL),
160                         (int)pat_len, pat,
161                         (rule->rflags & FILTRULE_DIRECTORY) ? "/" : "",
162                         listp->debug_type);
163         }
164
165         /* These flags also indicate that we're reading a list that
166          * needs to be filtered now, not post-filtered later. */
167         if (xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH)
168                 && (rule->rflags & FILTRULES_SIDES)
169                         == (am_sender ? FILTRULE_RECEIVER_SIDE : FILTRULE_SENDER_SIDE)) {
170                 /* This filter applies only to the other side.  Drop it. */
171                 free_filter(rule);
172                 return;
173         }
174
175         if (pat_len > 1 && pat[pat_len-1] == '/') {
176                 pat_len--;
177                 rule->rflags |= FILTRULE_DIRECTORY;
178         }
179
180         for (cp = pat; cp < pat + pat_len; cp++) {
181                 if (*cp == '/')
182                         slash_cnt++;
183         }
184
185         if (!(rule->rflags & (FILTRULE_ABS_PATH | FILTRULE_MERGE_FILE))
186          && ((xflags & (XFLG_ANCHORED2ABS|XFLG_ABS_IF_SLASH) && *pat == '/')
187           || (xflags & XFLG_ABS_IF_SLASH && slash_cnt))) {
188                 rule->rflags |= FILTRULE_ABS_PATH;
189                 if (*pat == '/')
190                         pre_len = dirbuf_len - module_dirlen - 1;
191                 else
192                         pre_len = 0;
193         } else
194                 pre_len = 0;
195
196         /* The daemon wants dir-exclude rules to get an appended "/" + "***". */
197         if (xflags & XFLG_DIR2WILD3
198          && BITS_SETnUNSET(rule->rflags, FILTRULE_DIRECTORY, FILTRULE_INCLUDE)) {
199                 rule->rflags &= ~FILTRULE_DIRECTORY;
200                 suf_len = sizeof SLASH_WILD3_SUFFIX - 1;
201         } else
202                 suf_len = 0;
203
204         rule->pattern = new_array(char, pre_len + pat_len + suf_len + 1);
205         if (pre_len) {
206                 memcpy(rule->pattern, dirbuf + module_dirlen, pre_len);
207                 for (cp = rule->pattern; cp < rule->pattern + pre_len; cp++) {
208                         if (*cp == '/')
209                                 slash_cnt++;
210                 }
211         }
212         strlcpy(rule->pattern + pre_len, pat, pat_len + 1);
213         pat_len += pre_len;
214         if (suf_len) {
215                 memcpy(rule->pattern + pat_len, SLASH_WILD3_SUFFIX, suf_len+1);
216                 pat_len += suf_len;
217                 slash_cnt++;
218         }
219
220         if (strpbrk(rule->pattern, "*[?")) {
221                 rule->rflags |= FILTRULE_WILD;
222                 if ((cp = strstr(rule->pattern, "**")) != NULL) {
223                         rule->rflags |= FILTRULE_WILD2;
224                         /* If the pattern starts with **, note that. */
225                         if (cp == rule->pattern)
226                                 rule->rflags |= FILTRULE_WILD2_PREFIX;
227                         /* If the pattern ends with ***, note that. */
228                         if (pat_len >= 3
229                          && rule->pattern[pat_len-3] == '*'
230                          && rule->pattern[pat_len-2] == '*'
231                          && rule->pattern[pat_len-1] == '*')
232                                 rule->rflags |= FILTRULE_WILD3_SUFFIX;
233                 }
234         }
235
236         if (rule->rflags & FILTRULE_PERDIR_MERGE) {
237                 filter_rule_list *lp;
238                 unsigned int len;
239                 int i;
240
241                 if ((cp = strrchr(rule->pattern, '/')) != NULL)
242                         cp++;
243                 else
244                         cp = rule->pattern;
245
246                 /* If the local merge file was already mentioned, don't
247                  * add it again. */
248                 for (i = 0; i < mergelist_cnt; i++) {
249                         filter_rule *ex = mergelist_parents[i];
250                         const char *s;
251                         if (!ex)
252                                 continue;
253                         s = strrchr(ex->pattern, '/');
254                         if (s)
255                                 s++;
256                         else
257                                 s = ex->pattern;
258                         len = strlen(s);
259                         if (len == pat_len - (cp - rule->pattern) && memcmp(s, cp, len) == 0) {
260                                 free_filter(rule);
261                                 return;
262                         }
263                 }
264
265                 lp = new_array0(filter_rule_list, 1);
266                 if (asprintf(&lp->debug_type, " [per-dir %s]", cp) < 0)
267                         out_of_memory("add_rule");
268                 rule->u.mergelist = lp;
269
270                 if (mergelist_cnt == mergelist_size) {
271                         mergelist_size += 5;
272                         mergelist_parents = realloc_array(mergelist_parents, filter_rule *, mergelist_size);
273                 }
274                 if (DEBUG_GTE(FILTER, 2)) {
275                         rprintf(FINFO, "[%s] activating mergelist #%d%s\n",
276                                 who_am_i(), mergelist_cnt, lp->debug_type);
277                 }
278                 mergelist_parents[mergelist_cnt++] = rule;
279         } else
280                 rule->u.slash_cnt = slash_cnt;
281
282         if (!listp->tail) {
283                 rule->next = listp->head;
284                 listp->head = listp->tail = rule;
285         } else {
286                 rule->next = listp->tail->next;
287                 listp->tail->next = rule;
288                 listp->tail = rule;
289         }
290 }
291
292 /* This frees any non-inherited items, leaving just inherited items on the list. */
293 static void pop_filter_list(filter_rule_list *listp)
294 {
295         filter_rule *inherited;
296
297         if (!listp->tail)
298                 return;
299
300         inherited = listp->tail->next;
301
302         /* Truncate any inherited items from the local list. */
303         listp->tail->next = NULL;
304         /* Now free everything that is left. */
305         free_filters(listp->head);
306
307         listp->head = inherited;
308         listp->tail = NULL;
309 }
310
311 /* This returns an expanded (absolute) filename for the merge-file name if
312  * the name has any slashes in it OR if the parent_dirscan var is True;
313  * otherwise it returns the original merge_file name.  If the len_ptr value
314  * is non-NULL the merge_file name is limited by the referenced length
315  * value and will be updated with the length of the resulting name.  We
316  * always return a name that is null terminated, even if the merge_file
317  * name was not. */
318 static char *parse_merge_name(const char *merge_file, unsigned int *len_ptr,
319                               unsigned int prefix_skip)
320 {
321         static char buf[MAXPATHLEN];
322         char *fn, tmpbuf[MAXPATHLEN];
323         unsigned int fn_len;
324
325         if (!parent_dirscan && *merge_file != '/') {
326                 /* Return the name unchanged it doesn't have any slashes. */
327                 if (len_ptr) {
328                         const char *p = merge_file + *len_ptr;
329                         while (--p > merge_file && *p != '/') {}
330                         if (p == merge_file) {
331                                 strlcpy(buf, merge_file, *len_ptr + 1);
332                                 return buf;
333                         }
334                 } else if (strchr(merge_file, '/') == NULL)
335                         return (char *)merge_file;
336         }
337
338         fn = *merge_file == '/' ? buf : tmpbuf;
339         if (sanitize_paths) {
340                 const char *r = prefix_skip ? "/" : NULL;
341                 /* null-terminate the name if it isn't already */
342                 if (len_ptr && merge_file[*len_ptr]) {
343                         char *to = fn == buf ? tmpbuf : buf;
344                         strlcpy(to, merge_file, *len_ptr + 1);
345                         merge_file = to;
346                 }
347                 if (!sanitize_path(fn, merge_file, r, dirbuf_depth, SP_DEFAULT)) {
348                         rprintf(FERROR, "merge-file name overflows: %s\n",
349                                 merge_file);
350                         return NULL;
351                 }
352                 fn_len = strlen(fn);
353         } else {
354                 strlcpy(fn, merge_file, len_ptr ? *len_ptr + 1 : MAXPATHLEN);
355                 fn_len = clean_fname(fn, CFN_COLLAPSE_DOT_DOT_DIRS);
356         }
357
358         /* If the name isn't in buf yet, it wasn't absolute. */
359         if (fn != buf) {
360                 int d_len = dirbuf_len - prefix_skip;
361                 if (d_len + fn_len >= MAXPATHLEN) {
362                         rprintf(FERROR, "merge-file name overflows: %s\n", fn);
363                         return NULL;
364                 }
365                 memcpy(buf, dirbuf + prefix_skip, d_len);
366                 memcpy(buf + d_len, fn, fn_len + 1);
367                 fn_len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
368         }
369
370         if (len_ptr)
371                 *len_ptr = fn_len;
372         return buf;
373 }
374
375 /* Sets the dirbuf and dirbuf_len values. */
376 void set_filter_dir(const char *dir, unsigned int dirlen)
377 {
378         unsigned int len;
379         if (*dir != '/') {
380                 memcpy(dirbuf, curr_dir, curr_dir_len);
381                 dirbuf[curr_dir_len] = '/';
382                 len = curr_dir_len + 1;
383                 if (len + dirlen >= MAXPATHLEN)
384                         dirlen = 0;
385         } else
386                 len = 0;
387         memcpy(dirbuf + len, dir, dirlen);
388         dirbuf[dirlen + len] = '\0';
389         dirbuf_len = clean_fname(dirbuf, CFN_COLLAPSE_DOT_DOT_DIRS);
390         if (dirbuf_len > 1 && dirbuf[dirbuf_len-1] == '.'
391             && dirbuf[dirbuf_len-2] == '/')
392                 dirbuf_len -= 2;
393         if (dirbuf_len != 1)
394                 dirbuf[dirbuf_len++] = '/';
395         dirbuf[dirbuf_len] = '\0';
396         if (sanitize_paths)
397                 dirbuf_depth = count_dir_elements(dirbuf + module_dirlen);
398 }
399
400 /* This routine takes a per-dir merge-file entry and finishes its setup.
401  * If the name has a path portion then we check to see if it refers to a
402  * parent directory of the first transfer dir.  If it does, we scan all the
403  * dirs from that point through the parent dir of the transfer dir looking
404  * for the per-dir merge-file in each one. */
405 static BOOL setup_merge_file(int mergelist_num, filter_rule *ex,
406                              filter_rule_list *lp)
407 {
408         char buf[MAXPATHLEN];
409         char *x, *y, *pat = ex->pattern;
410         unsigned int len;
411
412         if (!(x = parse_merge_name(pat, NULL, 0)) || *x != '/')
413                 return 0;
414
415         if (DEBUG_GTE(FILTER, 2)) {
416                 rprintf(FINFO, "[%s] performing parent_dirscan for mergelist #%d%s\n",
417                         who_am_i(), mergelist_num, lp->debug_type);
418         }
419         y = strrchr(x, '/');
420         *y = '\0';
421         ex->pattern = strdup(y+1);
422         if (!*x)
423                 x = "/";
424         if (*x == '/')
425                 strlcpy(buf, x, MAXPATHLEN);
426         else
427                 pathjoin(buf, MAXPATHLEN, dirbuf, x);
428
429         len = clean_fname(buf, CFN_COLLAPSE_DOT_DOT_DIRS);
430         if (len != 1 && len < MAXPATHLEN-1) {
431                 buf[len++] = '/';
432                 buf[len] = '\0';
433         }
434         /* This ensures that the specified dir is a parent of the transfer. */
435         for (x = buf, y = dirbuf; *x && *x == *y; x++, y++) {}
436         if (*x)
437                 y += strlen(y); /* nope -- skip the scan */
438
439         parent_dirscan = True;
440         while (*y) {
441                 char save[MAXPATHLEN];
442                 strlcpy(save, y, MAXPATHLEN);
443                 *y = '\0';
444                 dirbuf_len = y - dirbuf;
445                 strlcpy(x, ex->pattern, MAXPATHLEN - (x - buf));
446                 parse_filter_file(lp, buf, ex, XFLG_ANCHORED2ABS);
447                 if (ex->rflags & FILTRULE_NO_INHERIT) {
448                         /* Free the undesired rules to clean up any per-dir
449                          * mergelists they defined.  Otherwise pop_local_filters
450                          * may crash trying to restore nonexistent state for
451                          * those mergelists. */
452                         free_filters(lp->head);
453                         lp->head = NULL;
454                 }
455                 lp->tail = NULL;
456                 strlcpy(y, save, MAXPATHLEN);
457                 while ((*x++ = *y++) != '/') {}
458         }
459         parent_dirscan = False;
460         if (DEBUG_GTE(FILTER, 2)) {
461                 rprintf(FINFO, "[%s] completed parent_dirscan for mergelist #%d%s\n",
462                         who_am_i(), mergelist_num, lp->debug_type);
463         }
464         free(pat);
465         return 1;
466 }
467
468 struct local_filter_state {
469         int mergelist_cnt;
470         filter_rule_list mergelists[1];
471 };
472
473 /* Each time rsync changes to a new directory it call this function to
474  * handle all the per-dir merge-files.  The "dir" value is the current path
475  * relative to curr_dir (which might not be null-terminated).  We copy it
476  * into dirbuf so that we can easily append a file name on the end. */
477 void *push_local_filters(const char *dir, unsigned int dirlen)
478 {
479         struct local_filter_state *push;
480         int i;
481
482         set_filter_dir(dir, dirlen);
483         if (DEBUG_GTE(FILTER, 2)) {
484                 rprintf(FINFO, "[%s] pushing local filters for %s\n",
485                         who_am_i(), dirbuf);
486         }
487
488         if (!mergelist_cnt) {
489                 /* No old state to save and no new merge files to push. */
490                 return NULL;
491         }
492
493         push = (struct local_filter_state *)new_array(char,
494                           sizeof (struct local_filter_state)
495                         + (mergelist_cnt-1) * sizeof (filter_rule_list));
496
497         push->mergelist_cnt = mergelist_cnt;
498         for (i = 0; i < mergelist_cnt; i++) {
499                 filter_rule *ex = mergelist_parents[i];
500                 if (!ex)
501                         continue;
502                 memcpy(&push->mergelists[i], ex->u.mergelist, sizeof (filter_rule_list));
503         }
504
505         /* Note: parse_filter_file() might increase mergelist_cnt, so keep
506          * this loop separate from the above loop. */
507         for (i = 0; i < mergelist_cnt; i++) {
508                 filter_rule *ex = mergelist_parents[i];
509                 filter_rule_list *lp;
510                 if (!ex)
511                         continue;
512                 lp = ex->u.mergelist;
513
514                 if (DEBUG_GTE(FILTER, 2)) {
515                         rprintf(FINFO, "[%s] pushing mergelist #%d%s\n",
516                                 who_am_i(), i, lp->debug_type);
517                 }
518
519                 lp->tail = NULL; /* Switch any local rules to inherited. */
520                 if (ex->rflags & FILTRULE_NO_INHERIT)
521                         lp->head = NULL;
522
523                 if (ex->rflags & FILTRULE_FINISH_SETUP) {
524                         ex->rflags &= ~FILTRULE_FINISH_SETUP;
525                         if (setup_merge_file(i, ex, lp))
526                                 set_filter_dir(dir, dirlen);
527                 }
528
529                 if (strlcpy(dirbuf + dirbuf_len, ex->pattern,
530                     MAXPATHLEN - dirbuf_len) < MAXPATHLEN - dirbuf_len) {
531                         parse_filter_file(lp, dirbuf, ex,
532                                           XFLG_ANCHORED2ABS);
533                 } else {
534                         io_error |= IOERR_GENERAL;
535                         rprintf(FERROR,
536                             "cannot add local filter rules in long-named directory: %s\n",
537                             full_fname(dirbuf));
538                 }
539                 dirbuf[dirbuf_len] = '\0';
540         }
541
542         return (void*)push;
543 }
544
545 void pop_local_filters(void *mem)
546 {
547         struct local_filter_state *pop = (struct local_filter_state *)mem;
548         int i;
549         int old_mergelist_cnt = pop ? pop->mergelist_cnt : 0;
550
551         if (DEBUG_GTE(FILTER, 2))
552                 rprintf(FINFO, "[%s] popping local filters\n", who_am_i());
553
554         for (i = mergelist_cnt; i-- > 0; ) {
555                 filter_rule *ex = mergelist_parents[i];
556                 filter_rule_list *lp;
557                 if (!ex)
558                         continue;
559                 lp = ex->u.mergelist;
560
561                 if (DEBUG_GTE(FILTER, 2)) {
562                         rprintf(FINFO, "[%s] popping mergelist #%d%s\n",
563                                 who_am_i(), i, lp->debug_type);
564                 }
565
566                 pop_filter_list(lp);
567                 if (i >= old_mergelist_cnt && lp->head) {
568                         /* This mergelist does not exist in the state to be restored, but it
569                          * still has inherited rules.  This can sometimes happen if a per-dir
570                          * merge file calls setup_merge_file() in push_local_filters() and that
571                          * leaves some inherited rules that aren't in the pushed list state. */
572                         if (DEBUG_GTE(FILTER, 2)) {
573                                 rprintf(FINFO, "[%s] freeing parent_dirscan filters of mergelist #%d%s\n",
574                                         who_am_i(), i, ex->u.mergelist->debug_type);
575                         }
576                         pop_filter_list(lp);
577                 }
578         }
579
580         if (!pop)
581                 return; /* No state to restore. */
582
583         for (i = 0; i < old_mergelist_cnt; i++) {
584                 filter_rule *ex = mergelist_parents[i];
585                 if (!ex)
586                         continue;
587                 memcpy(ex->u.mergelist, &pop->mergelists[i], sizeof (filter_rule_list));
588         }
589
590         free(pop);
591 }
592
593 void change_local_filter_dir(const char *dname, int dlen, int dir_depth)
594 {
595         static int cur_depth = -1;
596         static void *filt_array[MAXPATHLEN/2+1];
597
598         if (!dname) {
599                 for ( ; cur_depth >= 0; cur_depth--) {
600                         if (filt_array[cur_depth]) {
601                                 pop_local_filters(filt_array[cur_depth]);
602                                 filt_array[cur_depth] = NULL;
603                         }
604                 }
605                 return;
606         }
607
608         assert(dir_depth < MAXPATHLEN/2+1);
609
610         for ( ; cur_depth >= dir_depth; cur_depth--) {
611                 if (filt_array[cur_depth]) {
612                         pop_local_filters(filt_array[cur_depth]);
613                         filt_array[cur_depth] = NULL;
614                 }
615         }
616
617         cur_depth = dir_depth;
618         filt_array[cur_depth] = push_local_filters(dname, dlen);
619 }
620
621 static int rule_matches(const char *fname, filter_rule *ex, int name_flags)
622 {
623         int slash_handling, str_cnt = 0, anchored_match = 0;
624         int ret_match = ex->rflags & FILTRULE_NEGATE ? 0 : 1;
625         char *p, *pattern = ex->pattern;
626         const char *strings[16]; /* more than enough */
627         const char *name = fname + (*fname == '/');
628
629         if (!*name)
630                 return 0;
631
632         if (!(name_flags & NAME_IS_XATTR) ^ !(ex->rflags & FILTRULE_XATTR))
633                 return 0;
634
635         if (!ex->u.slash_cnt && !(ex->rflags & FILTRULE_WILD2)) {
636                 /* If the pattern does not have any slashes AND it does
637                  * not have a "**" (which could match a slash), then we
638                  * just match the name portion of the path. */
639                 if ((p = strrchr(name,'/')) != NULL)
640                         name = p+1;
641         } else if (ex->rflags & FILTRULE_ABS_PATH && *fname != '/'
642             && curr_dir_len > module_dirlen + 1) {
643                 /* If we're matching against an absolute-path pattern,
644                  * we need to prepend our full path info. */
645                 strings[str_cnt++] = curr_dir + module_dirlen + 1;
646                 strings[str_cnt++] = "/";
647         } else if (ex->rflags & FILTRULE_WILD2_PREFIX && *fname != '/') {
648                 /* Allow "**"+"/" to match at the start of the string. */
649                 strings[str_cnt++] = "/";
650         }
651         strings[str_cnt++] = name;
652         if (name_flags & NAME_IS_DIR) {
653                 /* Allow a trailing "/"+"***" to match the directory. */
654                 if (ex->rflags & FILTRULE_WILD3_SUFFIX)
655                         strings[str_cnt++] = "/";
656         } else if (ex->rflags & FILTRULE_DIRECTORY)
657                 return !ret_match;
658         strings[str_cnt] = NULL;
659
660         if (*pattern == '/') {
661                 anchored_match = 1;
662                 pattern++;
663         }
664
665         if (!anchored_match && ex->u.slash_cnt
666             && !(ex->rflags & FILTRULE_WILD2)) {
667                 /* A non-anchored match with an infix slash and no "**"
668                  * needs to match the last slash_cnt+1 name elements. */
669                 slash_handling = ex->u.slash_cnt + 1;
670         } else if (!anchored_match && !(ex->rflags & FILTRULE_WILD2_PREFIX)
671                                    && ex->rflags & FILTRULE_WILD2) {
672                 /* A non-anchored match with an infix or trailing "**" (but not
673                  * a prefixed "**") needs to try matching after every slash. */
674                 slash_handling = -1;
675         } else {
676                 /* The pattern matches only at the start of the path or name. */
677                 slash_handling = 0;
678         }
679
680         if (ex->rflags & FILTRULE_WILD) {
681                 if (wildmatch_array(pattern, strings, slash_handling))
682                         return ret_match;
683         } else if (str_cnt > 1) {
684                 if (litmatch_array(pattern, strings, slash_handling))
685                         return ret_match;
686         } else if (anchored_match) {
687                 if (strcmp(name, pattern) == 0)
688                         return ret_match;
689         } else {
690                 int l1 = strlen(name);
691                 int l2 = strlen(pattern);
692                 if (l2 <= l1 &&
693                     strcmp(name+(l1-l2),pattern) == 0 &&
694                     (l1==l2 || name[l1-(l2+1)] == '/')) {
695                         return ret_match;
696                 }
697         }
698
699         return !ret_match;
700 }
701
702 static void report_filter_result(enum logcode code, char const *name,
703                                  filter_rule const *ent,
704                                  int name_flags, const char *type)
705 {
706         /* If a trailing slash is present to match only directories,
707          * then it is stripped out by add_rule().  So as a special
708          * case we add it back in here. */
709
710         if (DEBUG_GTE(FILTER, 1)) {
711                 static char *actions[2][2]
712                     = { {"show", "hid"}, {"risk", "protect"} };
713                 const char *w = who_am_i();
714                 const char *t = name_flags & NAME_IS_XATTR ? "xattr"
715                               : name_flags & NAME_IS_DIR ? "directory"
716                               : "file";
717                 rprintf(code, "[%s] %sing %s %s because of pattern %s%s%s\n",
718                     w, actions[*w!='s'][!(ent->rflags & FILTRULE_INCLUDE)],
719                     t, name, ent->pattern,
720                     ent->rflags & FILTRULE_DIRECTORY ? "/" : "", type);
721         }
722 }
723
724 /* This function is used to check if a file should be included/excluded
725  * from the list of files based on its name and type etc.  The value of
726  * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
727 int name_is_excluded(const char *fname, int name_flags, int filter_level)
728 {
729         if (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, name_flags) < 0) {
730                 if (!(name_flags & NAME_IS_XATTR))
731                         errno = ENOENT;
732                 return 1;
733         }
734
735         if (filter_level != ALL_FILTERS)
736                 return 0;
737
738         if (filter_list.head && check_filter(&filter_list, FINFO, fname, name_flags) < 0)
739                 return 1;
740
741         return 0;
742 }
743
744 /* Return -1 if file "name" is defined to be excluded by the specified
745  * exclude list, 1 if it is included, and 0 if it was not matched. */
746 int check_filter(filter_rule_list *listp, enum logcode code,
747                  const char *name, int name_flags)
748 {
749         filter_rule *ent;
750
751         for (ent = listp->head; ent; ent = ent->next) {
752                 if (ignore_perishable && ent->rflags & FILTRULE_PERISHABLE)
753                         continue;
754                 if (ent->rflags & FILTRULE_PERDIR_MERGE) {
755                         int rc = check_filter(ent->u.mergelist, code, name, name_flags);
756                         if (rc)
757                                 return rc;
758                         continue;
759                 }
760                 if (ent->rflags & FILTRULE_CVS_IGNORE) {
761                         int rc = check_filter(&cvs_filter_list, code, name, name_flags);
762                         if (rc)
763                                 return rc;
764                         continue;
765                 }
766                 if (rule_matches(name, ent, name_flags)) {
767                         report_filter_result(code, name, ent, name_flags, listp->debug_type);
768                         return ent->rflags & FILTRULE_INCLUDE ? 1 : -1;
769                 }
770         }
771
772         return 0;
773 }
774
775 #define RULE_STRCMP(s,r) rule_strcmp((s), (r), sizeof (r) - 1)
776
777 static const uchar *rule_strcmp(const uchar *str, const char *rule, int rule_len)
778 {
779         if (strncmp((char*)str, rule, rule_len) != 0)
780                 return NULL;
781         if (isspace(str[rule_len]) || str[rule_len] == '_' || !str[rule_len])
782                 return str + rule_len - 1;
783         if (str[rule_len] == ',')
784                 return str + rule_len;
785         return NULL;
786 }
787
788 #define FILTRULES_FROM_CONTAINER (FILTRULE_ABS_PATH | FILTRULE_INCLUDE \
789                                 | FILTRULE_DIRECTORY | FILTRULE_NEGATE \
790                                 | FILTRULE_PERISHABLE)
791
792 /* Gets the next include/exclude rule from *rulestr_ptr and advances
793  * *rulestr_ptr to point beyond it.  Stores the pattern's start (within
794  * *rulestr_ptr) and length in *pat_ptr and *pat_len_ptr, and returns a newly
795  * allocated filter_rule containing the rest of the information.  Returns
796  * NULL if there are no more rules in the input.
797  *
798  * The template provides defaults for the new rule to inherit, and the
799  * template rflags and the xflags additionally affect parsing. */
800 static filter_rule *parse_rule_tok(const char **rulestr_ptr,
801                                    const filter_rule *template, int xflags,
802                                    const char **pat_ptr, unsigned int *pat_len_ptr)
803 {
804         const uchar *s = (const uchar *)*rulestr_ptr;
805         filter_rule *rule;
806         unsigned int len;
807
808         if (template->rflags & FILTRULE_WORD_SPLIT) {
809                 /* Skip over any initial whitespace. */
810                 while (isspace(*s))
811                         s++;
812                 /* Update to point to real start of rule. */
813                 *rulestr_ptr = (const char *)s;
814         }
815         if (!*s)
816                 return NULL;
817
818         rule = new0(filter_rule);
819
820         /* Inherit from the template.  Don't inherit FILTRULES_SIDES; we check
821          * that later. */
822         rule->rflags = template->rflags & FILTRULES_FROM_CONTAINER;
823
824         /* Figure out what kind of a filter rule "s" is pointing at.  Note
825          * that if FILTRULE_NO_PREFIXES is set, the rule is either an include
826          * or an exclude based on the inheritance of the FILTRULE_INCLUDE
827          * flag (above).  XFLG_OLD_PREFIXES indicates a compatibility mode
828          * for old include/exclude patterns where just "+ " and "- " are
829          * allowed as optional prefixes.  */
830         if (template->rflags & FILTRULE_NO_PREFIXES) {
831                 if (*s == '!' && template->rflags & FILTRULE_CVS_IGNORE)
832                         rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
833         } else if (xflags & XFLG_OLD_PREFIXES) {
834                 if (*s == '-' && s[1] == ' ') {
835                         rule->rflags &= ~FILTRULE_INCLUDE;
836                         s += 2;
837                 } else if (*s == '+' && s[1] == ' ') {
838                         rule->rflags |= FILTRULE_INCLUDE;
839                         s += 2;
840                 } else if (*s == '!')
841                         rule->rflags |= FILTRULE_CLEAR_LIST; /* Tentative! */
842         } else {
843                 char ch = 0;
844                 BOOL prefix_specifies_side = False;
845                 switch (*s) {
846                 case 'c':
847                         if ((s = RULE_STRCMP(s, "clear")) != NULL)
848                                 ch = '!';
849                         break;
850                 case 'd':
851                         if ((s = RULE_STRCMP(s, "dir-merge")) != NULL)
852                                 ch = ':';
853                         break;
854                 case 'e':
855                         if ((s = RULE_STRCMP(s, "exclude")) != NULL)
856                                 ch = '-';
857                         break;
858                 case 'h':
859                         if ((s = RULE_STRCMP(s, "hide")) != NULL)
860                                 ch = 'H';
861                         break;
862                 case 'i':
863                         if ((s = RULE_STRCMP(s, "include")) != NULL)
864                                 ch = '+';
865                         break;
866                 case 'm':
867                         if ((s = RULE_STRCMP(s, "merge")) != NULL)
868                                 ch = '.';
869                         break;
870                 case 'p':
871                         if ((s = RULE_STRCMP(s, "protect")) != NULL)
872                                 ch = 'P';
873                         break;
874                 case 'r':
875                         if ((s = RULE_STRCMP(s, "risk")) != NULL)
876                                 ch = 'R';
877                         break;
878                 case 's':
879                         if ((s = RULE_STRCMP(s, "show")) != NULL)
880                                 ch = 'S';
881                         break;
882                 default:
883                         ch = *s;
884                         if (s[1] == ',')
885                                 s++;
886                         break;
887                 }
888                 switch (ch) {
889                 case ':':
890                         rule->rflags |= FILTRULE_PERDIR_MERGE
891                                       | FILTRULE_FINISH_SETUP;
892                         /* FALL THROUGH */
893                 case '.':
894                         rule->rflags |= FILTRULE_MERGE_FILE;
895                         break;
896                 case '+':
897                         rule->rflags |= FILTRULE_INCLUDE;
898                         break;
899                 case '-':
900                         break;
901                 case 'S':
902                         rule->rflags |= FILTRULE_INCLUDE;
903                         /* FALL THROUGH */
904                 case 'H':
905                         rule->rflags |= FILTRULE_SENDER_SIDE;
906                         prefix_specifies_side = True;
907                         break;
908                 case 'R':
909                         rule->rflags |= FILTRULE_INCLUDE;
910                         /* FALL THROUGH */
911                 case 'P':
912                         rule->rflags |= FILTRULE_RECEIVER_SIDE;
913                         prefix_specifies_side = True;
914                         break;
915                 case '!':
916                         rule->rflags |= FILTRULE_CLEAR_LIST;
917                         break;
918                 default:
919                         rprintf(FERROR, "Unknown filter rule: `%s'\n", *rulestr_ptr);
920                         exit_cleanup(RERR_SYNTAX);
921                 }
922                 while (ch != '!' && *++s && *s != ' ' && *s != '_') {
923                         if (template->rflags & FILTRULE_WORD_SPLIT && isspace(*s)) {
924                                 s--;
925                                 break;
926                         }
927                         switch (*s) {
928                         default:
929                             invalid:
930                                 rprintf(FERROR,
931                                         "invalid modifier '%c' at position %d in filter rule: %s\n",
932                                         *s, (int)(s - (const uchar *)*rulestr_ptr), *rulestr_ptr);
933                                 exit_cleanup(RERR_SYNTAX);
934                         case '-':
935                                 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
936                                         goto invalid;
937                                 rule->rflags |= FILTRULE_NO_PREFIXES;
938                                 break;
939                         case '+':
940                                 if (!BITS_SETnUNSET(rule->rflags, FILTRULE_MERGE_FILE, FILTRULE_NO_PREFIXES))
941                                         goto invalid;
942                                 rule->rflags |= FILTRULE_NO_PREFIXES
943                                               | FILTRULE_INCLUDE;
944                                 break;
945                         case '/':
946                                 rule->rflags |= FILTRULE_ABS_PATH;
947                                 break;
948                         case '!':
949                                 /* Negation really goes with the pattern, so it
950                                  * isn't useful as a merge-file default. */
951                                 if (rule->rflags & FILTRULE_MERGE_FILE)
952                                         goto invalid;
953                                 rule->rflags |= FILTRULE_NEGATE;
954                                 break;
955                         case 'C':
956                                 if (rule->rflags & FILTRULE_NO_PREFIXES || prefix_specifies_side)
957                                         goto invalid;
958                                 rule->rflags |= FILTRULE_NO_PREFIXES
959                                               | FILTRULE_WORD_SPLIT
960                                               | FILTRULE_NO_INHERIT
961                                               | FILTRULE_CVS_IGNORE;
962                                 break;
963                         case 'e':
964                                 if (!(rule->rflags & FILTRULE_MERGE_FILE))
965                                         goto invalid;
966                                 rule->rflags |= FILTRULE_EXCLUDE_SELF;
967                                 break;
968                         case 'n':
969                                 if (!(rule->rflags & FILTRULE_MERGE_FILE))
970                                         goto invalid;
971                                 rule->rflags |= FILTRULE_NO_INHERIT;
972                                 break;
973                         case 'p':
974                                 rule->rflags |= FILTRULE_PERISHABLE;
975                                 break;
976                         case 'r':
977                                 if (prefix_specifies_side)
978                                         goto invalid;
979                                 rule->rflags |= FILTRULE_RECEIVER_SIDE;
980                                 break;
981                         case 's':
982                                 if (prefix_specifies_side)
983                                         goto invalid;
984                                 rule->rflags |= FILTRULE_SENDER_SIDE;
985                                 break;
986                         case 'w':
987                                 if (!(rule->rflags & FILTRULE_MERGE_FILE))
988                                         goto invalid;
989                                 rule->rflags |= FILTRULE_WORD_SPLIT;
990                                 break;
991                         case 'x':
992                                 rule->rflags |= FILTRULE_XATTR;
993                                 saw_xattr_filter = 1;
994                                 break;
995                         }
996                 }
997                 if (*s)
998                         s++;
999         }
1000         if (template->rflags & FILTRULES_SIDES) {
1001                 if (rule->rflags & FILTRULES_SIDES) {
1002                         /* The filter and template both specify side(s).  This
1003                          * is dodgy (and won't work correctly if the template is
1004                          * a one-sided per-dir merge rule), so reject it. */
1005                         rprintf(FERROR,
1006                                 "specified-side merge file contains specified-side filter: %s\n",
1007                                 *rulestr_ptr);
1008                         exit_cleanup(RERR_SYNTAX);
1009                 }
1010                 rule->rflags |= template->rflags & FILTRULES_SIDES;
1011         }
1012
1013         if (template->rflags & FILTRULE_WORD_SPLIT) {
1014                 const uchar *cp = s;
1015                 /* Token ends at whitespace or the end of the string. */
1016                 while (!isspace(*cp) && *cp != '\0')
1017                         cp++;
1018                 len = cp - s;
1019         } else
1020                 len = strlen((char*)s);
1021
1022         if (rule->rflags & FILTRULE_CLEAR_LIST) {
1023                 if (!(rule->rflags & FILTRULE_NO_PREFIXES)
1024                  && !(xflags & XFLG_OLD_PREFIXES) && len) {
1025                         rprintf(FERROR,
1026                                 "'!' rule has trailing characters: %s\n", *rulestr_ptr);
1027                         exit_cleanup(RERR_SYNTAX);
1028                 }
1029                 if (len > 1)
1030                         rule->rflags &= ~FILTRULE_CLEAR_LIST;
1031         } else if (!len && !(rule->rflags & FILTRULE_CVS_IGNORE)) {
1032                 rprintf(FERROR, "unexpected end of filter rule: %s\n", *rulestr_ptr);
1033                 exit_cleanup(RERR_SYNTAX);
1034         }
1035
1036         /* --delete-excluded turns an un-modified include/exclude into a sender-side rule.  */
1037         if (delete_excluded
1038          && !(rule->rflags & (FILTRULES_SIDES|FILTRULE_MERGE_FILE|FILTRULE_PERDIR_MERGE)))
1039                 rule->rflags |= FILTRULE_SENDER_SIDE;
1040
1041         *pat_ptr = (const char *)s;
1042         *pat_len_ptr = len;
1043         *rulestr_ptr = *pat_ptr + len;
1044         return rule;
1045 }
1046
1047 static void get_cvs_excludes(uint32 rflags)
1048 {
1049         static int initialized = 0;
1050         char *p, fname[MAXPATHLEN];
1051
1052         if (initialized)
1053                 return;
1054         initialized = 1;
1055
1056         parse_filter_str(&cvs_filter_list, DEFAULT_CVSIGNORE,
1057                          rule_template(rflags | (protocol_version >= 30 ? FILTRULE_PERISHABLE : 0)),
1058                          0);
1059
1060         p = module_id >= 0 && lp_use_chroot(module_id) ? "/" : getenv("HOME");
1061         if (p && pathjoin(fname, MAXPATHLEN, p, ".cvsignore") < MAXPATHLEN)
1062                 parse_filter_file(&cvs_filter_list, fname, rule_template(rflags), 0);
1063
1064         parse_filter_str(&cvs_filter_list, getenv("CVSIGNORE"), rule_template(rflags), 0);
1065 }
1066
1067 const filter_rule *rule_template(uint32 rflags)
1068 {
1069         static filter_rule template; /* zero-initialized */
1070         template.rflags = rflags;
1071         return &template;
1072 }
1073
1074 void parse_filter_str(filter_rule_list *listp, const char *rulestr,
1075                      const filter_rule *template, int xflags)
1076 {
1077         filter_rule *rule;
1078         const char *pat;
1079         unsigned int pat_len;
1080
1081         if (!rulestr)
1082                 return;
1083
1084         while (1) {
1085                 uint32 new_rflags;
1086
1087                 /* Remember that the returned string is NOT '\0' terminated! */
1088                 if (!(rule = parse_rule_tok(&rulestr, template, xflags, &pat, &pat_len)))
1089                         break;
1090
1091                 if (pat_len >= MAXPATHLEN) {
1092                         rprintf(FERROR, "discarding over-long filter: %.*s\n",
1093                                 (int)pat_len, pat);
1094                     free_continue:
1095                         free_filter(rule);
1096                         continue;
1097                 }
1098
1099                 new_rflags = rule->rflags;
1100                 if (new_rflags & FILTRULE_CLEAR_LIST) {
1101                         if (DEBUG_GTE(FILTER, 2)) {
1102                                 rprintf(FINFO,
1103                                         "[%s] clearing filter list%s\n",
1104                                         who_am_i(), listp->debug_type);
1105                         }
1106                         pop_filter_list(listp);
1107                         listp->head = NULL;
1108                         goto free_continue;
1109                 }
1110
1111                 if (new_rflags & FILTRULE_MERGE_FILE) {
1112                         if (!pat_len) {
1113                                 pat = ".cvsignore";
1114                                 pat_len = 10;
1115                         }
1116                         if (new_rflags & FILTRULE_EXCLUDE_SELF) {
1117                                 const char *name;
1118                                 filter_rule *excl_self;
1119
1120                                 excl_self = new0(filter_rule);
1121                                 /* Find the beginning of the basename and add an exclude for it. */
1122                                 for (name = pat + pat_len; name > pat && name[-1] != '/'; name--) {}
1123                                 add_rule(listp, name, (pat + pat_len) - name, excl_self, 0);
1124                                 rule->rflags &= ~FILTRULE_EXCLUDE_SELF;
1125                         }
1126                         if (new_rflags & FILTRULE_PERDIR_MERGE) {
1127                                 if (parent_dirscan) {
1128                                         const char *p;
1129                                         unsigned int len = pat_len;
1130                                         if ((p = parse_merge_name(pat, &len, module_dirlen)))
1131                                                 add_rule(listp, p, len, rule, 0);
1132                                         else
1133                                                 free_filter(rule);
1134                                         continue;
1135                                 }
1136                         } else {
1137                                 const char *p;
1138                                 unsigned int len = pat_len;
1139                                 if ((p = parse_merge_name(pat, &len, 0)))
1140                                         parse_filter_file(listp, p, rule, XFLG_FATAL_ERRORS);
1141                                 free_filter(rule);
1142                                 continue;
1143                         }
1144                 }
1145
1146                 add_rule(listp, pat, pat_len, rule, xflags);
1147
1148                 if (new_rflags & FILTRULE_CVS_IGNORE
1149                     && !(new_rflags & FILTRULE_MERGE_FILE))
1150                         get_cvs_excludes(new_rflags);
1151         }
1152 }
1153
1154 void parse_filter_file(filter_rule_list *listp, const char *fname, const filter_rule *template, int xflags)
1155 {
1156         FILE *fp;
1157         char line[BIGPATHBUFLEN];
1158         char *eob = line + sizeof line - 1;
1159         BOOL word_split = (template->rflags & FILTRULE_WORD_SPLIT) != 0;
1160
1161         if (!fname || !*fname)
1162                 return;
1163
1164         if (*fname != '-' || fname[1] || am_server) {
1165                 if (daemon_filter_list.head) {
1166                         strlcpy(line, fname, sizeof line);
1167                         clean_fname(line, CFN_COLLAPSE_DOT_DOT_DIRS);
1168                         if (check_filter(&daemon_filter_list, FLOG, line, 0) < 0)
1169                                 fp = NULL;
1170                         else
1171                                 fp = fopen(line, "rb");
1172                 } else
1173                         fp = fopen(fname, "rb");
1174         } else
1175                 fp = stdin;
1176
1177         if (DEBUG_GTE(FILTER, 2)) {
1178                 rprintf(FINFO, "[%s] parse_filter_file(%s,%x,%x)%s\n",
1179                         who_am_i(), fname, template->rflags, xflags,
1180                         fp ? "" : " [not found]");
1181         }
1182
1183         if (!fp) {
1184                 if (xflags & XFLG_FATAL_ERRORS) {
1185                         rsyserr(FERROR, errno,
1186                                 "failed to open %sclude file %s",
1187                                 template->rflags & FILTRULE_INCLUDE ? "in" : "ex",
1188                                 fname);
1189                         exit_cleanup(RERR_FILEIO);
1190                 }
1191                 return;
1192         }
1193         dirbuf[dirbuf_len] = '\0';
1194
1195         while (1) {
1196                 char *s = line;
1197                 int ch, overflow = 0;
1198                 while (1) {
1199                         if ((ch = getc(fp)) == EOF) {
1200                                 if (ferror(fp) && errno == EINTR) {
1201                                         clearerr(fp);
1202                                         continue;
1203                                 }
1204                                 break;
1205                         }
1206                         if (word_split && isspace(ch))
1207                                 break;
1208                         if (eol_nulls? !ch : (ch == '\n' || ch == '\r'))
1209                                 break;
1210                         if (s < eob)
1211                                 *s++ = ch;
1212                         else
1213                                 overflow = 1;
1214                 }
1215                 if (overflow) {
1216                         rprintf(FERROR, "discarding over-long filter: %s...\n", line);
1217                         s = line;
1218                 }
1219                 *s = '\0';
1220                 /* Skip an empty token and (when line parsing) comments. */
1221                 if (*line && (word_split || (*line != ';' && *line != '#')))
1222                         parse_filter_str(listp, line, template, xflags);
1223                 if (ch == EOF)
1224                         break;
1225         }
1226         fclose(fp);
1227 }
1228
1229 /* If the "for_xfer" flag is set, the prefix is made compatible with the
1230  * current protocol_version (if possible) or a NULL is returned (if not
1231  * possible). */
1232 char *get_rule_prefix(filter_rule *rule, const char *pat, int for_xfer,
1233                       unsigned int *plen_ptr)
1234 {
1235         static char buf[MAX_RULE_PREFIX+1];
1236         char *op = buf;
1237         int legal_len = for_xfer && protocol_version < 29 ? 1 : MAX_RULE_PREFIX-1;
1238
1239         if (rule->rflags & FILTRULE_PERDIR_MERGE) {
1240                 if (legal_len == 1)
1241                         return NULL;
1242                 *op++ = ':';
1243         } else if (rule->rflags & FILTRULE_INCLUDE)
1244                 *op++ = '+';
1245         else if (legal_len != 1
1246             || ((*pat == '-' || *pat == '+') && pat[1] == ' '))
1247                 *op++ = '-';
1248         else
1249                 legal_len = 0;
1250
1251         if (rule->rflags & FILTRULE_ABS_PATH)
1252                 *op++ = '/';
1253         if (rule->rflags & FILTRULE_NEGATE)
1254                 *op++ = '!';
1255         if (rule->rflags & FILTRULE_CVS_IGNORE)
1256                 *op++ = 'C';
1257         else {
1258                 if (rule->rflags & FILTRULE_NO_INHERIT)
1259                         *op++ = 'n';
1260                 if (rule->rflags & FILTRULE_WORD_SPLIT)
1261                         *op++ = 'w';
1262                 if (rule->rflags & FILTRULE_NO_PREFIXES) {
1263                         if (rule->rflags & FILTRULE_INCLUDE)
1264                                 *op++ = '+';
1265                         else
1266                                 *op++ = '-';
1267                 }
1268         }
1269         if (rule->rflags & FILTRULE_EXCLUDE_SELF)
1270                 *op++ = 'e';
1271         if (rule->rflags & FILTRULE_XATTR)
1272                 *op++ = 'x';
1273         if (rule->rflags & FILTRULE_SENDER_SIDE
1274             && (!for_xfer || protocol_version >= 29))
1275                 *op++ = 's';
1276         if (rule->rflags & FILTRULE_RECEIVER_SIDE
1277             && (!for_xfer || protocol_version >= 29
1278              || (delete_excluded && am_sender)))
1279                 *op++ = 'r';
1280         if (rule->rflags & FILTRULE_PERISHABLE) {
1281                 if (!for_xfer || protocol_version >= 30)
1282                         *op++ = 'p';
1283                 else if (am_sender)
1284                         return NULL;
1285         }
1286         if (op - buf > legal_len)
1287                 return NULL;
1288         if (legal_len)
1289                 *op++ = ' ';
1290         *op = '\0';
1291         if (plen_ptr)
1292                 *plen_ptr = op - buf;
1293         return buf;
1294 }
1295
1296 static void send_rules(int f_out, filter_rule_list *flp)
1297 {
1298         filter_rule *ent, *prev = NULL;
1299
1300         for (ent = flp->head; ent; ent = ent->next) {
1301                 unsigned int len, plen, dlen;
1302                 int elide = 0;
1303                 char *p;
1304
1305                 /* Note we need to check delete_excluded here in addition to
1306                  * the code in parse_rule_tok() because some rules may have
1307                  * been added before we found the --delete-excluded option.
1308                  * We must also elide any CVS merge-file rules to avoid a
1309                  * backward compatibility problem, and we elide any no-prefix
1310                  * merge files as an optimization (since they can only have
1311                  * include/exclude rules). */
1312                 if (ent->rflags & FILTRULE_SENDER_SIDE)
1313                         elide = am_sender ? 1 : -1;
1314                 if (ent->rflags & FILTRULE_RECEIVER_SIDE)
1315                         elide = elide ? 0 : am_sender ? -1 : 1;
1316                 else if (delete_excluded && !elide
1317                  && (!(ent->rflags & FILTRULE_PERDIR_MERGE)
1318                   || ent->rflags & FILTRULE_NO_PREFIXES))
1319                         elide = am_sender ? 1 : -1;
1320                 if (elide < 0) {
1321                         if (prev)
1322                                 prev->next = ent->next;
1323                         else
1324                                 flp->head = ent->next;
1325                 } else
1326                         prev = ent;
1327                 if (elide > 0)
1328                         continue;
1329                 if (ent->rflags & FILTRULE_CVS_IGNORE
1330                     && !(ent->rflags & FILTRULE_MERGE_FILE)) {
1331                         int f = am_sender || protocol_version < 29 ? f_out : -2;
1332                         send_rules(f, &cvs_filter_list);
1333                         if (f == f_out)
1334                                 continue;
1335                 }
1336                 p = get_rule_prefix(ent, ent->pattern, 1, &plen);
1337                 if (!p) {
1338                         rprintf(FERROR,
1339                                 "filter rules are too modern for remote rsync.\n");
1340                         exit_cleanup(RERR_PROTOCOL);
1341                 }
1342                 if (f_out < 0)
1343                         continue;
1344                 len = strlen(ent->pattern);
1345                 dlen = ent->rflags & FILTRULE_DIRECTORY ? 1 : 0;
1346                 if (!(plen + len + dlen))
1347                         continue;
1348                 write_int(f_out, plen + len + dlen);
1349                 if (plen)
1350                         write_buf(f_out, p, plen);
1351                 write_buf(f_out, ent->pattern, len);
1352                 if (dlen)
1353                         write_byte(f_out, '/');
1354         }
1355         flp->tail = prev;
1356 }
1357
1358 /* This is only called by the client. */
1359 void send_filter_list(int f_out)
1360 {
1361         int receiver_wants_list = prune_empty_dirs
1362             || (delete_mode && (!delete_excluded || protocol_version >= 29));
1363
1364         if (local_server || (am_sender && !receiver_wants_list))
1365                 f_out = -1;
1366         if (cvs_exclude && am_sender) {
1367                 if (protocol_version >= 29)
1368                         parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1369                 parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1370         }
1371
1372         send_rules(f_out, &filter_list);
1373
1374         if (f_out >= 0)
1375                 write_int(f_out, 0);
1376
1377         if (cvs_exclude) {
1378                 if (!am_sender || protocol_version < 29)
1379                         parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1380                 if (!am_sender)
1381                         parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1382         }
1383 }
1384
1385 /* This is only called by the server. */
1386 void recv_filter_list(int f_in)
1387 {
1388         char line[BIGPATHBUFLEN];
1389         int xflags = protocol_version >= 29 ? 0 : XFLG_OLD_PREFIXES;
1390         int receiver_wants_list = prune_empty_dirs
1391             || (delete_mode && (!delete_excluded || protocol_version >= 29));
1392         unsigned int len;
1393
1394         if (!local_server && (am_sender || receiver_wants_list)) {
1395                 while ((len = read_int(f_in)) != 0) {
1396                         if (len >= sizeof line)
1397                                 overflow_exit("recv_rules");
1398                         read_sbuf(f_in, line, len);
1399                         parse_filter_str(&filter_list, line, rule_template(0), xflags);
1400                 }
1401         }
1402
1403         if (cvs_exclude) {
1404                 if (local_server || am_sender || protocol_version < 29)
1405                         parse_filter_str(&filter_list, ":C", rule_template(0), 0);
1406                 if (local_server || am_sender)
1407                         parse_filter_str(&filter_list, "-C", rule_template(0), 0);
1408         }
1409
1410         if (local_server) /* filter out any rules that aren't for us. */
1411                 send_rules(-1, &filter_list);
1412 }