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