Got rid of RERR_LOG_FAILURE.
[rsync.git] / exclude.c
1 /* -*- c-file-style: "linux" -*-
2  *
3  * Copyright (C) 1996-2001 by Andrew Tridgell <tridge@samba.org>
4  * Copyright (C) 1996 by Paul Mackerras
5  * Copyright (C) 2002 by Martin Pool
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21
22 /* a lot of this stuff was originally derived from GNU tar, although
23    it has now changed so much that it is hard to tell :) */
24
25 /* include/exclude cluestick added by Martin Pool <mbp@samba.org> */
26
27 #include "rsync.h"
28
29 extern int verbose;
30 extern int am_server;
31 extern int am_sender;
32 extern int eol_nulls;
33 extern int list_only;
34 extern int recurse;
35 extern int io_error;
36 extern int local_server;
37 extern int delete_mode;
38 extern int delete_excluded;
39 extern int cvs_exclude;
40 extern int sanitize_paths;
41 extern int protocol_version;
42 extern int module_id;
43
44 extern char curr_dir[];
45 extern unsigned int curr_dir_len;
46 extern unsigned int module_dirlen;
47
48 struct filter_list_struct filter_list = { 0, 0, "" };
49 struct filter_list_struct cvs_filter_list = { 0, 0, " [cvsignore]" };
50 struct filter_list_struct server_filter_list = { 0, 0, " [server]" };
51
52 /* Need room enough for ":MODS " prefix plus some room to grow. */
53 #define MAX_RULE_PREFIX (16)
54
55 #define MODIFIERS_MERGE_FILE "-+Cenw"
56 #define MODIFIERS_INCL_EXCL "/!Crs"
57 #define MODIFIERS_HIDE_PROTECT "/!"
58
59 /* The dirbuf is set by push_local_filters() to the current subdirectory
60  * relative to curr_dir that is being processed.  The path always has a
61  * trailing slash appended, and the variable dirbuf_len contains the length
62  * of this path prefix.  The path is always absolute. */
63 static char dirbuf[MAXPATHLEN+1];
64 static unsigned int dirbuf_len = 0;
65 static int dirbuf_depth;
66
67 /* This is True when we're scanning parent dirs for per-dir merge-files. */
68 static BOOL parent_dirscan = False;
69
70 /* This array contains a list of all the currently active per-dir merge
71  * files.  This makes it easier to save the appropriate values when we
72  * "push" down into each subdirectory. */
73 static struct filter_struct **mergelist_parents;
74 static int mergelist_cnt = 0;
75 static int mergelist_size = 0;
76
77 /* Each filter_list_struct describes a singly-linked list by keeping track
78  * of both the head and tail pointers.  The list is slightly unusual in that
79  * a parent-dir's content can be appended to the end of the local list in a
80  * special way:  the last item in the local list has its "next" pointer set
81  * to point to the inherited list, but the local list's tail pointer points
82  * at the end of the local list.  Thus, if the local list is empty, the head
83  * will be pointing at the inherited content but the tail will be NULL.  To
84  * help you visualize this, here are the possible list arrangements:
85  *
86  * Completely Empty                     Local Content Only
87  * ==================================   ====================================
88  * head -> NULL                         head -> Local1 -> Local2 -> NULL
89  * tail -> NULL                         tail -------------^
90  *
91  * Inherited Content Only               Both Local and Inherited Content
92  * ==================================   ====================================
93  * head -> Parent1 -> Parent2 -> NULL   head -> L1 -> L2 -> P1 -> P2 -> NULL
94  * tail -> NULL                         tail ---------^
95  *
96  * This means that anyone wanting to traverse the whole list to use it just
97  * needs to start at the head and use the "next" pointers until it goes
98  * NULL.  To add new local content, we insert the item after the tail item
99  * and update the tail (obviously, if "tail" was NULL, we insert it at the
100  * head).  To clear the local list, WE MUST NOT FREE THE INHERITED CONTENT
101  * because it is shared between the current list and our parent list(s).
102  * The easiest way to handle this is to simply truncate the list after the
103  * tail item and then free the local list from the head.  When inheriting
104  * the list for a new local dir, we just save off the filter_list_struct
105  * values (so we can pop back to them later) and set the tail to NULL.
106  */
107
108 static void free_filter(struct filter_struct *ex)
109 {
110         if (ex->match_flags & MATCHFLG_PERDIR_MERGE) {
111                 free(ex->u.mergelist->debug_type);
112                 free(ex->u.mergelist);
113                 mergelist_cnt--;
114         }
115         free(ex->pattern);
116         free(ex);
117 }
118
119 /* Build a filter structure given a filter pattern.  The value in "pat"
120  * is not null-terminated. */
121 static void add_rule(struct filter_list_struct *listp, const char *pat,
122                      unsigned int pat_len, uint32 mflags, int xflags)
123 {
124         struct filter_struct *ret;
125         const char *cp;
126         unsigned int ex_len;
127
128         if (verbose > 2) {
129                 rprintf(FINFO, "[%s] add_rule(%s%.*s%s)%s\n",
130                         who_am_i(), get_rule_prefix(mflags, pat, 0, NULL),
131                         (int)pat_len, pat,
132                         (mflags & MATCHFLG_DIRECTORY) ? "/" : "",
133                         listp->debug_type);
134         }
135
136         /* This flag also indicates that we're reading a list that
137          * needs to be filtered now, not post-filtered later. */
138         if (xflags & XFLG_ANCHORED2ABS) {
139                 uint32 mf = mflags & (MATCHFLG_RECEIVER_SIDE|MATCHFLG_SENDER_SIDE);
140                 if (am_sender) {
141                         if (mf == MATCHFLG_RECEIVER_SIDE)
142                                 return;
143                 } else {
144                         if (mf == MATCHFLG_SENDER_SIDE)
145                                 return;
146                 }
147         }
148
149         if (!(ret = new(struct filter_struct)))
150                 out_of_memory("add_rule");
151         memset(ret, 0, sizeof ret[0]);
152
153         if (xflags & XFLG_ANCHORED2ABS && *pat == '/'
154             && !(mflags & (MATCHFLG_ABS_PATH | MATCHFLG_MERGE_FILE))) {
155                 mflags |= MATCHFLG_ABS_PATH;
156                 ex_len = dirbuf_len - module_dirlen - 1;
157         } else
158                 ex_len = 0;
159         if (!(ret->pattern = new_array(char, ex_len + pat_len + 1)))
160                 out_of_memory("add_rule");
161         if (ex_len)
162                 memcpy(ret->pattern, dirbuf + module_dirlen, ex_len);
163         strlcpy(ret->pattern + ex_len, pat, pat_len + 1);
164         pat_len += ex_len;
165
166         if (strpbrk(ret->pattern, "*[?")) {
167                 mflags |= MATCHFLG_WILD;
168                 if ((cp = strstr(ret->pattern, "**")) != NULL) {
169                         mflags |= MATCHFLG_WILD2;
170                         /* If the pattern starts with **, note that. */
171                         if (cp == ret->pattern)
172                                 mflags |= MATCHFLG_WILD2_PREFIX;
173                 }
174         }
175
176         if (pat_len > 1 && ret->pattern[pat_len-1] == '/') {
177                 ret->pattern[pat_len-1] = 0;
178                 mflags |= MATCHFLG_DIRECTORY;
179         }
180
181         if (mflags & MATCHFLG_PERDIR_MERGE) {
182                 struct filter_list_struct *lp;
183                 unsigned int len;
184                 int i;
185
186                 if ((cp = strrchr(ret->pattern, '/')) != NULL)
187                         cp++;
188                 else
189                         cp = ret->pattern;
190
191                 /* If the local merge file was already mentioned, don't
192                  * add it again. */
193                 for (i = 0; i < mergelist_cnt; i++) {
194                         struct filter_struct *ex = mergelist_parents[i];
195                         const char *s = strrchr(ex->pattern, '/');
196                         if (s)
197                                 s++;
198                         else
199                                 s = ex->pattern;
200                         len = strlen(s);
201                         if (len == pat_len - (cp - ret->pattern)
202                             && memcmp(s, cp, len) == 0) {
203                                 free_filter(ret);
204                                 return;
205                         }
206                 }
207
208                 if (!(lp = new_array(struct filter_list_struct, 1)))
209                         out_of_memory("add_rule");
210                 lp->head = lp->tail = NULL;
211                 if (asprintf(&lp->debug_type, " [per-dir %s]", cp) < 0)
212                         out_of_memory("add_rule");
213                 ret->u.mergelist = lp;
214
215                 if (mergelist_cnt == mergelist_size) {
216                         mergelist_size += 5;
217                         mergelist_parents = realloc_array(mergelist_parents,
218                                                 struct filter_struct *,
219                                                 mergelist_size);
220                         if (!mergelist_parents)
221                                 out_of_memory("add_rule");
222                 }
223                 mergelist_parents[mergelist_cnt++] = ret;
224         } else {
225                 for (cp = ret->pattern; (cp = strchr(cp, '/')) != NULL; cp++)
226                         ret->u.slash_cnt++;
227         }
228
229         ret->match_flags = mflags;
230
231         if (!listp->tail) {
232                 ret->next = listp->head;
233                 listp->head = listp->tail = ret;
234         } else {
235                 ret->next = listp->tail->next;
236                 listp->tail->next = ret;
237                 listp->tail = ret;
238         }
239 }
240
241 static void clear_filter_list(struct filter_list_struct *listp)
242 {
243         if (listp->tail) {
244                 struct filter_struct *ent, *next;
245                 /* Truncate any inherited items from the local list. */
246                 listp->tail->next = NULL;
247                 /* Now free everything that is left. */
248                 for (ent = listp->head; ent; ent = next) {
249                         next = ent->next;
250                         free_filter(ent);
251                 }
252         }
253
254         listp->head = listp->tail = NULL;
255 }
256
257 /* This returns an expanded (absolute) filename for the merge-file name if
258  * the name has any slashes in it OR if the parent_dirscan var is True;
259  * otherwise it returns the original merge_file name.  If the len_ptr value
260  * is non-NULL the merge_file name is limited by the referenced length
261  * value and will be updated with the length of the resulting name.  We
262  * always return a name that is null terminated, even if the merge_file
263  * name was not. */
264 static char *parse_merge_name(const char *merge_file, unsigned int *len_ptr,
265                               unsigned int prefix_skip)
266 {
267         static char buf[MAXPATHLEN];
268         char *fn, tmpbuf[MAXPATHLEN];
269         unsigned int fn_len;
270
271         if (!parent_dirscan && *merge_file != '/') {
272                 /* Return the name unchanged it doesn't have any slashes. */
273                 if (len_ptr) {
274                         const char *p = merge_file + *len_ptr;
275                         while (--p > merge_file && *p != '/') {}
276                         if (p == merge_file) {
277                                 strlcpy(buf, merge_file, *len_ptr + 1);
278                                 return buf;
279                         }
280                 } else if (strchr(merge_file, '/') == NULL)
281                         return (char *)merge_file;
282         }
283
284         fn = *merge_file == '/' ? buf : tmpbuf;
285         if (sanitize_paths) {
286                 const char *r = prefix_skip ? "/" : NULL;
287                 /* null-terminate the name if it isn't already */
288                 if (len_ptr && merge_file[*len_ptr]) {
289                         char *to = fn == buf ? tmpbuf : buf;
290                         strlcpy(to, merge_file, *len_ptr + 1);
291                         merge_file = to;
292                 }
293                 if (!sanitize_path(fn, merge_file, r, dirbuf_depth)) {
294                         rprintf(FERROR, "merge-file name overflows: %s\n",
295                                 safe_fname(merge_file));
296                         return NULL;
297                 }
298         } else {
299                 strlcpy(fn, merge_file, len_ptr ? *len_ptr + 1 : MAXPATHLEN);
300                 clean_fname(fn, 1);
301         }
302         
303         fn_len = strlen(fn);
304         if (fn == buf)
305                 goto done;
306
307         if (dirbuf_len + fn_len >= MAXPATHLEN) {
308                 rprintf(FERROR, "merge-file name overflows: %s\n",
309                         safe_fname(fn));
310                 return NULL;
311         }
312         memcpy(buf, dirbuf + prefix_skip, dirbuf_len - prefix_skip);
313         memcpy(buf + dirbuf_len - prefix_skip, fn, fn_len + 1);
314         fn_len = clean_fname(buf, 1);
315
316     done:
317         if (len_ptr)
318                 *len_ptr = fn_len;
319         return buf;
320 }
321
322 /* Sets the dirbuf and dirbuf_len values. */
323 void set_filter_dir(const char *dir, unsigned int dirlen)
324 {
325         unsigned int len;
326         if (*dir != '/') {
327                 memcpy(dirbuf, curr_dir, curr_dir_len);
328                 dirbuf[curr_dir_len] = '/';
329                 len = curr_dir_len + 1;
330                 if (len + dirlen >= MAXPATHLEN)
331                         dirlen = 0;
332         } else
333                 len = 0;
334         memcpy(dirbuf + len, dir, dirlen);
335         dirbuf[dirlen + len] = '\0';
336         dirbuf_len = clean_fname(dirbuf, 1);
337         if (dirbuf_len > 1 && dirbuf[dirbuf_len-1] == '.'
338             && dirbuf[dirbuf_len-2] == '/')
339                 dirbuf_len -= 2;
340         if (dirbuf_len != 1)
341                 dirbuf[dirbuf_len++] = '/';
342         dirbuf[dirbuf_len] = '\0';
343         if (sanitize_paths)
344                 dirbuf_depth = count_dir_elements(dirbuf + module_dirlen);
345 }
346
347 /* This routine takes a per-dir merge-file entry and finishes its setup.
348  * If the name has a path portion then we check to see if it refers to a
349  * parent directory of the first transfer dir.  If it does, we scan all the
350  * dirs from that point through the parent dir of the transfer dir looking
351  * for the per-dir merge-file in each one. */
352 static BOOL setup_merge_file(struct filter_struct *ex,
353                              struct filter_list_struct *lp)
354 {
355         char buf[MAXPATHLEN];
356         char *x, *y, *pat = ex->pattern;
357         unsigned int len;
358
359         if (!(x = parse_merge_name(pat, NULL, 0)) || *x != '/')
360                 return 0;
361
362         y = strrchr(x, '/');
363         *y = '\0';
364         ex->pattern = strdup(y+1);
365         if (!*x)
366                 x = "/";
367         if (*x == '/')
368                 strlcpy(buf, x, MAXPATHLEN);
369         else
370                 pathjoin(buf, MAXPATHLEN, dirbuf, x);
371
372         len = clean_fname(buf, 1);
373         if (len != 1 && len < MAXPATHLEN-1) {
374                 buf[len++] = '/';
375                 buf[len] = '\0';
376         }
377         /* This ensures that the specified dir is a parent of the transfer. */
378         for (x = buf, y = dirbuf; *x && *x == *y; x++, y++) {}
379         if (*x)
380                 y += strlen(y); /* nope -- skip the scan */
381
382         parent_dirscan = True;
383         while (*y) {
384                 char save[MAXPATHLEN];
385                 strlcpy(save, y, MAXPATHLEN);
386                 *y = '\0';
387                 dirbuf_len = y - dirbuf;
388                 strlcpy(x, ex->pattern, MAXPATHLEN - (x - buf));
389                 parse_filter_file(lp, buf, ex->match_flags, XFLG_ANCHORED2ABS);
390                 if (ex->match_flags & MATCHFLG_NO_INHERIT)
391                         lp->head = NULL;
392                 lp->tail = NULL;
393                 strlcpy(y, save, MAXPATHLEN);
394                 while ((*x++ = *y++) != '/') {}
395         }
396         parent_dirscan = False;
397         free(pat);
398         return 1;
399 }
400
401 /* Each time rsync changes to a new directory it call this function to
402  * handle all the per-dir merge-files.  The "dir" value is the current path
403  * relative to curr_dir (which might not be null-terminated).  We copy it
404  * into dirbuf so that we can easily append a file name on the end. */
405 void *push_local_filters(const char *dir, unsigned int dirlen)
406 {
407         struct filter_list_struct *ap, *push;
408         int i;
409
410         set_filter_dir(dir, dirlen);
411
412         if (!mergelist_cnt)
413                 return NULL;
414
415         push = new_array(struct filter_list_struct, mergelist_cnt);
416         if (!push)
417                 out_of_memory("push_local_filters");
418
419         for (i = 0, ap = push; i < mergelist_cnt; i++) {
420                 memcpy(ap++, mergelist_parents[i]->u.mergelist,
421                        sizeof (struct filter_list_struct));
422         }
423
424         /* Note: parse_filter_file() might increase mergelist_cnt, so keep
425          * this loop separate from the above loop. */
426         for (i = 0; i < mergelist_cnt; i++) {
427                 struct filter_struct *ex = mergelist_parents[i];
428                 struct filter_list_struct *lp = ex->u.mergelist;
429
430                 if (verbose > 2) {
431                         rprintf(FINFO, "[%s] pushing filter list%s\n",
432                                 who_am_i(), lp->debug_type);
433                 }
434
435                 lp->tail = NULL; /* Switch any local rules to inherited. */
436                 if (ex->match_flags & MATCHFLG_NO_INHERIT)
437                         lp->head = NULL;
438
439                 if (ex->match_flags & MATCHFLG_FINISH_SETUP) {
440                         ex->match_flags &= ~MATCHFLG_FINISH_SETUP;
441                         if (setup_merge_file(ex, lp))
442                                 set_filter_dir(dir, dirlen);
443                 }
444
445                 if (strlcpy(dirbuf + dirbuf_len, ex->pattern,
446                     MAXPATHLEN - dirbuf_len) < MAXPATHLEN - dirbuf_len) {
447                         parse_filter_file(lp, dirbuf, ex->match_flags,
448                                           XFLG_ANCHORED2ABS);
449                 } else {
450                         io_error |= IOERR_GENERAL;
451                         rprintf(FINFO,
452                             "cannot add local filter rules in long-named directory: %s\n",
453                             full_fname(dirbuf));
454                 }
455                 dirbuf[dirbuf_len] = '\0';
456         }
457
458         return (void*)push;
459 }
460
461 void pop_local_filters(void *mem)
462 {
463         struct filter_list_struct *ap, *pop = (struct filter_list_struct*)mem;
464         int i;
465
466         for (i = mergelist_cnt; i-- > 0; ) {
467                 struct filter_struct *ex = mergelist_parents[i];
468                 struct filter_list_struct *lp = ex->u.mergelist;
469
470                 if (verbose > 2) {
471                         rprintf(FINFO, "[%s] popping filter list%s\n",
472                                 who_am_i(), lp->debug_type);
473                 }
474
475                 clear_filter_list(lp);
476         }
477
478         if (!pop)
479                 return;
480
481         for (i = 0, ap = pop; i < mergelist_cnt; i++) {
482                 memcpy(mergelist_parents[i]->u.mergelist, ap++,
483                        sizeof (struct filter_list_struct));
484         }
485
486         free(pop);
487 }
488
489 static int rule_matches(char *name, struct filter_struct *ex, int name_is_dir)
490 {
491         char *p, full_name[MAXPATHLEN];
492         int match_start = 0;
493         int ret_match = ex->match_flags & MATCHFLG_NEGATE ? 0 : 1;
494         char *pattern = ex->pattern;
495
496         if (!*name)
497                 return 0;
498
499         /* If the pattern does not have any slashes AND it does not have
500          * a "**" (which could match a slash), then we just match the
501          * name portion of the path. */
502         if (!ex->u.slash_cnt && !(ex->match_flags & MATCHFLG_WILD2)) {
503                 if ((p = strrchr(name,'/')) != NULL)
504                         name = p+1;
505         }
506         else if (ex->match_flags & MATCHFLG_ABS_PATH && *name != '/'
507             && curr_dir_len > module_dirlen + 1) {
508                 pathjoin(full_name, sizeof full_name,
509                          curr_dir + module_dirlen + 1, name);
510                 name = full_name;
511         }
512
513         if (ex->match_flags & MATCHFLG_DIRECTORY && !name_is_dir)
514                 return !ret_match;
515
516         if (*pattern == '/') {
517                 match_start = 1;
518                 pattern++;
519                 if (*name == '/')
520                         name++;
521         }
522
523         if (ex->match_flags & MATCHFLG_WILD) {
524                 /* A non-anchored match with an infix slash and no "**"
525                  * needs to match the last slash_cnt+1 name elements. */
526                 if (!match_start && ex->u.slash_cnt
527                     && !(ex->match_flags & MATCHFLG_WILD2)) {
528                         int cnt = ex->u.slash_cnt + 1;
529                         for (p = name + strlen(name) - 1; p >= name; p--) {
530                                 if (*p == '/' && !--cnt)
531                                         break;
532                         }
533                         name = p+1;
534                 }
535                 if (wildmatch(pattern, name))
536                         return ret_match;
537                 if (ex->match_flags & MATCHFLG_WILD2_PREFIX) {
538                         /* If the **-prefixed pattern has a '/' as the next
539                          * character, then try to match the rest of the
540                          * pattern at the root. */
541                         if (pattern[2] == '/' && wildmatch(pattern+3, name))
542                                 return ret_match;
543                 }
544                 else if (!match_start && ex->match_flags & MATCHFLG_WILD2) {
545                         /* A non-anchored match with an infix or trailing "**"
546                          * (but not a prefixed "**") needs to try matching
547                          * after every slash. */
548                         while ((name = strchr(name, '/')) != NULL) {
549                                 name++;
550                                 if (wildmatch(pattern, name))
551                                         return ret_match;
552                         }
553                 }
554         } else if (match_start) {
555                 if (strcmp(name,pattern) == 0)
556                         return ret_match;
557         } else {
558                 int l1 = strlen(name);
559                 int l2 = strlen(pattern);
560                 if (l2 <= l1 &&
561                     strcmp(name+(l1-l2),pattern) == 0 &&
562                     (l1==l2 || name[l1-(l2+1)] == '/')) {
563                         return ret_match;
564                 }
565         }
566
567         return !ret_match;
568 }
569
570
571 static void report_filter_result(char const *name,
572                                  struct filter_struct const *ent,
573                                  int name_is_dir, const char *type)
574 {
575         /* If a trailing slash is present to match only directories,
576          * then it is stripped out by add_rule().  So as a special
577          * case we add it back in here. */
578
579         if (verbose >= 2) {
580                 rprintf(FINFO, "[%s] %scluding %s %s because of pattern %s%s%s\n",
581                         who_am_i(),
582                         ent->match_flags & MATCHFLG_INCLUDE ? "in" : "ex",
583                         name_is_dir ? "directory" : "file", name, ent->pattern,
584                         ent->match_flags & MATCHFLG_DIRECTORY ? "/" : "", type);
585         }
586 }
587
588
589 /*
590  * Return -1 if file "name" is defined to be excluded by the specified
591  * exclude list, 1 if it is included, and 0 if it was not matched.
592  */
593 int check_filter(struct filter_list_struct *listp, char *name, int name_is_dir)
594 {
595         struct filter_struct *ent;
596
597         for (ent = listp->head; ent; ent = ent->next) {
598                 if (ent->match_flags & MATCHFLG_PERDIR_MERGE) {
599                         int rc = check_filter(ent->u.mergelist, name,
600                                               name_is_dir);
601                         if (rc)
602                                 return rc;
603                         continue;
604                 }
605                 if (ent->match_flags & MATCHFLG_CVS_IGNORE) {
606                         int rc = check_filter(&cvs_filter_list, name,
607                                               name_is_dir);
608                         if (rc)
609                                 return rc;
610                         continue;
611                 }
612                 if (rule_matches(name, ent, name_is_dir)) {
613                         report_filter_result(name, ent, name_is_dir,
614                                               listp->debug_type);
615                         return ent->match_flags & MATCHFLG_INCLUDE ? 1 : -1;
616                 }
617         }
618
619         return 0;
620 }
621
622 #define RULE_STRCMP(s,r) rule_strcmp((s), (r), sizeof (r) - 1)
623
624 static const uchar *rule_strcmp(const uchar *str, const char *rule, int rule_len)
625 {
626         if (strncmp((char*)str, rule, rule_len) != 0)
627                 return NULL;
628         if (isspace(str[rule_len]) || str[rule_len] == '_' || !str[rule_len])
629                 return str + rule_len - 1;
630         if (str[rule_len] == ',')
631                 return str + rule_len;
632         return NULL;
633 }
634
635 /* Get the next include/exclude arg from the string.  The token will not
636  * be '\0' terminated, so use the returned length to limit the string.
637  * Also, be sure to add this length to the returned pointer before passing
638  * it back to ask for the next token.  This routine parses the "!" (list-
639  * clearing) token and (depending on the mflags) the various prefixes.
640  * The *mflags_ptr value will be set on exit to the new MATCHFLG_* bits
641  * for the current token. */
642 static const char *parse_rule_tok(const char *p, uint32 mflags, int xflags,
643                                   unsigned int *len_ptr, uint32 *mflags_ptr)
644 {
645         const uchar *s = (const uchar *)p;
646         uint32 new_mflags;
647         unsigned int len;
648
649         if (mflags & MATCHFLG_WORD_SPLIT) {
650                 /* Skip over any initial whitespace. */
651                 while (isspace(*s))
652                         s++;
653                 /* Update to point to real start of rule. */
654                 p = (const char *)s;
655         }
656         if (!*s)
657                 return NULL;
658
659         new_mflags = mflags & MATCHFLGS_FROM_CONTAINER;
660
661         /* Figure out what kind of a filter rule "s" is pointing at.  Note
662          * that if MATCHFLG_NO_PREFIXES is set, the rule is either an include
663          * or an exclude based on the inheritance of the MATCHFLG_INCLUDE
664          * flag (above).  XFLG_OLD_PREFIXES indicates a compatibility mode
665          * for old include/exclude patterns where just "+ " and "- " are
666          * allowed as optional prefixes.  */
667         if (mflags & MATCHFLG_NO_PREFIXES) {
668                 if (*s == '!' && mflags & MATCHFLG_CVS_IGNORE)
669                         new_mflags |= MATCHFLG_CLEAR_LIST; /* Tentative! */
670         } else if (xflags & XFLG_OLD_PREFIXES) {
671                 if (*s == '-' && s[1] == ' ') {
672                         new_mflags &= ~MATCHFLG_INCLUDE;
673                         s += 2;
674                 } else if (*s == '+' && s[1] == ' ') {
675                         new_mflags |= MATCHFLG_INCLUDE;
676                         s += 2;
677                 } else if (*s == '!')
678                         new_mflags |= MATCHFLG_CLEAR_LIST; /* Tentative! */
679         } else {
680                 char ch = 0, *mods = "";
681                 switch (*s) {
682                 case 'c':
683                         if ((s = RULE_STRCMP(s, "clear")) != NULL)
684                                 ch = '!';
685                         break;
686                 case 'd':
687                         if ((s = RULE_STRCMP(s, "dir-merge")) != NULL)
688                                 ch = ':';
689                         break;
690                 case 'e':
691                         if ((s = RULE_STRCMP(s, "exclude")) != NULL)
692                                 ch = '-';
693                         break;
694                 case 'h':
695                         if ((s = RULE_STRCMP(s, "hide")) != NULL)
696                                 ch = 'H';
697                         break;
698                 case 'i':
699                         if ((s = RULE_STRCMP(s, "include")) != NULL)
700                                 ch = '+';
701                         break;
702                 case 'm':
703                         if ((s = RULE_STRCMP(s, "merge")) != NULL)
704                                 ch = '.';
705                         break;
706                 case 'p':
707                         if ((s = RULE_STRCMP(s, "protect")) != NULL)
708                                 ch = 'P';
709                         break;
710                 case 'r':
711                         if ((s = RULE_STRCMP(s, "risk")) != NULL)
712                                 ch = 'R';
713                         break;
714                 case 's':
715                         if ((s = RULE_STRCMP(s, "show")) != NULL)
716                                 ch = 'S';
717                         break;
718
719                 default:
720                         ch = *s;
721                         if (s[1] == ',')
722                                 s++;
723                         break;
724                 }
725                 switch (ch) {
726                 case ':':
727                         new_mflags |= MATCHFLG_PERDIR_MERGE
728                                     | MATCHFLG_FINISH_SETUP;
729                         /* FALL THROUGH */
730                 case '.':
731                         new_mflags |= MATCHFLG_MERGE_FILE;
732                         mods = MODIFIERS_INCL_EXCL MODIFIERS_MERGE_FILE;
733                         break;
734                 case '+':
735                         new_mflags |= MATCHFLG_INCLUDE;
736                         /* FALL THROUGH */
737                 case '-':
738                         mods = MODIFIERS_INCL_EXCL;
739                         break;
740                 case 'S':
741                         new_mflags |= MATCHFLG_INCLUDE;
742                         /* FALL THROUGH */
743                 case 'H':
744                         new_mflags |= MATCHFLG_SENDER_SIDE;
745                         mods = MODIFIERS_HIDE_PROTECT;
746                         break;
747                 case 'R':
748                         new_mflags |= MATCHFLG_INCLUDE;
749                         /* FALL THROUGH */
750                 case 'P':
751                         new_mflags |= MATCHFLG_RECEIVER_SIDE;
752                         mods = MODIFIERS_HIDE_PROTECT;
753                         break;
754                 case '!':
755                         new_mflags |= MATCHFLG_CLEAR_LIST;
756                         mods = NULL;
757                         break;
758                 default:
759                         rprintf(FERROR, "Unknown filter rule: `%s'\n", p);
760                         exit_cleanup(RERR_SYNTAX);
761                 }
762                 while (mods && *++s && *s != ' ' && *s != '_') {
763                         if (strchr(mods, *s) == NULL) {
764                                 if (mflags & MATCHFLG_WORD_SPLIT && isspace(*s)) {
765                                         s--;
766                                         break;
767                                 }
768                             invalid:
769                                 rprintf(FERROR,
770                                         "invalid modifier sequence at '%c' in filter rule: %s\n",
771                                         *s, p);
772                                 exit_cleanup(RERR_SYNTAX);
773                         }
774                         switch (*s) {
775                         case '-':
776                                 if (new_mflags & MATCHFLG_NO_PREFIXES)
777                                     goto invalid;
778                                 new_mflags |= MATCHFLG_NO_PREFIXES;
779                                 break;
780                         case '+':
781                                 if (new_mflags & MATCHFLG_NO_PREFIXES)
782                                     goto invalid;
783                                 new_mflags |= MATCHFLG_NO_PREFIXES
784                                             | MATCHFLG_INCLUDE;
785                                 break;
786                         case '/':
787                                 new_mflags |= MATCHFLG_ABS_PATH;
788                                 break;
789                         case '!':
790                                 new_mflags |= MATCHFLG_NEGATE;
791                                 break;
792                         case 'C':
793                                 if (new_mflags & MATCHFLG_NO_PREFIXES)
794                                     goto invalid;
795                                 new_mflags |= MATCHFLG_NO_PREFIXES
796                                             | MATCHFLG_WORD_SPLIT
797                                             | MATCHFLG_NO_INHERIT
798                                             | MATCHFLG_CVS_IGNORE;
799                                 break;
800                         case 'e':
801                                 new_mflags |= MATCHFLG_EXCLUDE_SELF;
802                                 break;
803                         case 'n':
804                                 new_mflags |= MATCHFLG_NO_INHERIT;
805                                 break;
806                         case 'r':
807                                 new_mflags |= MATCHFLG_RECEIVER_SIDE;
808                                 break;
809                         case 's':
810                                 new_mflags |= MATCHFLG_SENDER_SIDE;
811                                 break;
812                         case 'w':
813                                 new_mflags |= MATCHFLG_WORD_SPLIT;
814                                 break;
815                         }
816                 }
817                 if (*s)
818                         s++;
819         }
820
821         if (mflags & MATCHFLG_WORD_SPLIT) {
822                 const uchar *cp = s;
823                 /* Token ends at whitespace or the end of the string. */
824                 while (!isspace(*cp) && *cp != '\0')
825                         cp++;
826                 len = cp - s;
827         } else
828                 len = strlen((char*)s);
829
830         if (new_mflags & MATCHFLG_CLEAR_LIST) {
831                 if (!(xflags & XFLG_OLD_PREFIXES) && len) {
832                         rprintf(FERROR,
833                                 "'!' rule has trailing characters: %s\n", p);
834                         exit_cleanup(RERR_SYNTAX);
835                 }
836                 if (len > 1)
837                         new_mflags &= ~MATCHFLG_CLEAR_LIST;
838         } else if (!len && !(new_mflags & MATCHFLG_CVS_IGNORE)) {
839                 rprintf(FERROR, "unexpected end of filter rule: %s\n", p);
840                 exit_cleanup(RERR_SYNTAX);
841         }
842
843         *len_ptr = len;
844         *mflags_ptr = new_mflags;
845         return (const char *)s;
846 }
847
848
849 static char default_cvsignore[] = 
850         /* These default ignored items come from the CVS manual. */
851         "RCS SCCS CVS CVS.adm RCSLOG cvslog.* tags TAGS"
852         " .make.state .nse_depinfo *~ #* .#* ,* _$* *$"
853         " *.old *.bak *.BAK *.orig *.rej .del-*"
854         " *.a *.olb *.o *.obj *.so *.exe"
855         " *.Z *.elc *.ln core"
856         /* The rest we added to suit ourself. */
857         " .svn/";
858
859 static void get_cvs_excludes(uint32 mflags)
860 {
861         char *p, fname[MAXPATHLEN];
862         static int initialized = 0;
863
864         if (initialized)
865                 return;
866         initialized = 1;
867
868         parse_rule(&cvs_filter_list, default_cvsignore, mflags, 0);
869
870         p = module_id >= 0 && lp_use_chroot(module_id) ? "/" : getenv("HOME");
871         if (p && pathjoin(fname, MAXPATHLEN, p, ".cvsignore") < MAXPATHLEN)
872                 parse_filter_file(&cvs_filter_list, fname, mflags, 0);
873
874         parse_rule(&cvs_filter_list, getenv("CVSIGNORE"), mflags, 0);
875 }
876
877
878 void parse_rule(struct filter_list_struct *listp, const char *pattern,
879                 uint32 mflags, int xflags)
880 {
881         unsigned int pat_len;
882         uint32 new_mflags;
883         const char *cp, *p;
884
885         if (!pattern)
886                 return;
887
888         while (1) {
889                 /* Remember that the returned string is NOT '\0' terminated! */
890                 cp = parse_rule_tok(pattern, mflags, xflags,
891                                     &pat_len, &new_mflags);
892                 if (!cp)
893                         break;
894                 if (pat_len >= MAXPATHLEN) {
895                         rprintf(FERROR, "discarding over-long filter: %s\n",
896                                 cp);
897                         continue;
898                 }
899                 pattern = cp + pat_len;
900
901                 if (new_mflags & MATCHFLG_CLEAR_LIST) {
902                         if (verbose > 2) {
903                                 rprintf(FINFO,
904                                         "[%s] clearing filter list%s\n",
905                                         who_am_i(), listp->debug_type);
906                         }
907                         clear_filter_list(listp);
908                         continue;
909                 }
910
911                 if (new_mflags & MATCHFLG_MERGE_FILE) {
912                         unsigned int len;
913                         if (!pat_len) {
914                                 cp = ".cvsignore";
915                                 pat_len = 10;
916                         }
917                         len = pat_len;
918                         if (new_mflags & MATCHFLG_EXCLUDE_SELF) {
919                                 const char *name = strrchr(cp, '/');
920                                 if (name)
921                                         len -= ++name - cp;
922                                 else
923                                         name = cp;
924                                 add_rule(listp, name, len, 0, 0);
925                                 new_mflags &= ~MATCHFLG_EXCLUDE_SELF;
926                                 len = pat_len;
927                         }
928                         if (new_mflags & MATCHFLG_PERDIR_MERGE) {
929                                 if (parent_dirscan) {
930                                         if (!(p = parse_merge_name(cp, &len,
931                                                                 module_dirlen)))
932                                                 continue;
933                                         add_rule(listp, p, len, new_mflags, 0);
934                                         continue;
935                                 }
936                         } else {
937                                 if (!(p = parse_merge_name(cp, &len, 0)))
938                                         continue;
939                                 parse_filter_file(listp, p, new_mflags,
940                                                   XFLG_FATAL_ERRORS);
941                                 continue;
942                         }
943                 }
944
945                 add_rule(listp, cp, pat_len, new_mflags, xflags);
946
947                 if (new_mflags & MATCHFLG_CVS_IGNORE
948                     && !(new_mflags & MATCHFLG_MERGE_FILE))
949                         get_cvs_excludes(new_mflags);
950         }
951 }
952
953
954 void parse_filter_file(struct filter_list_struct *listp, const char *fname,
955                        uint32 mflags, int xflags)
956 {
957         FILE *fp;
958         char line[MAXPATHLEN+MAX_RULE_PREFIX+1]; /* +1 for trailing slash. */
959         char *eob = line + sizeof line - 1;
960         int word_split = mflags & MATCHFLG_WORD_SPLIT;
961
962         if (!fname || !*fname)
963                 return;
964
965         if (*fname != '-' || fname[1] || am_server) {
966                 if (server_filter_list.head) {
967                         strlcpy(line, fname, sizeof line);
968                         clean_fname(line, 1);
969                         if (check_filter(&server_filter_list, line, 0) < 0)
970                                 fp = NULL;
971                         else
972                                 fp = fopen(line, "rb");
973                 } else
974                         fp = fopen(fname, "rb");
975         } else
976                 fp = stdin;
977
978         if (verbose > 2) {
979                 rprintf(FINFO, "[%s] parse_filter_file(%s,%x,%x)%s\n",
980                         who_am_i(), safe_fname(fname), mflags, xflags,
981                         fp ? "" : " [not found]");
982         }
983
984         if (!fp) {
985                 if (xflags & XFLG_FATAL_ERRORS) {
986                         rsyserr(FERROR, errno,
987                                 "failed to open %sclude file %s",
988                                 mflags & MATCHFLG_INCLUDE ? "in" : "ex",
989                                 safe_fname(fname));
990                         exit_cleanup(RERR_FILEIO);
991                 }
992                 return;
993         }
994         dirbuf[dirbuf_len] = '\0';
995
996         while (1) {
997                 char *s = line;
998                 int ch, overflow = 0;
999                 while (1) {
1000                         if ((ch = getc(fp)) == EOF) {
1001                                 if (ferror(fp) && errno == EINTR)
1002                                         continue;
1003                                 break;
1004                         }
1005                         if (word_split && isspace(ch))
1006                                 break;
1007                         if (eol_nulls? !ch : (ch == '\n' || ch == '\r'))
1008                                 break;
1009                         if (s < eob)
1010                                 *s++ = ch;
1011                         else
1012                                 overflow = 1;
1013                 }
1014                 if (overflow) {
1015                         rprintf(FERROR, "discarding over-long filter: %s...\n", line);
1016                         s = line;
1017                 }
1018                 *s = '\0';
1019                 /* Skip an empty token and (when line parsing) comments. */
1020                 if (*line && (word_split || (*line != ';' && *line != '#')))
1021                         parse_rule(listp, line, mflags, xflags);
1022                 if (ch == EOF)
1023                         break;
1024         }
1025         fclose(fp);
1026 }
1027
1028 /* If the "for_xfer" flag is set, the prefix is made compatible with the
1029  * current protocol_version (if possible) or a NULL is returned (if not
1030  * possible). */
1031 char *get_rule_prefix(int match_flags, const char *pat, int for_xfer,
1032                       unsigned int *plen_ptr)
1033 {
1034         static char buf[MAX_RULE_PREFIX+1];
1035         char *op = buf;
1036         int legal_len = for_xfer && protocol_version < 29 ? 1 : MAX_RULE_PREFIX-1;
1037
1038         if (match_flags & MATCHFLG_PERDIR_MERGE) {
1039                 if (legal_len == 1)
1040                         return NULL;
1041                 *op++ = ':';
1042         } else if (match_flags & MATCHFLG_INCLUDE)
1043                 *op++ = '+';
1044         else if (legal_len != 1
1045             || ((*pat == '-' || *pat == '+') && pat[1] == ' '))
1046                 *op++ = '-';
1047         else
1048                 legal_len = 0;
1049
1050         if (match_flags & MATCHFLG_CVS_IGNORE)
1051                 *op++ = 'C';
1052         else {
1053                 if (match_flags & MATCHFLG_NO_INHERIT)
1054                         *op++ = 'n';
1055                 if (match_flags & MATCHFLG_WORD_SPLIT)
1056                         *op++ = 'w';
1057                 if (match_flags & MATCHFLG_NO_PREFIXES) {
1058                         if (match_flags & MATCHFLG_INCLUDE)
1059                                 *op++ = '+';
1060                         else
1061                                 *op++ = '-';
1062                 }
1063         }
1064         if (match_flags & MATCHFLG_EXCLUDE_SELF)
1065                 *op++ = 'e';
1066         if (match_flags & MATCHFLG_SENDER_SIDE
1067             && (!for_xfer || protocol_version >= 29))
1068                 *op++ = 's';
1069         if (match_flags & MATCHFLG_RECEIVER_SIDE
1070             && (!for_xfer || protocol_version >= 29
1071              || (delete_excluded && am_sender)))
1072                 *op++ = 'r';
1073         if (op - buf > legal_len)
1074                 return NULL;
1075         if (legal_len)
1076                 *op++ = ' ';
1077         *op = '\0';
1078         if (plen_ptr)
1079                 *plen_ptr = op - buf;
1080         return buf;
1081 }
1082
1083 static void send_rules(int f_out, struct filter_list_struct *flp)
1084 {
1085         struct filter_struct *ent, *prev = NULL;
1086
1087         for (ent = flp->head; ent; ent = ent->next) {
1088                 unsigned int len, plen, dlen;
1089                 int elide = 0;
1090                 char *p;
1091
1092                 if (ent->match_flags & MATCHFLG_SENDER_SIDE)
1093                         elide = am_sender ? 1 : -1;
1094                 if (ent->match_flags & MATCHFLG_RECEIVER_SIDE)
1095                         elide = elide ? 0 : am_sender ? -1 : 1;
1096                 else if (delete_excluded && !elide)
1097                         elide = am_sender ? 1 : -1;
1098                 if (elide < 0) {
1099                         if (prev)
1100                                 prev->next = ent->next;
1101                         else
1102                                 flp->head = ent->next;
1103                 } else
1104                         prev = ent;
1105                 if (elide > 0)
1106                         continue;
1107                 if (ent->match_flags & MATCHFLG_CVS_IGNORE
1108                     && !(ent->match_flags & MATCHFLG_MERGE_FILE)) {
1109                         int f = am_sender || protocol_version < 29 ? f_out : -1;
1110                         send_rules(f, &cvs_filter_list);
1111                         if (f >= 0)
1112                                 continue;
1113                 }
1114                 p = get_rule_prefix(ent->match_flags, ent->pattern, 1, &plen);
1115                 if (!p) {
1116                         rprintf(FERROR,
1117                                 "filter rules are too modern for remote rsync.\n");
1118                         exit_cleanup(RERR_SYNTAX);
1119                 }
1120                 if (f_out < 0)
1121                         continue;
1122                 len = strlen(ent->pattern);
1123                 dlen = ent->match_flags & MATCHFLG_DIRECTORY ? 1 : 0;
1124                 if (!(plen + len + dlen))
1125                         continue;
1126                 write_int(f_out, plen + len + dlen);
1127                 if (plen)
1128                         write_buf(f_out, p, plen);
1129                 write_buf(f_out, ent->pattern, len);
1130                 if (dlen)
1131                         write_byte(f_out, '/');
1132         }
1133         flp->tail = prev;
1134 }
1135
1136 /* This is only called by the client. */
1137 void send_filter_list(int f_out)
1138 {
1139         int receiver_wants_list = delete_mode
1140                 && (!delete_excluded || protocol_version >= 29);
1141
1142         if (local_server || (am_sender && !receiver_wants_list))
1143                 f_out = -1;
1144         if (cvs_exclude && am_sender) {
1145                 if (protocol_version >= 29)
1146                         parse_rule(&filter_list, ":C", 0, 0);
1147                 parse_rule(&filter_list, "-C", 0, 0);
1148         }
1149
1150         /* This is a complete hack - blame Rusty.  FIXME!
1151          * Remove this hack when older rsyncs (below 2.6.4) are gone. */
1152         if (list_only == 1 && !recurse)
1153                 parse_rule(&filter_list, "/*/*", MATCHFLG_NO_PREFIXES, 0);
1154
1155         send_rules(f_out, &filter_list);
1156
1157         if (f_out >= 0)
1158                 write_int(f_out, 0);
1159
1160         if (cvs_exclude) {
1161                 if (!am_sender || protocol_version < 29)
1162                         parse_rule(&filter_list, ":C", 0, 0);
1163                 if (!am_sender)
1164                         parse_rule(&filter_list, "-C", 0, 0);
1165         }
1166 }
1167
1168 /* This is only called by the server. */
1169 void recv_filter_list(int f_in)
1170 {
1171         char line[MAXPATHLEN+MAX_RULE_PREFIX+1]; /* +1 for trailing slash. */
1172         int xflags = protocol_version >= 29 ? 0 : XFLG_OLD_PREFIXES;
1173         int receiver_wants_list = delete_mode
1174                 && (!delete_excluded || protocol_version >= 29);
1175         unsigned int len;
1176
1177         if (!local_server && (am_sender || receiver_wants_list)) {
1178                 while ((len = read_int(f_in)) != 0) {
1179                         if (len >= sizeof line)
1180                                 overflow("recv_rules");
1181                         read_sbuf(f_in, line, len);
1182                         parse_rule(&filter_list, line, 0, xflags);
1183                 }
1184         }
1185
1186         if (cvs_exclude) {
1187                 if (local_server || am_sender || protocol_version < 29)
1188                         parse_rule(&filter_list, ":C", 0, 0);
1189                 if (local_server || am_sender)
1190                         parse_rule(&filter_list, "-C", 0, 0);
1191         }
1192
1193         if (local_server) /* filter out any rules that aren't for us. */
1194                 send_rules(-1, &filter_list);
1195 }