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