]> git.ipfire.org Git - thirdparty/bird.git/blob - filter/filter.c
Filter: Stacks moved to thread-local storage if available.
[thirdparty/bird.git] / filter / filter.c
1 /*
2 * Filters: utility functions
3 *
4 * Copyright 1998 Pavel Machek <pavel@ucw.cz>
5 *
6 * Can be freely distributed and used under the terms of the GNU GPL.
7 *
8 */
9
10 /**
11 * DOC: Filters
12 *
13 * You can find sources of the filter language in |filter/|
14 * directory. File |filter/config.Y| contains filter grammar and basically translates
15 * the source from user into a tree of &f_inst structures. These trees are
16 * later interpreted using code in |filter/filter.c|.
17 *
18 * A filter is represented by a tree of &f_inst structures, one structure per
19 * "instruction". Each &f_inst contains @code, @aux value which is
20 * usually the data type this instruction operates on and two generic
21 * arguments (@a[0], @a[1]). Some instructions contain pointer(s) to other
22 * instructions in their (@a[0], @a[1]) fields.
23 *
24 * Filters use a &f_val structure for their data. Each &f_val
25 * contains type and value (types are constants prefixed with %T_). Few
26 * of the types are special; %T_RETURN can be or-ed with a type to indicate
27 * that return from a function or from the whole filter should be
28 * forced. Important thing about &f_val's is that they may be copied
29 * with a simple |=|. That's fine for all currently defined types: strings
30 * are read-only (and therefore okay), paths are copied for each
31 * operation (okay too).
32 */
33
34 #undef LOCAL_DEBUG
35
36 #include "nest/bird.h"
37 #include "lib/lists.h"
38 #include "lib/resource.h"
39 #include "lib/socket.h"
40 #include "lib/string.h"
41 #include "lib/unaligned.h"
42 #include "lib/net.h"
43 #include "lib/ip.h"
44 #include "nest/route.h"
45 #include "nest/protocol.h"
46 #include "nest/iface.h"
47 #include "nest/attrs.h"
48 #include "conf/conf.h"
49 #include "filter/filter.h"
50 #include "filter/f-inst.h"
51 #include "filter/data.h"
52
53
54 /* Exception bits */
55 enum f_exception {
56 FE_RETURN = 0x1,
57 };
58
59
60 struct filter_stack {
61 /* Value stack for execution */
62 #define F_VAL_STACK_MAX 4096
63 uint vcnt; /* Current value stack size; 0 for empty */
64 uint ecnt; /* Current execute stack size; 0 for empty */
65
66 struct f_val vstk[F_VAL_STACK_MAX]; /* The stack itself */
67
68 /* Instruction stack for execution */
69 #define F_EXEC_STACK_MAX 4096
70 struct {
71 const struct f_line *line; /* The line that is being executed */
72 uint pos; /* Instruction index in the line */
73 uint ventry; /* Value stack depth on entry */
74 uint vbase; /* Where to index variable positions from */
75 enum f_exception emask; /* Exception mask */
76 } estk[F_EXEC_STACK_MAX];
77 };
78
79 /* Internal filter state, to be allocated on stack when executing filters */
80 struct filter_state {
81 /* Stacks needed for execution */
82 struct filter_stack *stack;
83
84 /* The route we are processing. This may be NULL to indicate no route available. */
85 struct rte **rte;
86
87 /* The old rta to be freed after filters are done. */
88 struct rta *old_rta;
89
90 /* Cached pointer to ea_list */
91 struct ea_list **eattrs;
92 struct linpool *pool;
93 struct buffer buf;
94 int flags;
95 };
96
97 #if HAVE_THREAD_LOCAL
98 _Thread_local static struct filter_state filter_state;
99 _Thread_local static struct filter_stack filter_stack;
100 #define FS_INIT(...) filter_state = (struct filter_state) { .stack = &filter_stack, __VA_ARGS__ }
101 #else
102 #define FS_INIT(...) struct filter_state filter_state = { .stack = alloca(sizeof(struct filter_stack)), __VA_ARGS__ };
103 #endif
104
105 void (*bt_assert_hook)(int result, const struct f_line_item *assert);
106
107 static inline void f_cache_eattrs(struct filter_state *fs)
108 {
109 fs->eattrs = &((*fs->rte)->attrs->eattrs);
110 }
111
112 static inline void f_rte_cow(struct filter_state *fs)
113 {
114 if (!((*fs->rte)->flags & REF_COW))
115 return;
116
117 *fs->rte = rte_cow(*fs->rte);
118 }
119
120 /*
121 * rta_cow - prepare rta for modification by filter
122 */
123 static void
124 f_rta_cow(struct filter_state *fs)
125 {
126 if (!rta_is_cached((*fs->rte)->attrs))
127 return;
128
129 /* Prepare to modify rte */
130 f_rte_cow(fs);
131
132 /* Store old rta to free it later, it stores reference from rte_cow() */
133 fs->old_rta = (*fs->rte)->attrs;
134
135 /*
136 * Get shallow copy of rta. Fields eattrs and nexthops of rta are shared
137 * with fs->old_rta (they will be copied when the cached rta will be obtained
138 * at the end of f_run()), also the lock of hostentry is inherited (we
139 * suppose hostentry is not changed by filters).
140 */
141 (*fs->rte)->attrs = rta_do_cow((*fs->rte)->attrs, fs->pool);
142
143 /* Re-cache the ea_list */
144 f_cache_eattrs(fs);
145 }
146
147 static char *
148 val_format_str(struct filter_state *fs, struct f_val *v) {
149 buffer b;
150 LOG_BUFFER_INIT(b);
151 val_format(v, &b);
152 return lp_strdup(fs->pool, b.start);
153 }
154
155 static struct tbf rl_runtime_err = TBF_DEFAULT_LOG_LIMITS;
156
157 /**
158 * interpret
159 * @fs: filter state
160 * @what: filter to interpret
161 *
162 * Interpret given tree of filter instructions. This is core function
163 * of filter system and does all the hard work.
164 *
165 * Each instruction has 4 fields: code (which is instruction code),
166 * aux (which is extension to instruction code, typically type),
167 * arg1 and arg2 - arguments. Depending on instruction, arguments
168 * are either integers, or pointers to instruction trees. Common
169 * instructions like +, that have two expressions as arguments use
170 * TWOARGS macro to get both of them evaluated.
171 */
172 static enum filter_return
173 interpret(struct filter_state *fs, const struct f_line *line, struct f_val *val)
174 {
175 /* No arguments allowed */
176 ASSERT(line->args == 0);
177
178 /* Initialize the filter stack */
179 struct filter_stack *fstk = fs->stack;
180
181 fstk->vcnt = line->vars;
182 memset(fstk->vstk, 0, sizeof(struct f_val) * line->vars);
183
184 /* The same as with the value stack. Not resetting the stack for performance reasons. */
185 fstk->ecnt = 1;
186 fstk->estk[0].line = line;
187 fstk->estk[0].pos = 0;
188
189 #define curline fstk->estk[fstk->ecnt-1]
190
191 #if DEBUGGING
192 debug("Interpreting line.");
193 f_dump_line(line, 1);
194 #endif
195
196 while (fstk->ecnt > 0) {
197 while (curline.pos < curline.line->len) {
198 const struct f_line_item *what = &(curline.line->items[curline.pos++]);
199
200 switch (what->fi_code) {
201 #define res fstk->vstk[fstk->vcnt]
202 #define v1 fstk->vstk[fstk->vcnt]
203 #define v2 fstk->vstk[fstk->vcnt + 1]
204 #define v3 fstk->vstk[fstk->vcnt + 2]
205
206 #define runtime(fmt, ...) do { \
207 if (!(fs->flags & FF_SILENT)) \
208 log_rl(&rl_runtime_err, L_ERR "filters, line %d: " fmt, what->lineno, ##__VA_ARGS__); \
209 return F_ERROR; \
210 } while(0)
211
212 #define ACCESS_RTE do { if (!fs->rte) runtime("No route to access"); } while (0)
213 #define ACCESS_EATTRS do { if (!fs->eattrs) f_cache_eattrs(fs); } while (0)
214
215 #include "filter/inst-interpret.c"
216 #undef res
217 #undef v1
218 #undef v2
219 #undef v3
220 #undef runtime
221 #undef ACCESS_RTE
222 #undef ACCESS_EATTRS
223 }
224 }
225
226 /* End of current line. Drop local variables before exiting. */
227 fstk->vcnt -= curline.line->vars;
228 fstk->vcnt -= curline.line->args;
229 fstk->ecnt--;
230 }
231
232 if (fstk->vcnt == 0) {
233 if (val) {
234 log_rl(&rl_runtime_err, L_ERR "filters: No value left on stack");
235 return F_ERROR;
236 }
237 return F_NOP;
238 }
239
240 if (val && (fstk->vcnt == 1)) {
241 *val = fstk->vstk[0];
242 return F_NOP;
243 }
244
245 log_rl(&rl_runtime_err, L_ERR "Too many items left on stack: %u", fstk->vcnt);
246 return F_ERROR;
247 }
248
249
250 /**
251 * f_run - run a filter for a route
252 * @filter: filter to run
253 * @rte: route being filtered, may be modified
254 * @tmp_pool: all filter allocations go from this pool
255 * @flags: flags
256 *
257 * If filter needs to modify the route, there are several
258 * posibilities. @rte might be read-only (with REF_COW flag), in that
259 * case rw copy is obtained by rte_cow() and @rte is replaced. If
260 * @rte is originally rw, it may be directly modified (and it is never
261 * copied).
262 *
263 * The returned rte may reuse the (possibly cached, cloned) rta, or
264 * (if rta was modified) contains a modified uncached rta, which
265 * uses parts allocated from @tmp_pool and parts shared from original
266 * rta. There is one exception - if @rte is rw but contains a cached
267 * rta and that is modified, rta in returned rte is also cached.
268 *
269 * Ownership of cached rtas is consistent with rte, i.e.
270 * if a new rte is returned, it has its own clone of cached rta
271 * (and cached rta of read-only source rte is intact), if rte is
272 * modified in place, old cached rta is possibly freed.
273 */
274 enum filter_return
275 f_run(const struct filter *filter, struct rte **rte, struct linpool *tmp_pool, int flags)
276 {
277 if (filter == FILTER_ACCEPT)
278 return F_ACCEPT;
279
280 if (filter == FILTER_REJECT)
281 return F_REJECT;
282
283 int rte_cow = ((*rte)->flags & REF_COW);
284 DBG( "Running filter `%s'...", filter->name );
285
286 /* Initialize the filter state */
287 FS_INIT(
288 .rte = rte,
289 .pool = tmp_pool,
290 .flags = flags,
291 );
292
293 LOG_BUFFER_INIT(filter_state.buf);
294
295 /* Run the interpreter itself */
296 enum filter_return fret = interpret(&filter_state, filter->root, NULL);
297
298 if (filter_state.old_rta) {
299 /*
300 * Cached rta was modified and filter_state->rte contains now an uncached one,
301 * sharing some part with the cached one. The cached rta should
302 * be freed (if rte was originally COW, filter_state->old_rta is a clone
303 * obtained during rte_cow()).
304 *
305 * This also implements the exception mentioned in f_run()
306 * description. The reason for this is that rta reuses parts of
307 * filter_state->old_rta, and these may be freed during rta_free(filter_state->old_rta).
308 * This is not the problem if rte was COW, because original rte
309 * also holds the same rta.
310 */
311 if (!rte_cow) {
312 /* Cache the new attrs */
313 (*filter_state.rte)->attrs = rta_lookup((*filter_state.rte)->attrs);
314
315 /* Drop cached ea_list pointer */
316 filter_state.eattrs = NULL;
317 }
318
319 /* Uncache the old attrs and drop the pointer as it is invalid now. */
320 rta_free(filter_state.old_rta);
321 filter_state.old_rta = NULL;
322 }
323
324 /* Process the filter output, log it and return */
325 if (fret < F_ACCEPT) {
326 if (!(filter_state.flags & FF_SILENT))
327 log_rl(&rl_runtime_err, L_ERR "Filter %s did not return accept nor reject. Make up your mind", filter_name(filter));
328 return F_ERROR;
329 }
330 DBG( "done (%u)\n", res.val.i );
331 return fret;
332 }
333
334 /**
335 * f_eval_rte – run a filter line for an uncached route
336 * @expr: filter line to run
337 * @rte: route being filtered, may be modified
338 * @tmp_pool: all filter allocations go from this pool
339 *
340 * This specific filter entry point runs the given filter line
341 * (which must not have any arguments) on the given route.
342 *
343 * The route MUST NOT have REF_COW set and its attributes MUST NOT
344 * be cached by rta_lookup().
345 */
346
347 enum filter_return
348 f_eval_rte(const struct f_line *expr, struct rte **rte, struct linpool *tmp_pool)
349 {
350 FS_INIT(
351 .rte = rte,
352 .pool = tmp_pool,
353 );
354
355 LOG_BUFFER_INIT(filter_state.buf);
356
357 ASSERT(!((*rte)->flags & REF_COW));
358 ASSERT(!rta_is_cached((*rte)->attrs));
359
360 return interpret(&filter_state, expr, NULL);
361 }
362
363 /*
364 * f_eval – get a value of a term
365 * @expr: filter line containing the term
366 * @tmp_pool: long data may get allocated from this pool
367 * @pres: here the output will be stored
368 */
369 enum filter_return
370 f_eval(const struct f_line *expr, struct linpool *tmp_pool, struct f_val *pres)
371 {
372 FS_INIT(
373 .pool = tmp_pool,
374 );
375
376 LOG_BUFFER_INIT(filter_state.buf);
377
378 enum filter_return fret = interpret(&filter_state, expr, pres);
379 return fret;
380 }
381
382 /*
383 * f_eval_int – get an integer value of a term
384 * Called internally from the config parser, uses its internal memory pool
385 * for allocations. Do not call in other cases.
386 */
387 uint
388 f_eval_int(const struct f_line *expr)
389 {
390 /* Called independently in parse-time to eval expressions */
391 FS_INIT(
392 .pool = cfg_mem,
393 );
394
395 struct f_val val;
396
397 LOG_BUFFER_INIT(filter_state.buf);
398
399 if (interpret(&filter_state, expr, &val) > F_RETURN)
400 cf_error("Runtime error while evaluating expression");
401
402 if (val.type != T_INT)
403 cf_error("Integer expression expected");
404
405 return val.val.i;
406 }
407
408 /*
409 * f_eval_buf – get a value of a term and print it to the supplied buffer
410 */
411 enum filter_return
412 f_eval_buf(const struct f_line *expr, struct linpool *tmp_pool, buffer *buf)
413 {
414 struct f_val val;
415 enum filter_return fret = f_eval(expr, tmp_pool, &val);
416 if (fret > F_RETURN)
417 val_format(&val, buf);
418 return fret;
419 }
420
421 /**
422 * filter_same - compare two filters
423 * @new: first filter to be compared
424 * @old: second filter to be compared
425 *
426 * Returns 1 in case filters are same, otherwise 0. If there are
427 * underlying bugs, it will rather say 0 on same filters than say
428 * 1 on different.
429 */
430 int
431 filter_same(const struct filter *new, const struct filter *old)
432 {
433 if (old == new) /* Handle FILTER_ACCEPT and FILTER_REJECT */
434 return 1;
435 if (old == FILTER_ACCEPT || old == FILTER_REJECT ||
436 new == FILTER_ACCEPT || new == FILTER_REJECT)
437 return 0;
438
439 if ((!old->sym) && (!new->sym))
440 return f_same(new->root, old->root);
441
442 if ((!old->sym) || (!new->sym))
443 return 0;
444
445 if (strcmp(old->sym->name, new->sym->name))
446 return 0;
447
448 return new->sym->flags & SYM_FLAG_SAME;
449 }
450
451 /**
452 * filter_commit - do filter comparisons on all the named functions and filters
453 */
454 void
455 filter_commit(const struct config *new, const struct config *old)
456 {
457 if (!old)
458 return;
459
460 struct symbol *sym, *osym;
461 WALK_LIST(sym, new->symbols)
462 switch (sym->class) {
463 case SYM_FUNCTION:
464 if ((osym = cf_find_symbol(old, sym->name)) &&
465 (osym->class == SYM_FUNCTION) &&
466 f_same(sym->function, osym->function))
467 sym->flags |= SYM_FLAG_SAME;
468 else
469 sym->flags &= ~SYM_FLAG_SAME;
470 break;
471
472 case SYM_FILTER:
473 if ((osym = cf_find_symbol(old, sym->name)) &&
474 (osym->class == SYM_FILTER) &&
475 f_same(sym->filter->root, osym->filter->root))
476 sym->flags |= SYM_FLAG_SAME;
477 else
478 sym->flags &= ~SYM_FLAG_SAME;
479 break;
480 }
481 }