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