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