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