root/src/noit_check_rest.c

Revision 914f04715e543bf76101c324e06a062e7a10b3ba, 16.6 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 5 years ago)

adding checks, needs a lot of input validation, refs #171

  • 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 #include <assert.h>
35 #include <errno.h>
36 #include <libxml/parser.h>
37 #include <libxml/tree.h>
38 #include <libxml/xpath.h>
39 #include "noit_listener.h"
40 #include "noit_http.h"
41 #include "noit_rest.h"
42 #include "noit_check.h"
43 #include "noit_check_tools.h"
44 #include "noit_conf.h"
45 #include "noit_conf_private.h"
46
47 #define UUID_REGEX "[0-9a-fA-F]{4}(?:[0-9a-fA-F]{4}-){4}[0-9a-fA-F]{12}"
48
49 struct rest_xml_payload {
50   char *buffer;
51   int len;
52   int allocd;
53   int complete;
54 };
55
56 static int
57 rest_show_check(noit_http_rest_closure_t *restc,
58                 int npats, char **pats) {
59   noit_http_session_ctx *ctx = restc->http_ctx;
60   xmlXPathObjectPtr pobj = NULL;
61   xmlXPathContextPtr xpath_ctxt = NULL;
62   xmlDocPtr doc = NULL;
63   xmlNodePtr node, root, attr, config, state, tmp, anode, metrics;
64   uuid_t checkid;
65   noit_check_t *check;
66   char xpath[1024], *uuid_conf, *module, *value;
67   int rv, cnt;
68   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
69   const char *k;
70   int klen;
71   void *data;
72   noit_hash_table *configh;
73
74   if(npats != 2) goto error;
75
76   rv = noit_check_xpath(xpath, sizeof(xpath), pats[0], pats[1]);
77   if(rv == 0) goto not_found;
78   if(rv < 0) goto error;
79
80   noit_conf_xml_xpath(NULL, &xpath_ctxt);
81   pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
82   if(!pobj || pobj->type != XPATH_NODESET ||
83      xmlXPathNodeSetIsEmpty(pobj->nodesetval)) goto not_found;
84   cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
85   if(cnt != 1) goto error;
86
87   node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
88   uuid_conf = (char *)xmlGetProp(node, (xmlChar *)"uuid");
89   if(!uuid_conf || uuid_parse(uuid_conf, checkid)) goto error;
90
91   doc = xmlNewDoc((xmlChar *)"1.0");
92   root = xmlNewDocNode(doc, NULL, (xmlChar *)"check", NULL);
93   xmlDocSetRootElement(doc, root);
94
95 #define MYATTR(node,a,n,b) _noit_conf_get_string(node, &(n), "@" #a, &(b))
96 #define INHERIT(node,a,n,b) \
97   _noit_conf_get_string(node, &(n), "ancestor-or-self::node()/@" #a, &(b))
98 #define SHOW_ATTR(parent, node, a) do { \
99   xmlNodePtr anode = NULL; \
100   char *value = NULL; \
101   INHERIT(node, a, anode, value); \
102   if(value != NULL) { \
103     int clen, plen;\
104     const char *cpath, *apath; \
105     xmlNodePtr child; \
106     cpath = node ? (char *)xmlGetNodePath(node) : ""; \
107     apath = anode ? (char *)xmlGetNodePath(anode) : ""; \
108     clen = strlen(cpath); \
109     plen = strlen("/noit/checks"); \
110     child = xmlNewNode(NULL, (xmlChar *)#a); \
111     xmlNodeAddContent(child, (xmlChar *)value); \
112     if(!strncmp(cpath, apath, clen) && apath[clen] == '/') { \
113     } \
114     else { \
115       xmlSetProp(child, (xmlChar *)"inherited", (xmlChar *)apath+plen); \
116     } \
117     xmlAddChild(parent, child); \
118   } \
119 } while(0)
120 #define NODE_CONTENT(parent, k, v) do { \
121   xmlNodePtr tmp; \
122   if(v) { \
123     tmp = xmlNewNode(NULL, (xmlChar *)(k)); \
124     xmlNodeAddContent(tmp, (xmlChar *)(v)); \
125     xmlAddChild(parent, tmp); \
126   } \
127 } while(0)
128
129   attr = xmlNewNode(NULL, (xmlChar *)"attributes");
130   xmlAddChild(root, attr);
131
132   /* Name is odd, it falls back transparently to module */
133   if(!INHERIT(node, module, tmp, module)) module = NULL;
134   xmlAddChild(attr, (tmp = xmlNewNode(NULL, (xmlChar *)"name")));
135   if(MYATTR(node, name, anode, value))
136     xmlNodeAddContent(tmp, (xmlChar *)value);
137   else if(module)
138     xmlNodeAddContent(tmp, (xmlChar *)module);
139
140   SHOW_ATTR(attr,node,module);
141   SHOW_ATTR(attr,node,target);
142   SHOW_ATTR(attr,node,period);
143   SHOW_ATTR(attr,node,timeout);
144   SHOW_ATTR(attr,node,oncheck);
145   SHOW_ATTR(attr,node,filterset);
146   SHOW_ATTR(attr,node,disable);
147
148   /* Add the config */
149   config = xmlNewNode(NULL, (xmlChar *)"config");
150   configh = noit_conf_get_hash(node, "config");
151   while(noit_hash_next(configh, &iter, &k, &klen, &data))
152     NODE_CONTENT(config, k, data);
153   noit_hash_destroy(configh, free, free);
154   free(configh);
155   xmlAddChild(root, config);
156
157   /* Add the state */
158   xmlAddChild(root, (state = xmlNewNode(NULL, (xmlChar *)"state")));
159   check = noit_poller_lookup(checkid);
160   if(!check)
161     xmlSetProp(state, (xmlChar *)"error", (xmlChar *)"true");
162   else {
163     stats_t *c = &check->stats.current;
164     NODE_CONTENT(state, "running", NOIT_CHECK_RUNNING(check)?"true":"false");
165     NODE_CONTENT(state, "killed", NOIT_CHECK_KILLED(check)?"true":"false");
166     NODE_CONTENT(state, "configured",
167                  NOIT_CHECK_CONFIGURED(check)?"true":"false");
168     NODE_CONTENT(state, "disabled", NOIT_CHECK_DISABLED(check)?"true":"false");
169     xmlAddChild(state, (tmp = xmlNewNode(NULL, (xmlChar *)"last_run")));
170     if(check->stats.current.whence.tv_sec) {
171       struct timeval f = check->stats.current.whence;
172       struct timeval n;
173       char timestr[20];
174       gettimeofday(&n, NULL);
175       snprintf(timestr, sizeof(timestr), "%0.3f",
176                n.tv_sec + (n.tv_usec / 1000000.0));
177       xmlSetProp(tmp, (xmlChar *)"now", (xmlChar *)timestr);
178       snprintf(timestr, sizeof(timestr), "%0.3f",
179                f.tv_sec + (f.tv_usec / 1000000.0));
180       xmlNodeAddContent(tmp, (xmlChar *)timestr);
181     }
182     if(c->available) { /* truth here means the check has been run */
183       char buff[20];
184       snprintf(buff, sizeof(buff), "%0.3f", (float)c->duration/1000.0);
185       NODE_CONTENT(state, "runtime", buff);
186     }
187     NODE_CONTENT(state, "availability",
188                  noit_check_available_string(c->available));
189     NODE_CONTENT(state, "state", noit_check_state_string(c->state));
190     NODE_CONTENT(state, "status", c->status ? c->status : "");
191     memset(&iter, 0, sizeof(iter));
192     xmlAddChild(state, (metrics = xmlNewNode(NULL, (xmlChar *)"metrics")));
193     while(noit_hash_next(&c->metrics, &iter, &k, &klen, &data)) {
194       char buff[256];
195       metric_t *m = (metric_t *)data;
196       xmlAddChild(metrics, (tmp = xmlNewNode(NULL, (xmlChar *)m->metric_name)));
197       buff[0] = m->metric_type; buff[1] = '\0';
198       xmlSetProp(tmp, (xmlChar *)"type", (xmlChar *)buff);
199       if(m->metric_value.s) {
200         int rv;
201         rv = noit_stats_snprint_metric_value(buff, sizeof(buff), m);
202         if(rv < 0)
203           xmlSetProp(tmp, (xmlChar *)"error", (xmlChar *)"unknown type");
204         else
205           xmlNodeAddContent(tmp, (xmlChar *)buff);
206       }
207     }
208
209   }
210   noit_http_response_ok(ctx, "text/xml");
211   noit_http_response_xml(ctx, doc);
212   noit_http_response_end(ctx);
213   goto cleanup;
214
215  not_found:
216   noit_http_response_not_found(ctx, "text/html");
217   noit_http_response_end(ctx);
218   goto cleanup;
219
220  error:
221   noit_http_response_server_error(ctx, "text/html");
222   noit_http_response_end(ctx);
223   goto cleanup;
224
225  cleanup:
226   if(pobj) xmlXPathFreeObject(pobj);
227   if(doc) xmlFreeDoc(doc);
228   return 0;
229 }
230
231 static void
232 rest_xml_payload_free(void *f) {
233   struct rest_xml_payload *xmlin = f;
234   if(xmlin->buffer) free(xmlin->buffer);
235 }
236
237 static int
238 validate_check_post(xmlDocPtr doc, xmlNodePtr *a, xmlNodePtr *c) {
239   xmlNodePtr root, tl, an;
240   int name=0, module=0, target=0, period=0, timeout=0, filterset=0, disable=0;
241   *a = *c = NULL;
242   root = xmlDocGetRootElement(doc);
243   if(!root || strcmp((char *)root->name, "check")) return 0;
244   for(tl = root->children; tl; tl = tl->next) {
245     if(!strcmp((char *)tl->name, "attributes")) {
246       *a = tl->children;
247       for(an = tl->children; an; an = an->next) {
248 #define CHECK_N_SET(a) if(!strcmp((char *)an->name, #a)) a = 1
249         CHECK_N_SET(name);
250         else CHECK_N_SET(module);
251         else CHECK_N_SET(target);
252         else CHECK_N_SET(period);
253         else CHECK_N_SET(timeout);
254         else CHECK_N_SET(filterset);
255         else CHECK_N_SET(disable);
256         else return 0;
257       }
258     }
259     else if(!strcmp((char *)tl->name, "config")) {
260       *c = tl->children;
261       /* Noop, anything goes */
262     }
263     else return 0;
264   }
265   if(name && module && target && period && timeout && filterset) return 1;
266   return 0;
267 }
268 static void
269 configure_xml_check(xmlNodePtr check, xmlNodePtr a, xmlNodePtr c) {
270   xmlNodePtr n, config, oldconfig;
271   for(n = a; n; n = n->next) {
272 #define ATTR2PROP(attr) do { \
273   if(!strcmp((char *)n->name, #attr)) { \
274     xmlChar *v = xmlNodeGetContent(n); \
275     if(v) xmlSetProp(check, n->name, v); \
276     else xmlUnsetProp(check, n->name); \
277     if(v) xmlFree(v); \
278   } \
279 } while(0)
280     ATTR2PROP(name);
281     ATTR2PROP(target);
282     ATTR2PROP(module);
283     ATTR2PROP(period);
284     ATTR2PROP(timeout);
285     ATTR2PROP(disable);
286     ATTR2PROP(filter);
287   }
288   for(oldconfig = check->children; oldconfig; oldconfig = oldconfig->next)
289     if(!strcmp((char *)oldconfig->name, "config")) break;
290   config = xmlNewNode(NULL, (xmlChar *)"config");
291   for(n = c; n; n = n->next) {
292     xmlNodePtr co = xmlNewNode(NULL, n->name);
293     xmlNodeAddContent(co, XML_GET_CONTENT(n));
294     xmlAddChild(config, co);
295   }
296   if(oldconfig) {
297     xmlReplaceNode(oldconfig, config);
298     xmlFreeNode(oldconfig);
299   }
300   else xmlAddChild(check, config);
301 }
302 static xmlNodePtr
303 make_conf_path(char *path) {
304   xmlNodePtr start, tmp;
305   char fullpath[1024], *tok, *brk;
306   if(!path || strlen(path) < 1) return NULL;
307   snprintf(fullpath, sizeof(fullpath), "%s", path+1);
308   fullpath[strlen(fullpath)-1] = '\0';
309   start = noit_conf_get_section(NULL, "/noit/checks");
310   if(!start) return NULL;
311   for (tok = strtok_r(fullpath, "/", &brk);
312        tok;
313        tok = strtok_r(NULL, "/", &brk)) {
314     if(!xmlValidateNameValue((xmlChar *)tok)) return NULL;
315     if(!strcmp(tok, "check")) return NULL;  /* These two paths */
316     if(!strcmp(tok, "config")) return NULL; /* are off limits. */
317     for (tmp = start->children; tmp; tmp = tmp->next) {
318       if(!strcmp((char *)tmp->name, tok)) break;
319     }
320     if(!tmp) {
321       tmp = xmlNewNode(NULL, (xmlChar *)tok);
322       xmlAddChild(start, tmp);
323     }
324     start = tmp;
325   }
326   return start;
327 }
328 static int
329 rest_set_check(noit_http_rest_closure_t *restc,
330                int npats, char **pats) {
331   noit_http_session_ctx *ctx = restc->http_ctx;
332   xmlXPathObjectPtr pobj = NULL;
333   xmlXPathContextPtr xpath_ctxt = NULL;
334   xmlDocPtr doc = NULL, indoc = NULL;
335   xmlNodePtr node, root, attr, config, parent;
336   uuid_t checkid;
337   noit_check_t *check;
338   char xpath[1024], *uuid_conf;
339   int rv, cnt;
340   const char *error = "internal error";
341   noit_boolean exists = noit_false;
342   struct rest_xml_payload *rxc;
343
344   if(npats != 2) goto error;
345
346 #define FAIL(a) do { error = (a); goto error; } while(0)
347
348   if(restc->call_closure == NULL) {
349     rxc = restc->call_closure = calloc(1, sizeof(*rxc));
350     restc->call_closure_free = rest_xml_payload_free;
351   }
352   rxc = restc->call_closure;
353   while(!rxc->complete) {
354     int len, mask;
355     if(rxc->len == rxc->allocd) {
356       char *b;
357       rxc->allocd += 32768;
358       b = rxc->buffer ? realloc(rxc->buffer, rxc->allocd) :
359                         malloc(rxc->allocd);
360       if(!b) FAIL("alloc failed");
361       rxc->buffer = b;
362     }
363     len = noit_http_session_req_consume(restc->http_ctx,
364                                         rxc->buffer + rxc->len,
365                                         rxc->allocd - rxc->len,
366                                         &mask);
367     if(len > 0) rxc->len += len;
368     if(len < 0 && errno == EAGAIN) return mask;
369     if(rxc->len == restc->http_ctx->req.content_length) rxc->complete = 1;
370   }
371
372   indoc = xmlParseMemory(rxc->buffer, rxc->len);
373   if(indoc == NULL) FAIL("xml parse error");
374   if(!validate_check_post(indoc, &attr, &config)) FAIL("xml validate error");
375
376   if(uuid_parse(pats[1], checkid)) goto error;
377   check = noit_poller_lookup(checkid);
378   if(check)
379     exists = noit_true;
380
381   rv = noit_check_xpath(xpath, sizeof(xpath), pats[0], pats[1]);
382   if(rv == 0) FAIL("uuid not valid");
383   if(rv < 0) FAIL("Tricky McTrickster... No");
384
385   noit_conf_xml_xpath(NULL, &xpath_ctxt);
386   pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
387   if(!pobj || pobj->type != XPATH_NODESET ||
388      xmlXPathNodeSetIsEmpty(pobj->nodesetval)) {
389     if(exists) FAIL("uuid not yours");
390     else {
391       char *target = NULL, *name = NULL, *module = NULL;
392       noit_module_t *m;
393       xmlNodePtr newcheck, a;
394       /* make sure this isn't a dup */
395       for(a = attr; a; a = a->next) {
396         if(!strcmp((char *)a->name, "target"))
397           target = (char *)xmlNodeGetContent(a);
398         if(!strcmp((char *)a->name, "name"))
399           name = (char *)xmlNodeGetContent(a);
400         if(!strcmp((char *)a->name, "module"))
401           module = (char *)xmlNodeGetContent(a);
402       }
403       exists = (noit_poller_lookup_by_name(target, name) != NULL);
404       m = noit_module_lookup(module);
405       xmlFree(target);
406       xmlFree(name);
407       xmlFree(module);
408       if(exists) FAIL("target`name already registered");
409       if(!m) FAIL("module does not exist");
410       /* create a check here */
411       newcheck = xmlNewNode(NULL, (xmlChar *)"check");
412       xmlSetProp(newcheck, (xmlChar *)"uuid", (xmlChar *)pats[1]);
413       configure_xml_check(newcheck, attr, config);
414       parent = make_conf_path(pats[0]);
415       if(!parent) FAIL("invalid path");
416       xmlAddChild(parent, newcheck);
417     }
418   }
419   if(exists) {
420     int module_change;
421     char *target, *name, *module;
422     xmlNodePtr a;
423     noit_check_t *ocheck;
424     cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
425     if(cnt != 1) FAIL("internal error, |checkid| > 1");
426     node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
427     uuid_conf = (char *)xmlGetProp(node, (xmlChar *)"uuid");
428     if(!uuid_conf || strcasecmp(uuid_conf, pats[1]))
429       FAIL("internal error uuid");
430     /* update check here */
431
432     /* make sure this isn't a dup */
433     for(a = attr; a; a = a->next) {
434       if(!strcmp((char *)a->name, "target"))
435         target = (char *)xmlNodeGetContent(a);
436       if(!strcmp((char *)a->name, "name"))
437         name = (char *)xmlNodeGetContent(a);
438       if(!strcmp((char *)a->name, "module"))
439         module = (char *)xmlNodeGetContent(a);
440     }
441     ocheck = noit_poller_lookup_by_name(target, name);
442     module_change = strcmp(check->module, module);
443     xmlFree(target);
444     xmlFree(name);
445     xmlFree(module);
446     if(ocheck && ocheck != check) FAIL("new target`name would collide");
447     if(module_change) FAIL("cannot change module");
448     configure_xml_check(node, attr, config);
449     parent = make_conf_path(pats[0]);
450     if(!parent) FAIL("invalid path");
451     xmlUnlinkNode(node);
452     xmlAddChild(parent, node);
453   }
454
455   noit_conf_mark_changed();
456   noit_poller_reload(xpath);
457   if(restc->call_closure_free) restc->call_closure_free(restc->call_closure);
458   restc->call_closure_free = NULL;
459   restc->call_closure = NULL;
460   if(pobj) xmlXPathFreeObject(pobj);
461   if(doc) xmlFreeDoc(doc);
462   if(indoc) xmlFreeDoc(indoc);
463   restc->fastpath = rest_show_check;
464   return restc->fastpath(restc, restc->nparams, restc->params);
465
466  error:
467   noit_http_response_server_error(ctx, "text/xml");
468   doc = xmlNewDoc((xmlChar *)"1.0");
469   root = xmlNewDocNode(doc, NULL, (xmlChar *)"error", NULL);
470   xmlDocSetRootElement(doc, root);
471   xmlNodeAddContent(root, (xmlChar *)error);
472   noit_http_response_xml(ctx, doc);
473   noit_http_response_end(ctx);
474   goto cleanup;
475
476  cleanup:
477   if(pobj) xmlXPathFreeObject(pobj);
478   if(doc) xmlFreeDoc(doc);
479   if(indoc) xmlFreeDoc(indoc);
480   return 0;
481 }
482
483 void
484 noit_check_rest_init() {
485   assert(noit_http_rest_register(
486     "GET",
487     "/checks/",
488     "^show(/.*)(?<=/)(" UUID_REGEX ")$",
489     rest_show_check
490   ) == 0);
491   assert(noit_http_rest_register(
492     "POST",
493     "/checks/",
494     "^set(/.*)(?<=/)(" UUID_REGEX ")$",
495     rest_set_check
496   ) == 0);
497 }
498
Note: See TracBrowser for help on using the browser.