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