root/src/noit_filters.c

Revision cad43821ea8f313cdf28f0ac7531ab25a01a634f, 15.5 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 4 years ago)

fixes #247

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  *       notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  *       copyright notice, this list of conditions and the following
13  *       disclaimer in the documentation and/or other materials provided
14  *       with the distribution.
15  *     * Neither the name OmniTI Computer Consulting, Inc. nor the names
16  *       of its contributors may be used to endorse or promote products
17  *       derived from this software without specific prior written
18  *       permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "noit_defines.h"
34
35 #include "utils/noit_hash.h"
36 #include "utils/noit_atomic.h"
37 #include "noit_conf.h"
38 #include "noit_check.h"
39 #include "noit_conf_checks.h"
40 #include "noit_filters.h"
41
42 #include <pcre.h>
43 #include <assert.h>
44 #include <libxml/tree.h>
45
46 static noit_hash_table *filtersets = NULL;
47 static pthread_mutex_t filterset_lock;
48 #define LOCKFS() pthread_mutex_lock(&filterset_lock)
49 #define UNLOCKFS() pthread_mutex_unlock(&filterset_lock)
50
51 typedef enum { NOIT_FILTER_ACCEPT, NOIT_FILTER_DENY } noit_ruletype_t;
52 typedef struct _filterrule {
53   noit_ruletype_t type;
54   pcre *target;
55   pcre_extra *target_e;
56   pcre *module;
57   pcre_extra *module_e;
58   pcre *name;
59   pcre_extra *name_e;
60   pcre *metric;
61   pcre_extra *metric_e;
62   struct _filterrule *next;
63 } filterrule_t;
64
65 typedef struct {
66   noit_atomic32_t ref_cnt;
67   char *name;
68   filterrule_t *rules;
69 } filterset_t;
70
71 #define FRF(r,a) do { \
72   if(r->a) pcre_free(r->a); \
73   if(r->a##_e) pcre_free(r->a##_e); \
74 } while(0)
75
76 static void
77 filterrule_free(void *vp) {
78   filterrule_t *r = vp;
79   FRF(r,target);
80   FRF(r,module);
81   FRF(r,name);
82   FRF(r,metric);
83   free(r);
84 }
85 static void
86 filterset_free(void *vp) {
87   filterset_t *fs = vp;
88   filterrule_t *r;
89   if(noit_atomic_dec32(&fs->ref_cnt) != 0) return;
90   noitL(noit_error, "Freeing filterset [%d]: %s\n", fs->ref_cnt, fs->name);
91   while(fs->rules) {
92     r = fs->rules->next;
93     filterrule_free(fs->rules);
94     fs->rules = r;
95   }
96   if(fs->name) free(fs->name);
97   free(fs);
98 }
99 void
100 noit_filter_compile_add(noit_conf_section_t setinfo) {
101   noit_conf_section_t *rules;
102   int j, fcnt;
103   char filterset_name[256];
104   filterset_t *set;
105   if(!noit_conf_get_stringbuf(setinfo, "@name",
106                               filterset_name, sizeof(filterset_name))) {
107     noitL(noit_error,
108           "filterset with no name, skipping as it cannot be referenced.\n");
109     return;
110   }
111   set = calloc(1, sizeof(*set));
112   set->ref_cnt = 1;
113   set->name = strdup(filterset_name);
114
115   rules = noit_conf_get_sections(setinfo, "rule", &fcnt);
116   /* Here we will work through the list backwards pushing the rules on
117    * the front of the list.  That way we can simply walk them in order
118    * for the application process.
119    */
120   noitL(noit_debug, "Compiling filterset '%s'\n", set->name);
121   for(j=fcnt-1; j>=0; j--) {
122     filterrule_t *rule;
123     char buffer[256];
124     if(!noit_conf_get_stringbuf(rules[j], "@type", buffer, sizeof(buffer)) ||
125        (strcmp(buffer, "accept") && strcmp(buffer, "deny"))) {
126       noitL(noit_error, "rule must have type 'accept' or 'deny'\n");
127       continue;
128     }
129     noitL(noit_debug, "Prepending %s into %s\n", buffer, set->name);
130     rule = calloc(1, sizeof(*rule));
131     rule->type = (!strcmp(buffer, "accept")) ?
132                    NOIT_FILTER_ACCEPT : NOIT_FILTER_DENY;
133
134     /* Compile our rules */
135 #define RULE_COMPILE(rname) do { \
136   if(noit_conf_get_stringbuf(rules[j], "@" #rname, buffer, sizeof(buffer))) { \
137     const char *error; \
138     int erroffset; \
139     rule->rname = pcre_compile(buffer, 0, &error, &erroffset, NULL); \
140     if(!rule->rname) { \
141       noitL(noit_error, "set '%s' rule '%s: %s' compile failed: %s\n", \
142             set->name, #rname, buffer, error ? error : "???"); \
143     } \
144     else { \
145       rule->rname##_e = pcre_study(rule->rname, 0, &error); \
146     } \
147   } \
148 } while(0)
149
150     RULE_COMPILE(target);
151     RULE_COMPILE(module);
152     RULE_COMPILE(name);
153     RULE_COMPILE(metric);
154     rule->next = set->rules;
155     set->rules = rule;
156   }
157   free(rules);
158   LOCKFS();
159   noit_hash_replace(filtersets, set->name, strlen(set->name), (void *)set,
160                     NULL, filterset_free);
161   UNLOCKFS();
162 }
163 int
164 noit_filter_exists(const char *name) {
165   int removed;
166   void *v;
167   LOCKFS();
168   removed = noit_hash_retrieve(filtersets, name, strlen(name), &v);
169   UNLOCKFS();
170   return removed;
171 }
172 int
173 noit_filter_remove(noit_conf_section_t vnode) {
174   int removed;
175   xmlNodePtr node = vnode;
176   char *name = (char *)node->name;
177   LOCKFS();
178   removed = noit_hash_delete(filtersets, name, strlen(name),
179                              NULL, filterset_free);
180   UNLOCKFS();
181   return removed;
182 }
183 void
184 noit_filters_from_conf() {
185   noit_conf_section_t *sets;
186   int i, cnt;
187
188   sets = noit_conf_get_sections(NULL, "/noit/filtersets//filterset", &cnt);
189   for(i=0; i<cnt; i++) {
190     noit_filter_compile_add(sets[i]);
191   }
192   free(sets);
193 }
194
195 void
196 noit_refresh_filtersets(noit_console_closure_t ncct,
197                         noit_conf_t_userdata_t *info) {
198   noit_filters_from_conf();
199   nc_printf(ncct, "Reloaded %d filtersets.\n",
200             filtersets ? filtersets->size : 0);
201 }
202
203 static noit_boolean
204 noit_apply_filterrule(pcre *p, pcre_extra *pe, const char *subj) {
205   int rc, ovector[30];
206   if(!p) return noit_true;
207   rc = pcre_exec(p, pe, subj, strlen(subj), 0, 0, ovector, 30);
208   if(rc >= 0) return noit_true;
209   return noit_false;
210 }
211 noit_boolean
212 noit_apply_filterset(const char *filterset,
213                      noit_check_t *check,
214                      metric_t *metric) {
215   /* We pass in filterset here just in case someone wants to apply
216    * a filterset other than check->filterset.. You never know.
217    */
218   void *vfs;
219   if(!filterset) return noit_true;   /* No filter */
220   if(!filtersets) return noit_false; /* Couldn't possibly match */
221
222   LOCKFS();
223   if(noit_hash_retrieve(filtersets, filterset, strlen(filterset), &vfs)) {
224     filterset_t *fs = (filterset_t *)vfs;
225     filterrule_t *r;
226     noit_atomic_inc32(&fs->ref_cnt);
227     UNLOCKFS();
228 #define MATCHES(rname, value) noit_apply_filterrule(r->rname, r->rname##_e, value)
229     for(r = fs->rules; r; r = r->next) {
230       if(MATCHES(target, check->target) &&
231          MATCHES(module, check->module) &&
232          MATCHES(name, check->name) &&
233          MATCHES(metric, metric->metric_name))
234         return (r->type == NOIT_FILTER_ACCEPT) ? noit_true : noit_false;
235     }
236     filterset_free(fs);
237   }
238   UNLOCKFS();
239   return noit_false;
240 }
241
242 static char *
243 conf_t_filterset_prompt(EditLine *el) {
244   noit_console_closure_t ncct;
245   noit_conf_t_userdata_t *info;
246   static char *tl = "noit(conf)# ";
247   static char *pfmt = "noit(conf:filterset:%.*s%s)# ";
248   int max_space, namelen;
249   el_get(el, EL_USERDATA, (void *)&ncct);
250   if(!ncct) return tl;
251   info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
252   if(!info) return tl;
253   max_space = sizeof(info->prompt) - strlen(pfmt) + 6 - 1;
254   namelen = strlen(info->filter_name);
255   if(namelen > max_space)
256     snprintf(info->prompt, sizeof(info->prompt), pfmt,
257              max_space - 3, info->filter_name, "...");
258   else
259     snprintf(info->prompt, sizeof(info->prompt), pfmt,
260              namelen, info->filter_name, "");
261   return info->prompt;
262 }
263
264 static int
265 noit_console_filter_show(noit_console_closure_t ncct,
266                          int argc, char **argv,
267                          noit_console_state_t *state,
268                          void *closure) {
269   noit_conf_t_userdata_t *info;
270   char xpath[1024];
271   xmlNodePtr fsnode;
272   noit_conf_section_t *rules;
273   int i, rulecnt;
274
275   info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
276   snprintf(xpath, sizeof(xpath), "/%s",
277            info->path);
278   fsnode = noit_conf_get_section(NULL, xpath);
279   if(!fsnode) {
280     nc_printf(ncct, "internal error\n");
281     return -1;
282   }
283   rules = noit_conf_get_sections(fsnode, "rule", &rulecnt);
284   for(i=0; i<rulecnt; i++) {
285     char val[256];
286     val[0] = '\0';
287     noit_conf_get_stringbuf(rules[i], "@type", val, sizeof(val));
288     nc_printf(ncct, "Rule %d [%s]:\n", i+1, val);
289 #define DUMP_ATTR(a) do { \
290   if(noit_conf_get_stringbuf(rules[i], "@" #a, val, sizeof(val))) { \
291     nc_printf(ncct, "\t%s: /%s/\n", #a, val); \
292   } \
293 } while(0)
294     DUMP_ATTR(target);
295     DUMP_ATTR(module);
296     DUMP_ATTR(name);
297     DUMP_ATTR(metric);
298   }
299   if(rules) free(rules);
300   return 0;
301 }
302 static int
303 noit_console_rule_configure(noit_console_closure_t ncct,
304                             int argc, char **argv,
305                             noit_console_state_t *state,
306                             void *closure) {
307   xmlNodePtr fsnode = NULL;
308   noit_conf_t_userdata_t *info;
309   char xpath[1024];
310
311   info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
312   snprintf(xpath, sizeof(xpath), "/%s",
313            info->path);
314   fsnode = noit_conf_get_section(NULL, xpath);
315   if(!fsnode) {
316     nc_printf(ncct, "internal error");
317     return -1;
318   }
319   if(closure) {
320     int rulenum;
321     xmlNodePtr byebye;
322     /* removing a rule */
323     if(argc != 1) {
324       nc_printf(ncct, "requires one argument\n");
325       return -1;
326     }
327     rulenum = atoi(argv[0]);
328     snprintf(xpath, sizeof(xpath), "rule[%d]", rulenum);
329     byebye = noit_conf_get_section(fsnode, xpath);
330     if(!byebye) {
331       nc_printf(ncct, "cannot find rule\n");
332       return -1;
333     }
334     xmlUnlinkNode(byebye);
335     xmlFreeNode(byebye);
336     nc_printf(ncct, "removed\n");
337   }
338   else {
339     xmlNodePtr (*add_func)(xmlNodePtr, xmlNodePtr);
340     xmlNodePtr add_arg, new_rule;
341     int i, needs_type = 1;
342     if(argc < 1 || argc % 2) {
343       nc_printf(ncct, "even number of arguments required\n");
344       return -1;
345     }
346     if(!strcmp(argv[0], "before") || !strcmp(argv[0], "after")) {
347       int rulenum = atoi(argv[1]);
348       snprintf(xpath, sizeof(xpath), "rule[%d]", rulenum);
349       add_arg = noit_conf_get_section(fsnode, xpath);
350       if(!add_arg) {
351         nc_printf(ncct, "%s rule not found\n", xpath);
352         return -1;
353       }
354       if(*argv[0] == 'b') add_func = xmlAddPrevSibling;
355       else add_func = xmlAddNextSibling;
356       argc -= 2;
357       argv += 2;
358     }
359     else {
360       add_func = xmlAddChild;
361       add_arg = fsnode;
362     }
363     for(i=0;i<argc;i+=2) {
364       if(!strcmp(argv[i], "type")) needs_type = 0;
365       else if(strcmp(argv[i], "target") && strcmp(argv[i], "module") &&
366               strcmp(argv[i], "name") && strcmp(argv[i], "metric")) {
367         nc_printf(ncct, "unknown attribute '%s'\n", argv[i]);
368         return -1;
369       }
370     }
371     if(needs_type) {
372       nc_printf(ncct, "type <allow|deny> is required\n");
373       return -1;
374     }
375     new_rule = xmlNewNode(NULL, (xmlChar *)"rule");
376     for(i=0;i<argc;i+=2)
377       xmlSetProp(new_rule, (xmlChar *)argv[i], (xmlChar *)argv[i+1]);
378     add_func(add_arg, new_rule);
379     noit_filter_compile_add((noit_conf_section_t *)fsnode);
380   }
381   return 0;
382 }
383 static int
384 noit_console_filter_configure(noit_console_closure_t ncct,
385                               int argc, char **argv,
386                               noit_console_state_t *state,
387                               void *closure) {
388   xmlNodePtr parent, fsnode = NULL;
389   int rv = -1;
390   noit_conf_t_userdata_t *info;
391   char xpath[1024];
392
393   info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
394   if(!info ||
395      (strncmp(info->path, "/filtersets/", strlen("/filtersets/")) &&
396       strcmp(info->path, "/filtersets"))) {
397     nc_printf(ncct, "filterset only allows inside /filtersets (not %s)\n",
398               info->path);
399     goto cleanup;
400   }
401   if(argc != 1) {
402     nc_printf(ncct, "filterset requires one argument\n");
403     goto cleanup;
404   }
405   snprintf(xpath, sizeof(xpath), "/%s", info->path);
406   parent = noit_conf_get_section(NULL, xpath);
407   if(!parent) {
408     nc_printf(ncct, "internal error, can't final current working path\n");
409     goto cleanup;
410   }
411   snprintf(xpath, sizeof(xpath), "filterset[@name=\"%s\"]", argv[0]);
412   fsnode = noit_conf_get_section(parent, xpath);
413   if(closure) {
414     int removed;
415     removed = noit_filter_remove(fsnode);
416     nc_printf(ncct, "%sremoved filterset '%s'\n",
417               removed ? "" : "failed to ", argv[0]);
418     if(removed) {
419       xmlUnlinkNode(fsnode);
420       xmlFreeNode(fsnode);
421     }
422     rv = !removed;
423     goto cleanup;
424   }
425   if(!fsnode) {
426     void *vfs;
427     nc_printf(ncct, "Cannot find filterset '%s'\n", argv[0]);
428     LOCKFS();
429     if(noit_hash_retrieve(filtersets, argv[0], strlen(argv[0]), &vfs)) {
430       UNLOCKFS();
431       nc_printf(ncct, "filter of the same name already exists\n");
432       goto cleanup;
433     }
434     UNLOCKFS();
435     /* Fine the parent path */
436     fsnode = xmlNewNode(NULL, (xmlChar *)"filterset");
437     xmlSetProp(fsnode, (xmlChar *)"name", (xmlChar *)argv[0]);
438     xmlAddChild(parent, fsnode);
439     nc_printf(ncct, "created new filterset\n");
440   }
441
442   if(info) {
443     if(info->path) free(info->path);
444     info->path = strdup((char *)xmlGetNodePath(fsnode) + strlen("/noit"));
445     strlcpy(info->filter_name, argv[0], sizeof(info->filter_name));
446     if(state) {
447       noit_console_state_push_state(ncct, state);
448       noit_console_state_init(ncct);
449     }
450   }
451  cleanup:
452   return rv;
453 }
454
455 static void
456 register_console_filter_commands() {
457   noit_console_state_t *tl, *filterset_state, *nostate;
458   cmd_info_t *confcmd, *conf_t_cmd, *no_cmd;
459
460   tl = noit_console_state_initial();
461   confcmd = noit_console_state_get_cmd(tl, "configure");
462   assert(confcmd && confcmd->dstate);
463
464   conf_t_cmd = noit_console_state_get_cmd(confcmd->dstate, "terminal");
465   assert(conf_t_cmd && conf_t_cmd->dstate);
466
467   nostate = noit_console_state_alloc();
468   noit_console_state_add_cmd(nostate,
469     NCSCMD("rule", noit_console_rule_configure, NULL, NULL, (void *)1));
470
471   filterset_state = noit_console_state_alloc();
472   noit_console_state_add_cmd(filterset_state,
473     NCSCMD("exit", noit_console_config_cd, NULL, NULL, ".."));
474   noit_console_state_add_cmd(filterset_state,
475     NCSCMD("status", noit_console_filter_show, NULL, NULL, NULL));
476   noit_console_state_add_cmd(filterset_state,
477     NCSCMD("rule", noit_console_rule_configure, NULL, NULL, NULL));
478   noit_console_state_add_cmd(filterset_state,
479     NCSCMD("no", noit_console_state_delegate, noit_console_opt_delegate,
480            nostate, NULL));
481
482   filterset_state->console_prompt_function = conf_t_filterset_prompt;
483
484   noit_console_state_add_cmd(conf_t_cmd->dstate,
485     NCSCMD("filterset", noit_console_filter_configure,
486            NULL, filterset_state, NULL));
487
488   no_cmd = noit_console_state_get_cmd(conf_t_cmd->dstate, "no");
489   assert(no_cmd && no_cmd->dstate);
490   noit_console_state_add_cmd(no_cmd->dstate,
491     NCSCMD("filterset", noit_console_filter_configure, NULL, NULL, (void *)1));
492 }
493
494 void
495 noit_filters_init() {
496   pthread_mutex_init(&filterset_lock, NULL);
497   filtersets = calloc(1, sizeof(noit_hash_table));
498   register_console_filter_commands();
499   noit_filters_from_conf();
500 }
Note: See TracBrowser for help on using the browser.