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