root/src/noit_conf.c

Revision 4500c970e66d7a20dc7b995e426cc4bb27fd0fc4, 46.2 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 7 years ago)

fix range error

noit_conf.c:544: warning: assuming signed overflow does not occur when
assuming that (X - c) >= X is always true

  • 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 <stdio.h>
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <assert.h>
40 #include <libxml/parser.h>
41 #include <libxml/tree.h>
42 #include <libxml/xpath.h>
43 #include <zlib.h>
44
45 #include "noit_conf.h"
46 #include "noit_check.h"
47 #include "noit_console.h"
48 #include "utils/noit_hash.h"
49 #include "utils/noit_log.h"
50 #include "utils/noit_b64.h"
51
52 /* tmp hash impl, replace this with something nice */
53 static noit_log_stream_t xml_debug = NULL;
54 #define XML2LOG(log) do { \
55   xmlSetGenericErrorFunc(log, noit_conf_xml_error_func); \
56   xmlSetStructuredErrorFunc(log, noit_conf_xml_error_ext_func); \
57 } while(0)
58 #define XML2CONSOLE(ncct) do { \
59   xmlSetGenericErrorFunc(ncct, noit_conf_xml_console_error_func); \
60   xmlSetStructuredErrorFunc(ncct, noit_conf_xml_console_error_ext_func); \
61 } while(0)
62 static noit_hash_table _tmp_config = NOIT_HASH_EMPTY;
63 static xmlDocPtr master_config = NULL;
64 static int config_include_cnt = -1;
65 static struct {
66   xmlNodePtr insertion_point;
67   xmlNodePtr old_children;
68   xmlDocPtr doc;
69   xmlNodePtr root;
70 } *config_include_nodes = NULL;
71
72 static char *root_node_name = NULL;
73 static char master_config_file[PATH_MAX] = "";
74 static xmlXPathContextPtr xpath_ctxt = NULL;
75
76 /* This is used to notice config changes and journal the config out
77  * using a user-specified function.  It supports allowing multiple config
78  * changed to coalesce so you don't write out 1000 changes in a few seconds.
79  */
80 static u_int32_t __config_gen = 0;
81 static u_int32_t __config_coalesce = 0;
82 static u_int32_t __config_coalesce_time = 0;
83 void noit_conf_coalesce_changes(u_int32_t seconds) {
84   __config_coalesce_time = seconds;
85 }
86 void noit_conf_mark_changed() {
87   /* increment the change counter -- in case anyone cares */
88   __config_gen++;
89   /* reset the coalesce counter.  It is decremented each second and
90    * the journal function fires on a transition from 1 => 0
91    */
92   __config_coalesce = __config_coalesce_time;
93 }
94 struct recurrent_journaler {
95   int (*journal_config)(void *);
96   void *jc_closure;
97 };
98 static int
99 noit_conf_watch_config_and_journal(eventer_t e, int mask, void *closure,
100                                    struct timeval *now) {
101   struct recurrent_journaler *rj = closure;
102   eventer_t newe;
103
104   if(__config_coalesce == 1)
105     rj->journal_config(rj->jc_closure);
106   if(__config_coalesce > 0)
107     __config_coalesce--;
108
109   /* Schedule the same event to fire a second form now */
110   newe = eventer_alloc();
111   gettimeofday(&newe->whence, NULL);
112   newe->whence.tv_sec += 1;
113   newe->mask = EVENTER_TIMER;
114   newe->callback = noit_conf_watch_config_and_journal;
115   newe->closure = closure;
116   eventer_add(newe);
117   return 0;
118 }
119 void
120 noit_conf_watch_and_journal_watchdog(int (*f)(void *), void *c) {
121   static int callbacknamed = 0;
122   struct recurrent_journaler *rj;
123   struct timeval __now;
124
125   if(!callbacknamed) {
126     callbacknamed = 1;
127     eventer_name_callback("noit_conf_watch_config_and_journal",
128                           noit_conf_watch_config_and_journal);
129   }
130   rj = calloc(1, sizeof(*rj));
131   rj->journal_config = f;
132   rj->jc_closure = c;
133   gettimeofday(&__now, NULL);
134   noit_conf_watch_config_and_journal(NULL, EVENTER_TIMER, rj, &__now);
135 }
136
137 static noit_hash_table _compiled_fallback = NOIT_HASH_EMPTY;
138 static struct {
139   const char *key;
140   const char *val;
141 } config_info[] = {
142   /*
143    * These are compile-time fallbacks to be used in the event
144    * that the current running config does not have values for
145    * these config paths.
146    *
147    * PLEASE: keep them alphabetically sorted.
148    */
149   { "/%s/eventer/@implementation", DEFAULT_EVENTER },
150   { "/%s/modules/@directory", MODULES_DIR },
151
152   { NULL, NULL }
153 };
154
155 void noit_conf_xml_console_error_func(void *ctx, const char *format, ...) {
156   noit_console_closure_t ncct = ctx;
157   va_list arg;
158   if(!ncct) return;
159   va_start(arg, format);
160   nc_vprintf(ncct, format, arg);
161   va_end(arg);
162 }
163
164 void noit_conf_xml_console_error_ext_func(void *ctx, xmlErrorPtr err) {
165   noit_console_closure_t ncct = ctx;
166   if(!ctx) return;
167   if(err->file)
168     nc_printf(ncct, "XML error [%d/%d] in %s on line %d %s\n",
169               err->domain, err->code, err->file, err->line, err->message);
170   else
171     nc_printf(ncct, "XML error [%d/%d] %s\n",
172               err->domain, err->code, err->message);
173 }
174
175 void noit_conf_xml_error_func(void *ctx, const char *format, ...) {
176   struct timeval __now;
177   noit_log_stream_t ls = ctx;
178   va_list arg;
179   if(!ls) return;
180   va_start(arg, format);
181   gettimeofday(&__now,  NULL);
182   noit_vlog(ls, &__now, __FILE__, __LINE__, format, arg);
183   va_end(arg);
184 }
185 void noit_conf_xml_error_ext_func(void *ctx, xmlErrorPtr err) {
186   struct timeval __now;
187   noit_log_stream_t ls = ctx;
188   if(!ls) return;
189   gettimeofday(&__now,  NULL);
190   if(err->file)
191     noit_log(ls, &__now, err->file, err->line,
192              "XML error [%d/%d] in %s on line %d %s\n",
193              err->domain, err->code, err->file, err->line, err->message);
194   else
195     noit_log(ls, &__now, err->file, err->line,
196              "XML error [%d/%d] %s\n",
197              err->domain, err->code, err->message);
198 }
199
200
201 DECLARE_CHECKER(name)
202 void noit_conf_init(const char *toplevel) {
203   int i;
204   char keystr[256];
205
206   xml_debug = noit_log_stream_find("debug/xml");
207
208   COMPILE_CHECKER(name, "^[-_\\.:/a-zA-Z0-9]+$");
209   XML2LOG(noit_error);
210   for(i = 0; config_info[i].key != NULL; i++) {
211     snprintf(keystr, sizeof(keystr), config_info[i].key, toplevel);
212     noit_hash_store(&_compiled_fallback,
213                     strdup(keystr), strlen(keystr),
214                     (void *)strdup(config_info[i].val));
215   }
216   xmlKeepBlanksDefault(0);
217   xmlInitParser();
218   xmlXPathInit();
219 }
220
221 void
222 noit_conf_magic_separate(xmlDocPtr doc) {
223   assert(config_include_cnt != -1);
224   if(config_include_nodes) {
225     int i;
226     for(i=0; i<config_include_cnt; i++) {
227       if(config_include_nodes[i].doc) {
228         xmlNodePtr n;
229         for(n=config_include_nodes[i].insertion_point->children;
230             n; n = n->next)
231           n->parent = config_include_nodes[i].root;
232         config_include_nodes[i].insertion_point->children =
233           config_include_nodes[i].old_children;
234         xmlFreeDoc(config_include_nodes[i].doc);
235       }
236     }
237     free(config_include_nodes);
238   }
239   config_include_nodes = NULL;
240   config_include_cnt = -1;
241 }
242 void
243 noit_conf_kansas_city_shuffle_redo(xmlDocPtr doc) {
244   if(config_include_nodes) {
245     int i;
246     for(i=0; i<config_include_cnt; i++) {
247       if(config_include_nodes[i].doc) {
248         xmlNodePtr n;
249         config_include_nodes[i].insertion_point->children =
250           config_include_nodes[i].root->children;
251         for(n=config_include_nodes[i].insertion_point->children;
252             n; n = n->next)
253           n->parent = config_include_nodes[i].insertion_point;
254       }
255     }
256   }
257 }
258 void
259 noit_conf_kansas_city_shuffle_undo(xmlDocPtr doc) {
260   if(config_include_nodes) {
261     int i;
262     for(i=0; i<config_include_cnt; i++) {
263       if(config_include_nodes[i].doc) {
264         xmlNodePtr n;
265         for(n=config_include_nodes[i].insertion_point->children;
266             n; n = n->next)
267           n->parent = config_include_nodes[i].root;
268         config_include_nodes[i].insertion_point->children =
269           config_include_nodes[i].old_children;
270       }
271     }
272   }
273 }
274 int
275 noit_conf_magic_mix(const char *parentfile, xmlDocPtr doc) {
276   xmlXPathContextPtr mix_ctxt = NULL;
277   xmlXPathObjectPtr pobj = NULL;
278   xmlNodePtr node;
279   int i, cnt, rv = 0;
280
281   assert(config_include_cnt == -1);
282
283   config_include_cnt = 0;
284   mix_ctxt = xmlXPathNewContext(doc);
285   pobj = xmlXPathEval((xmlChar *)"//include[@file]", mix_ctxt);
286   if(!pobj) goto out;
287   if(pobj->type != XPATH_NODESET) goto out;
288   if(xmlXPathNodeSetIsEmpty(pobj->nodesetval)) goto out;
289   cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
290   if(cnt > 0)
291     config_include_nodes = calloc(cnt, sizeof(*config_include_nodes));
292   for(i=0; i<cnt; i++) {
293     char *path, *infile;
294     node = xmlXPathNodeSetItem(pobj->nodesetval, i);
295     path = (char *)xmlGetProp(node, (xmlChar *)"file");
296     if(!path) continue;
297     if(*path == '/') infile = strdup(path);
298     else {
299       char *cp;
300       infile = malloc(PATH_MAX);
301       strlcpy(infile, parentfile, PATH_MAX);
302       for(cp = infile + strlen(infile) - 1; cp > infile; cp--) {
303         if(*cp == '/') { *cp = '\0'; break; }
304         else *cp = '\0';
305       }
306       strlcat(infile, "/", PATH_MAX);
307       strlcat(infile, path, PATH_MAX);
308     }
309     config_include_nodes[i].doc = xmlParseFile(infile);
310     if(config_include_nodes[i].doc) {
311       xmlNodePtr n;
312       config_include_nodes[i].insertion_point = node;
313       config_include_nodes[i].root = xmlDocGetRootElement(config_include_nodes[i].doc);
314       config_include_nodes[i].old_children = node->children;
315       node->children = config_include_nodes[i].root->children;
316       for(n=node->children; n; n = n->next)
317         n->parent = config_include_nodes[i].insertion_point;
318     }
319     else {
320       noitL(noit_error, "Could not load: '%s'\n", infile);
321       rv = -1;
322     }
323     free(infile);
324   }
325   config_include_cnt = cnt;
326   noitL(noit_debug, "Processed %d includes\n", config_include_cnt);
327  out:
328   if(pobj) xmlXPathFreeObject(pobj);
329   if(mix_ctxt) xmlXPathFreeContext(mix_ctxt);
330   return rv;
331 }
332
333 int noit_conf_load(const char *path) {
334   int rv = 0;
335   xmlDocPtr new_config;
336   xmlNodePtr root;
337   new_config = xmlParseFile(path);
338   if(new_config) {
339     root = xmlDocGetRootElement(new_config);
340     if(root_node_name) free(root_node_name);
341     root_node_name = strdup((char *)root->name);
342
343     if(master_config) {
344       /* separate all includes */
345       noit_conf_magic_separate(master_config);
346       xmlFreeDoc(master_config);
347     }
348     if(xpath_ctxt) xmlXPathFreeContext(xpath_ctxt);
349
350     master_config = new_config;
351     /* mixin all the includes */
352     if(noit_conf_magic_mix(path, master_config)) rv = -1;
353
354     xpath_ctxt = xmlXPathNewContext(master_config);
355     if(path != master_config_file)
356       if(realpath(path, master_config_file) == NULL)
357         noitL(noit_error, "realpath failed: %s\n", strerror(errno));
358     noit_conf_mark_changed();
359     return rv;
360   }
361   rv = -1;
362   return rv;
363 }
364
365 char *noit_conf_config_filename() {
366   return strdup(master_config_file);
367 }
368
369 int noit_conf_xml_xpath(xmlDocPtr *mc, xmlXPathContextPtr *xp) {
370   if(mc) *mc = master_config;
371   if(xp) *xp = xpath_ctxt;
372   return 0;
373 }
374 int noit_conf_save(const char *path) {
375   return -1;
376 }
377
378 void noit_conf_get_elements_into_hash(noit_conf_section_t section,
379                                       const char *path,
380                                       noit_hash_table *table) {
381   int i, cnt;
382   xmlXPathObjectPtr pobj = NULL;
383   xmlXPathContextPtr current_ctxt;
384   xmlNodePtr current_node = (xmlNodePtr)section;
385   xmlNodePtr node;
386
387   current_ctxt = xpath_ctxt;
388   if(current_node) {
389     current_ctxt = xmlXPathNewContext(master_config);
390     current_ctxt->node = current_node;
391   }
392   pobj = xmlXPathEval((xmlChar *)path, current_ctxt);
393   if(!pobj) goto out;
394   if(pobj->type != XPATH_NODESET) goto out;
395   if(xmlXPathNodeSetIsEmpty(pobj->nodesetval)) goto out;
396   cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
397   for(i=0; i<cnt; i++) {
398     char *value;
399     node = xmlXPathNodeSetItem(pobj->nodesetval, i);
400     value = (char *)xmlXPathCastNodeToString(node);
401     noit_hash_replace(table,
402                       strdup((char *)node->name), strlen((char *)node->name),
403                       strdup(value), free, free);
404     xmlFree(value);
405   }
406  out:
407   if(pobj) xmlXPathFreeObject(pobj);
408   if(current_ctxt && current_ctxt != xpath_ctxt)
409     xmlXPathFreeContext(current_ctxt);
410 }
411 void noit_conf_get_into_hash(noit_conf_section_t section,
412                              const char *path,
413                              noit_hash_table *table) {
414   unsigned int cnt;
415   xmlXPathObjectPtr pobj = NULL;
416   xmlXPathContextPtr current_ctxt;
417   xmlNodePtr current_node = (xmlNodePtr)section;
418   xmlNodePtr node, parent_node;
419   char xpath_expr[1024];
420   char *inheritid;
421
422   current_ctxt = xpath_ctxt;
423   if(current_node) {
424     current_ctxt = xmlXPathNewContext(master_config);
425     current_ctxt->node = current_node;
426   }
427   if(path[0] == '/')
428     strlcpy(xpath_expr, path, sizeof(xpath_expr));
429   else
430     snprintf(xpath_expr, sizeof(xpath_expr),
431              "ancestor-or-self::node()/%s", path);
432   pobj = xmlXPathEval((xmlChar *)xpath_expr, current_ctxt);
433   if(!pobj) goto out;
434   if(pobj->type != XPATH_NODESET) goto out;
435   if(xmlXPathNodeSetIsEmpty(pobj->nodesetval)) goto out;
436   cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
437   /* These are in the order of root to leaf
438    * We want to recurse... apply:
439    *   1. our parent's config
440    *   2. our "inherit" config if it exists.
441    *   3. our config.
442    */
443   node = xmlXPathNodeSetItem(pobj->nodesetval, cnt-1);
444   /* 1. */
445   if(cnt > 1 && node) {
446     parent_node = xmlXPathNodeSetItem(pobj->nodesetval, cnt-2);
447     if(parent_node != current_node)
448       noit_conf_get_into_hash(parent_node, (const char *)node->name, table);
449   }
450   /* 2. */
451   inheritid = (char *)xmlGetProp(node, (xmlChar *)"inherit");
452   if(inheritid) {
453     snprintf(xpath_expr, sizeof(xpath_expr), "//*[@id=\"%s\"]", inheritid);
454     noit_conf_get_into_hash(NULL, xpath_expr, table);
455   }
456   /* 3. */
457   noit_conf_get_elements_into_hash(node, "*", table);
458
459  out:
460   if(pobj) xmlXPathFreeObject(pobj);
461   if(current_ctxt && current_ctxt != xpath_ctxt)
462     xmlXPathFreeContext(current_ctxt);
463 }
464 noit_hash_table *noit_conf_get_hash(noit_conf_section_t section,
465                                     const char *path) {
466   noit_hash_table *table = NULL;
467
468   table = calloc(1, sizeof(*table));
469   noit_conf_get_into_hash(section, path, table);
470   return table;
471 }
472 noit_conf_section_t noit_conf_get_section(noit_conf_section_t section,
473                                           const char *path) {
474   noit_conf_section_t subsection = NULL;
475   xmlXPathObjectPtr pobj = NULL;
476   xmlXPathContextPtr current_ctxt;
477   xmlNodePtr current_node = (xmlNodePtr)section;
478
479   current_ctxt = xpath_ctxt;
480   if(current_node) {
481     current_ctxt = xmlXPathNewContext(master_config);
482     current_ctxt->node = current_node;
483   }
484   pobj = xmlXPathEval((xmlChar *)path, current_ctxt);
485   if(!pobj) goto out;
486   if(pobj->type != XPATH_NODESET) goto out;
487   if(xmlXPathNodeSetIsEmpty(pobj->nodesetval)) goto out;
488   subsection = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
489  out:
490   if(pobj) xmlXPathFreeObject(pobj);
491   if(current_ctxt && current_ctxt != xpath_ctxt)
492     xmlXPathFreeContext(current_ctxt);
493   return subsection;
494 }
495 noit_conf_section_t *noit_conf_get_sections(noit_conf_section_t section,
496                                             const char *path,
497                                             int *cnt) {
498   int i;
499   noit_conf_section_t *sections = NULL;
500   xmlXPathObjectPtr pobj = NULL;
501   xmlXPathContextPtr current_ctxt;
502   xmlNodePtr current_node = (xmlNodePtr)section;
503
504   *cnt = 0;
505   current_ctxt = xpath_ctxt;
506   if(current_node) {
507     current_ctxt = xmlXPathNewContext(master_config);
508     current_ctxt->node = current_node;
509   }
510   pobj = xmlXPathEval((xmlChar *)path, current_ctxt);
511   if(!pobj) goto out;
512   if(pobj->type != XPATH_NODESET) goto out;
513   if(xmlXPathNodeSetIsEmpty(pobj->nodesetval)) goto out;
514   *cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
515   sections = calloc(*cnt, sizeof(*sections));
516   for(i=0; i<*cnt; i++)
517     sections[i] = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
518  out:
519   if(pobj) xmlXPathFreeObject(pobj);
520   if(current_ctxt && current_ctxt != xpath_ctxt)
521     xmlXPathFreeContext(current_ctxt);
522   return sections;
523 }
524 int _noit_conf_get_string(noit_conf_section_t section, xmlNodePtr *vnode,
525                           const char *path, char **value) {
526   const char *str;
527   int rv = 1;
528   unsigned int i;
529   xmlXPathObjectPtr pobj = NULL;
530   xmlXPathContextPtr current_ctxt;
531   xmlNodePtr current_node = (xmlNodePtr)section;
532
533   current_ctxt = xpath_ctxt;
534   if(current_node) {
535     current_ctxt = xmlXPathNewContext(master_config);
536     current_ctxt->node = current_node;
537   }
538   pobj = xmlXPathEval((xmlChar *)path, current_ctxt);
539   if(pobj) {
540     xmlNodePtr node;
541     switch(pobj->type) {
542       case XPATH_NODESET:
543         if(xmlXPathNodeSetIsEmpty(pobj->nodesetval)) goto fallback;
544         i = xmlXPathNodeSetGetLength(pobj->nodesetval);
545         node = xmlXPathNodeSetItem(pobj->nodesetval, i-1);
546         if(vnode) *vnode = node;
547         *value = (char *)xmlXPathCastNodeToString(node);
548         break;
549       default:
550         *value = (char *)xmlXPathCastToString(pobj);
551     }
552     goto found;
553   }
554  fallback:
555   if(noit_hash_retr_str(&_compiled_fallback,
556                         path, strlen(path), &str)) {
557     *value = (char *)xmlStrdup((xmlChar *)str);
558     goto found;
559   }
560   rv = 0;
561  found:
562   if(pobj) xmlXPathFreeObject(pobj);
563   if(current_ctxt && current_ctxt != xpath_ctxt)
564     xmlXPathFreeContext(current_ctxt);
565   return rv;
566 }
567 int noit_conf_get_uuid(noit_conf_section_t section,
568                        const char *path, uuid_t out) {
569   char *str;
570   if(_noit_conf_get_string(section,NULL,path,&str)) {
571     if(uuid_parse(str, out) == 0) return 1;
572     return 0;
573   }
574   return 0;
575 }
576 int noit_conf_get_string(noit_conf_section_t section,
577                          const char *path, char **value) {
578   char *str;
579   if(_noit_conf_get_string(section,NULL,path,&str)) {
580     *value = strdup(str);
581     xmlFree(str);
582     return 1;
583   }
584   return 0;
585 }
586 int noit_conf_get_stringbuf(noit_conf_section_t section,
587                             const char *path, char *buf, int len) {
588   char *str;
589   if(_noit_conf_get_string(section,NULL,path,&str)) {
590     strlcpy(buf, str, len);
591     xmlFree(str);
592     return 1;
593   }
594   return 0;
595 }
596 int noit_conf_set_string(noit_conf_section_t section,
597                          const char *path, const char *value) {
598   noit_hash_replace(&_tmp_config,
599                     strdup(path), strlen(path), (void *)strdup(value),
600                     free, free);
601   return 1;
602 }
603 int noit_conf_string_to_int(const char *str) {
604   int base = 10;
605   if(!str) return 0;
606   if(str[0] == '0') {
607     if(str[1] == 'x') base = 16;
608     else base = 8;
609   }
610   return strtol(str, NULL, base);
611 }
612 int noit_conf_get_int(noit_conf_section_t section,
613                       const char *path, int *value) {
614   char *str;
615   if(_noit_conf_get_string(section,NULL,path,&str)) {
616     *value = (int)noit_conf_string_to_int(str);
617     xmlFree(str);
618     return 1;
619   }
620   return 0;
621 }
622 int noit_conf_set_int(noit_conf_section_t section,
623                       const char *path, int value) {
624   char buffer[32];
625   snprintf(buffer, 32, "%d", value);
626   return noit_conf_set_string(section,path,buffer);
627 }
628 float noit_conf_string_to_float(const char *str) {
629   if(!str) return 0.0;
630   return atof(str);
631 }
632 int noit_conf_get_float(noit_conf_section_t section,
633                         const char *path, float *value) {
634   char *str;
635   if(_noit_conf_get_string(section,NULL,path,&str)) {
636     *value = noit_conf_string_to_float(str);
637     xmlFree(str);
638     return 1;
639   }
640   return 0;
641 }
642 int noit_conf_set_float(noit_conf_section_t section,
643                         const char *path, float value) {
644   char buffer[32];
645   snprintf(buffer, 32, "%f", value);
646   return noit_conf_set_string(section,path,buffer);
647 }
648 noit_boolean noit_conf_string_to_boolean(const char *str) {
649   if(!str) return noit_false;
650   if(!strcasecmp(str, "true") || !strcasecmp(str, "on")) return noit_true;
651   return noit_false;
652 }
653 int noit_conf_get_boolean(noit_conf_section_t section,
654                           const char *path, noit_boolean *value) {
655   char *str;
656   if(_noit_conf_get_string(section,NULL,path,&str)) {
657     *value = noit_conf_string_to_boolean(str);
658     xmlFree(str);
659     return 1;
660   }
661   return 0;
662 }
663 int noit_conf_set_boolean(noit_conf_section_t section,
664                           const char *path, noit_boolean value) {
665   if(value == noit_true)
666     return noit_conf_set_string(section,path,"true");
667   return noit_conf_set_string(section,path,"false");
668 }
669
670 struct config_line_vstr {
671   char *buff;
672   int raw_len;
673   int len;
674   int allocd;
675   enum { CONFIG_RAW = 0, CONFIG_COMPRESSED, CONFIG_B64 } target, encoded;
676 };
677 static int
678 noit_config_log_write_xml(void *vstr, const char *buffer, int len) {
679   struct config_line_vstr *clv = vstr;
680   assert(clv->encoded == CONFIG_RAW);
681   if(!clv->buff) {
682     clv->allocd = 8192;
683     clv->buff = malloc(clv->allocd);
684   }
685   while(len + clv->len > clv->allocd) {
686     char *newbuff;
687     int newsize = clv->allocd;
688     newsize <<= 1;
689     newbuff = realloc(clv->buff, newsize);
690     if(!newbuff) {
691       return -1;
692     }
693     clv->allocd = newsize;
694     clv->buff = newbuff;
695   }
696   memcpy(clv->buff + clv->len, buffer, len);
697   clv->len += len;
698   return len;
699 }
700 static int
701 noit_config_log_close_xml(void *vstr) {
702   struct config_line_vstr *clv = vstr;
703   uLong initial_dlen, dlen;
704   char *compbuff, *b64buff;
705
706   if(clv->buff == NULL) {
707     clv->encoded = clv->target;
708     return 0;
709   }
710   clv->raw_len = clv->len;
711   assert(clv->encoded == CONFIG_RAW);
712   if(clv->encoded == clv->target) return 0;
713
714   /* Compress */
715   initial_dlen = dlen = compressBound(clv->len);
716   compbuff = malloc(initial_dlen);
717   if(!compbuff) return -1;
718   if(Z_OK != compress2((Bytef *)compbuff, &dlen,
719                        (Bytef *)clv->buff, clv->len, 9)) {
720     noitL(noit_error, "Error compressing config for transmission.\n");
721     free(compbuff);
722     return -1;
723   }
724   free(clv->buff);
725   clv->buff = compbuff;
726   clv->allocd = initial_dlen;
727   clv->len = dlen;
728   clv->encoded = CONFIG_COMPRESSED;
729   if(clv->encoded == clv->target) return 0;
730
731   /* Encode */
732   initial_dlen = ((clv->len + 2) / 3) * 4;
733   b64buff = malloc(initial_dlen);
734   dlen = noit_b64_encode((unsigned char *)clv->buff, clv->len,
735                          b64buff, initial_dlen);
736   if(dlen == 0) {
737     free(b64buff);
738     return -1;
739   }
740   free(clv->buff);
741   clv->buff = b64buff;
742   clv->allocd = initial_dlen;
743   clv->len = dlen;
744   clv->encoded = CONFIG_B64;
745   if(clv->encoded == clv->target) return 0;
746   return -1;
747 }
748
749 int
750 noit_conf_reload(noit_console_closure_t ncct,
751                  int argc, char **argv,
752                  noit_console_state_t *state, void *closure) {
753   XML2CONSOLE(ncct);
754   if(noit_conf_load(master_config_file)) {
755     XML2LOG(xml_debug);
756     nc_printf(ncct, "error loading config\n");
757     return -1;
758   }
759   XML2LOG(xml_debug);
760   return 0;
761 }
762 int
763 noit_conf_write_terminal(noit_console_closure_t ncct,
764                          int argc, char **argv,
765                          noit_console_state_t *state, void *closure) {
766   xmlOutputBufferPtr out;
767   xmlCharEncodingHandlerPtr enc;
768   enc = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF8);
769   out = xmlOutputBufferCreateIO(noit_console_write_xml,
770                                 noit_console_close_xml,
771                                 ncct, enc);
772   noit_conf_kansas_city_shuffle_undo(master_config);
773   xmlSaveFormatFileTo(out, master_config, "utf8", 1);
774   noit_conf_kansas_city_shuffle_redo(master_config);
775   return 0;
776 }
777 int
778 noit_conf_write_file_console(noit_console_closure_t ncct,
779                              int argc, char **argv,
780                              noit_console_state_t *state, void *closure) {
781   int rv;
782   char *err = NULL;
783   rv = noit_conf_write_file(&err);
784   nc_printf(ncct, "%s\n", err);
785   if(err) free(err);
786   return rv;
787 }
788 int
789 noit_conf_write_file(char **err) {
790   int fd, len;
791   char master_file_tmp[PATH_MAX];
792   char errstr[1024];
793   xmlOutputBufferPtr out;
794   xmlCharEncodingHandlerPtr enc;
795   struct stat st;
796   mode_t mode = 0640; /* the default */
797
798   if(stat(master_config_file, &st) == 0)
799     mode = st.st_mode;
800   snprintf(master_file_tmp, sizeof(master_file_tmp),
801            "%s.tmp", master_config_file);
802   unlink(master_file_tmp);
803   fd = open(master_file_tmp, O_CREAT|O_EXCL|O_WRONLY, mode);
804   if(fd < 0) {
805     snprintf(errstr, sizeof(errstr), "Failed to open tmp file: %s",
806              strerror(errno));
807     if(err) *err = strdup(errstr);
808     return -1;
809   }
810   enc = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF8);
811   out = xmlOutputBufferCreateFd(fd, enc);
812   if(!out) {
813     close(fd);
814     unlink(master_file_tmp);
815     if(err) *err = strdup("internal error: OutputBufferCreate failed");
816     return -1;
817   }
818   noit_conf_kansas_city_shuffle_undo(master_config);
819   len = xmlSaveFormatFileTo(out, master_config, "utf8", 1);
820   noit_conf_kansas_city_shuffle_redo(master_config);
821   close(fd);
822   if(len <= 0) {
823     if(err) *err = strdup("internal error: writing to tmp file failed.");
824     return -1;
825   }
826   if(rename(master_file_tmp, master_config_file) != 0) {
827     snprintf(errstr, sizeof(errstr), "Failed to replace file: %s",
828              strerror(errno));
829     if(err) *err = strdup(errstr);
830     return -1;
831   }
832   snprintf(errstr, sizeof(errstr), "%d bytes written.", len);
833   if(err) *err = strdup(errstr);
834   return 0;
835 }
836 char *
837 noit_conf_xml_in_mem(size_t *len) {
838   struct config_line_vstr *clv;
839   xmlOutputBufferPtr out;
840   xmlCharEncodingHandlerPtr enc;
841   char *rv;
842
843   clv = calloc(1, sizeof(*clv));
844   clv->target = CONFIG_RAW;
845   enc = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF8);
846   out = xmlOutputBufferCreateIO(noit_config_log_write_xml,
847                                 noit_config_log_close_xml,
848                                 clv, enc);
849   noit_conf_kansas_city_shuffle_undo(master_config);
850   xmlSaveFormatFileTo(out, master_config, "utf8", 1);
851   noit_conf_kansas_city_shuffle_redo(master_config);
852   if(clv->encoded != CONFIG_RAW) {
853     noitL(noit_error, "Error logging configuration\n");
854     if(clv->buff) free(clv->buff);
855     free(clv);
856     return NULL;
857   }
858   rv = clv->buff;
859   *len = clv->len;
860   free(clv);
861   return rv;
862 }
863
864 int
865 noit_conf_write_log() {
866   static u_int32_t last_write_gen = 0;
867   static noit_log_stream_t config_log = NULL;
868   struct timeval __now;
869   xmlOutputBufferPtr out;
870   xmlCharEncodingHandlerPtr enc;
871   struct config_line_vstr *clv;
872   SETUP_LOG(config, return -1);
873
874   /* We know we haven't changed */
875   if(last_write_gen == __config_gen) return 0;
876
877   gettimeofday(&__now, NULL);
878   clv = calloc(1, sizeof(*clv));
879   clv->target = CONFIG_B64;
880   enc = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF8);
881   out = xmlOutputBufferCreateIO(noit_config_log_write_xml,
882                                 noit_config_log_close_xml,
883                                 clv, enc);
884   noit_conf_kansas_city_shuffle_undo(master_config);
885   xmlSaveFormatFileTo(out, master_config, "utf8", 1);
886   noit_conf_kansas_city_shuffle_redo(master_config);
887   if(clv->encoded != CONFIG_B64) {
888     noitL(noit_error, "Error logging configuration\n");
889     if(clv->buff) free(clv->buff);
890     free(clv);
891     return -1;
892   }
893   noitL(config_log, "n\t%lu.%03lu\t%d\t%.*s\n",
894         (unsigned long int)__now.tv_sec,
895         (unsigned long int)__now.tv_usec / 1000UL, clv->raw_len,
896         clv->len, clv->buff);
897   free(clv->buff);
898   free(clv);
899   last_write_gen = __config_gen;
900   return 0;
901 }
902
903 struct log_rotate_crutch {
904   noit_log_stream_t ls;
905   int seconds;
906   size_t max_size;
907 };
908
909 static int
910 noit_conf_log_rotate_size(eventer_t e, int mask, void *closure,
911                           struct timeval *now) {
912   struct log_rotate_crutch *lrc = closure;
913   if(noit_log_stream_written(lrc->ls) > lrc->max_size) {
914     noit_log_stream_rename(lrc->ls, NOIT_LOG_RENAME_AUTOTIME);
915     noit_log_stream_reopen(lrc->ls);
916   }
917   /* Yes the 5 is arbitrary, but this is cheap */
918   eventer_add_in_s_us(noit_conf_log_rotate_size, closure, 5, 0);
919   return 0;
920 }
921 static int
922 noit_conf_log_rotate_time(eventer_t e, int mask, void *closure,
923                           struct timeval *now) {
924   struct timeval lnow;
925   eventer_t newe;
926   struct log_rotate_crutch *lrc = closure;
927
928   if(now) {
929     noit_log_stream_rename(lrc->ls, NOIT_LOG_RENAME_AUTOTIME);
930     noit_log_stream_reopen(lrc->ls);
931   }
932  
933   newe = eventer_alloc();
934   newe->closure = closure;
935   if(!now) { gettimeofday(&lnow, NULL); now = &lnow; }
936   if(e)
937     memcpy(&newe->whence, &e->whence, sizeof(newe->whence));
938   else if(now) {
939     memcpy(&newe->whence, now, sizeof(newe->whence));
940     newe->whence.tv_sec = (newe->whence.tv_sec / lrc->seconds) * lrc->seconds;
941   }
942   newe->whence.tv_sec += lrc->seconds;
943   newe->mask = EVENTER_TIMER;
944   newe->callback = noit_conf_log_rotate_time;
945   eventer_add(newe);
946   return 0;
947 }
948 int
949 noit_conf_log_init_rotate(const char *toplevel, noit_boolean validate) {
950   int i, cnt = 0, max_time, max_size, rv = 0;
951   noit_conf_section_t *log_configs;
952   char path[256];
953
954   snprintf(path, sizeof(path), "/%s/logs//log", toplevel);
955   log_configs = noit_conf_get_sections(NULL, path, &cnt);
956   noitL(noit_debug, "Found %d %s stanzas\n", cnt, path);
957   for(i=0; i<cnt; i++) {
958     noit_log_stream_t ls;
959     char name[256];
960
961     if(!noit_conf_get_stringbuf(log_configs[i],
962                                 "ancestor-or-self::node()/@name",
963                                 name, sizeof(name))) {
964       noitL(noit_error, "log section %d does not have a name attribute\n", i+1);
965       if(validate) { rv = -1; break; }
966       else exit(-2);
967     }
968     ls = noit_log_stream_find(name);
969     if(!ls) continue;
970
971     if(noit_conf_get_int(log_configs[i],   
972                          "ancestor-or-self::node()/@rotate_seconds",
973                          &max_time) && max_time) {
974       struct log_rotate_crutch *lrc;
975       if(max_time < 600) {
976         fprintf(stderr, "rotate_seconds must be >= 600s (10 minutes)\n");
977         if(validate) { rv = -1; break; }
978         else exit(-2);
979       }
980       if(!validate) {
981         lrc = calloc(1, sizeof(*lrc));
982         lrc->ls = ls;
983         lrc->seconds = max_time;
984         noit_conf_log_rotate_time(NULL, EVENTER_TIMER, lrc, NULL);
985       }
986     }
987
988     if(noit_conf_get_int(log_configs[i],   
989                          "ancestor-or-self::node()/@rotate_bytes",
990                          &max_size) && max_size) {
991       struct log_rotate_crutch *lrc;
992       if(max_size < 102400) {
993         fprintf(stderr, "rotate_bytes must be >= 102400 (100k)\n");
994         if(validate) { rv = -1; break; }
995         else exit(-2);
996       }
997       if(!validate) {
998         lrc = calloc(1, sizeof(*lrc));
999         lrc->ls = ls;
1000         lrc->max_size = max_size;
1001         noit_conf_log_rotate_size(NULL, EVENTER_TIMER, lrc, NULL);
1002       }
1003     }
1004   }
1005   free(log_configs);
1006   return rv;
1007 }
1008 void
1009 noit_conf_log_init(const char *toplevel) {
1010   int i, cnt = 0, o, ocnt = 0;
1011   noit_conf_section_t *log_configs, *outlets;
1012   char path[256];
1013
1014   snprintf(path, sizeof(path), "/%s/logs//log", toplevel);
1015   log_configs = noit_conf_get_sections(NULL, path, &cnt);
1016   noitL(noit_debug, "Found %d %s stanzas\n", cnt, path);
1017   for(i=0; i<cnt; i++) {
1018     noit_log_stream_t ls;
1019     char name[256], type[256], path[256];
1020     noit_hash_table *config;
1021     noit_boolean disabled, debug, timestamps;
1022
1023     if(!noit_conf_get_stringbuf(log_configs[i],
1024                                 "ancestor-or-self::node()/@name",
1025                                 name, sizeof(name))) {
1026       noitL(noit_error, "log section %d does not have a name attribute\n", i+1);
1027       exit(-1);
1028     }
1029     if(!noit_conf_get_stringbuf(log_configs[i],
1030                                 "ancestor-or-self::node()/@type",
1031                                 type, sizeof(type))) {
1032       type[0] = '\0';
1033     }
1034     if(!noit_conf_get_stringbuf(log_configs[i],
1035                                 "ancestor-or-self::node()/@path",
1036                                 path, sizeof(path))) {
1037       path[0] = '\0';
1038     }
1039     config = noit_conf_get_hash(log_configs[i],
1040                                 "ancestor-or-self::node()/config");
1041     ls = noit_log_stream_new(name, type[0] ? type : NULL,
1042                              path[0] ? path : NULL, NULL, config);
1043     if(!ls) {
1044       fprintf(stderr, "Error configuring log: %s[%s:%s]\n", name, type, path);
1045       exit(-1);
1046     }
1047
1048     if(noit_conf_get_boolean(log_configs[i],
1049                              "ancestor-or-self::node()/@disabled",
1050                              &disabled) && disabled)
1051       ls->enabled = 0;
1052      
1053     if(noit_conf_get_boolean(log_configs[i],
1054                              "ancestor-or-self::node()/@debug",
1055                              &debug) && debug)
1056       ls->debug = 1;
1057      
1058     if(noit_conf_get_boolean(log_configs[i],
1059                              "ancestor-or-self::node()/@timestamps",
1060                              &timestamps))
1061       ls->timestamps = timestamps ? 1 : 0;
1062  
1063     outlets = noit_conf_get_sections(log_configs[i],
1064                                      "ancestor-or-self::node()/outlet", &ocnt);
1065     noitL(noit_debug, "Found %d outlets for log '%s'\n", ocnt, name);
1066
1067     for(o=0; o<ocnt; o++) {
1068       noit_log_stream_t outlet;
1069       char oname[256];
1070       noit_conf_get_stringbuf(outlets[o], "@name",
1071                               oname, sizeof(oname));
1072       outlet = noit_log_stream_find(oname);
1073       if(!outlet) {
1074         fprintf(stderr, "Cannot find outlet '%s' for %s[%s:%s]\n", oname,
1075               name, type, path);
1076         exit(-1);
1077       }
1078       else
1079         noit_log_stream_add_stream(ls, outlet);
1080     }
1081     if(outlets) free(outlets);
1082   }
1083   if(log_configs) free(log_configs);
1084   if(noit_conf_log_init_rotate(toplevel, noit_true)) exit(-1);
1085 }
1086
1087 static void
1088 conf_t_userdata_free(void *data) {
1089   noit_conf_t_userdata_t *info = data;
1090   if(info) {
1091     if(info->path) free(info->path);
1092     free(info);
1093   }
1094 }
1095
1096 static int
1097 noit_console_state_conf_terminal(noit_console_closure_t ncct,
1098                                  int argc, char **argv,
1099                                  noit_console_state_t *state, void *closure) {
1100   noit_conf_t_userdata_t *info;
1101   if(argc) {
1102     nc_printf(ncct, "extra arguments not expected.\n");
1103     return -1;
1104   }
1105   info = calloc(1, sizeof(*info));
1106   info->path = strdup("/");
1107   noit_console_userdata_set(ncct, NOIT_CONF_T_USERDATA, info,
1108                             conf_t_userdata_free);
1109   noit_console_state_push_state(ncct, state);
1110   noit_console_state_init(ncct);
1111   return 0;
1112 }
1113 static int
1114 noit_console_config_section(noit_console_closure_t ncct,
1115                             int argc, char **argv,
1116                             noit_console_state_t *state, void *closure) {
1117   const char *err = "internal error";
1118   char *path, xpath[1024];
1119   noit_conf_t_userdata_t *info;
1120   xmlXPathObjectPtr pobj = NULL;
1121   xmlXPathContextPtr xpath_ctxt = NULL;
1122   xmlNodePtr node = NULL, newnode;
1123   vpsized_int delete = (vpsized_int)closure;
1124
1125   noit_conf_xml_xpath(NULL, &xpath_ctxt);
1126   if(argc != 1) {
1127     nc_printf(ncct, "requires one argument\n");
1128     return -1;
1129   }
1130   if(strchr(argv[0], '/')) {
1131     nc_printf(ncct, "invalid section name\n");
1132     return -1;
1133   }
1134   if(!strcmp(argv[0], "check") ||
1135      !strcmp(argv[0], "noit") ||
1136      !strcmp(argv[0], "filterset") ||
1137      !strcmp(argv[0], "config")) {
1138     nc_printf(ncct, "%s is reserved.\n", argv[0]);
1139     return -1;
1140   }
1141   info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
1142   if(!strcmp(info->path, "/")) {
1143     nc_printf(ncct, "manipulation of toplevel section disallowed\n");
1144     return -1;
1145   }
1146
1147   if(delete) {
1148     /* We cannot delete if we have checks */
1149     snprintf(xpath, sizeof(xpath), "/%s%s/%s//check", root_node_name,
1150              info->path, argv[0]);
1151     pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
1152     if(!pobj || pobj->type != XPATH_NODESET ||
1153        !xmlXPathNodeSetIsEmpty(pobj->nodesetval)) {
1154       err = "cannot delete section, has checks";
1155       goto bad;
1156     }
1157     if(pobj) xmlXPathFreeObject(pobj);
1158   }
1159
1160   snprintf(xpath, sizeof(xpath), "/%s%s/%s", root_node_name,
1161            info->path, argv[0]);
1162   pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
1163   if(!pobj || pobj->type != XPATH_NODESET) {
1164     err = "internal error: cannot detect section";
1165     goto bad;
1166   }
1167   if(!delete && !xmlXPathNodeSetIsEmpty(pobj->nodesetval)) {
1168     if(xmlXPathNodeSetGetLength(pobj->nodesetval) == 1) {
1169       node = xmlXPathNodeSetItem(pobj->nodesetval, 0);
1170       if(info->path) free(info->path);
1171       info->path = strdup((char *)xmlGetNodePath(node) +
1172                           1 + strlen(root_node_name));
1173       goto cdout;
1174     }
1175     err = "cannot create section";
1176     goto bad;
1177   }
1178   if(delete && xmlXPathNodeSetIsEmpty(pobj->nodesetval)) {
1179     err = "no such section";
1180     goto bad;
1181   }
1182   if(delete) {
1183     node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
1184     xmlUnlinkNode(node);
1185     noit_conf_mark_changed();
1186     return 0;
1187   }
1188   if(pobj) xmlXPathFreeObject(pobj);
1189   pobj = NULL;
1190
1191   if(!strcmp(argv[0],"include")) {
1192     err = "include is a reserved section name";
1193     goto bad;
1194   }
1195   path = strcmp(info->path, "/") ? info->path : "";
1196   snprintf(xpath, sizeof(xpath), "/%s%s", root_node_name, path);
1197   pobj = xmlXPathEval((xmlChar *)xpath, xpath_ctxt);
1198   if(!pobj || pobj->type != XPATH_NODESET ||
1199      xmlXPathNodeSetGetLength(pobj->nodesetval) != 1) {
1200     err = "path invalid?";
1201     goto bad;
1202   }
1203   node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
1204   if((newnode = xmlNewChild(node, NULL, (xmlChar *)argv[0], NULL)) != NULL) {
1205     noit_conf_mark_changed();
1206     if(info->path) free(info->path);
1207     info->path = strdup((char *)xmlGetNodePath(newnode) + 1 +
1208                         strlen(root_node_name));
1209   }
1210   else {
1211     err = "failed to create section";
1212     goto bad;
1213   }
1214  cdout:
1215   if(pobj) xmlXPathFreeObject(pobj);
1216   return 0;
1217  bad:
1218   if(pobj) xmlXPathFreeObject(pobj);
1219   nc_printf(ncct, "%s\n", err);
1220   return -1;
1221 }
1222
1223 int
1224 noit_console_generic_show(noit_console_closure_t ncct,
1225                           int argc, char **argv,
1226                           noit_console_state_t *state, void *closure) {
1227   int i, cnt, titled = 0, cliplen = 0;
1228   const char *path = "", *basepath = NULL;
1229   char xpath[1024];
1230   noit_conf_t_userdata_t *info = NULL;
1231   xmlXPathObjectPtr pobj = NULL;
1232   xmlXPathContextPtr xpath_ctxt = NULL, current_ctxt;
1233   xmlDocPtr master_config = NULL;
1234   xmlNodePtr node = NULL;
1235
1236   noit_conf_xml_xpath(&master_config, &xpath_ctxt);
1237   if(argc > 1) {
1238     nc_printf(ncct, "too many arguments\n");
1239     return -1;
1240   }
1241
1242   info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
1243   if(info && info->path) path = basepath = info->path;
1244   if(!info && argc == 0) {
1245     nc_printf(ncct, "argument required when not in configuration mode\n");
1246     return -1;
1247   }
1248
1249   if(argc == 1) path = argv[0];
1250   if(!basepath) basepath = path;
1251
1252   /* { / } is a special case */
1253   if(!strcmp(basepath, "/")) basepath = "";
1254   if(!strcmp(path, "/")) path = "";
1255
1256   if(!master_config) {
1257     nc_printf(ncct, "no config\n");
1258     return -1;
1259   }
1260
1261   /* { / } is the only path that will end with a /
1262    * in XPath { / / * } means something _entirely different than { / * }
1263    * Ever notice how it is hard to describe xpath in C comments?
1264    */
1265   /* We don't want to show the root node */
1266   cliplen = strlen(root_node_name) + 2; /* /name/ */
1267
1268   /* If we are in configuration mode
1269    * and we are without an argument or the argument is absolute,
1270    * clip the current path off */
1271   if(info && (argc == 0 || path[0] != '/')) cliplen += strlen(basepath);
1272   if(!path[0] || path[0] == '/') /* base only, or absolute path requested */
1273     snprintf(xpath, sizeof(xpath), "/%s%s/@*", root_node_name, path);
1274   else
1275     snprintf(xpath, sizeof(xpath), "/%s%s/%s/@*", root_node_name,
1276              basepath, path);
1277
1278   current_ctxt = xpath_ctxt;
1279   pobj = xmlXPathEval((xmlChar *)xpath, current_ctxt);
1280   if(!pobj || pobj->type != XPATH_NODESET) {
1281     nc_printf(ncct, "no such object\n");
1282     goto bad;
1283   }
1284   cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
1285   titled = 0;
1286   for(i=0; i<cnt; i++) {
1287     node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
1288     if(node->children && node->children == xmlGetLastChild(node) &&
1289       xmlNodeIsText(node->children)) {
1290       if(!titled++) nc_printf(ncct, "== Section Settings ==\n");
1291       nc_printf(ncct, "%s: %s\n", xmlGetNodePath(node) + cliplen,
1292                 xmlXPathCastNodeToString(node->children));
1293     }
1294   }
1295   xmlXPathFreeObject(pobj);
1296
1297   /* _shorten string_ turning last { / @ * } to { / * } */
1298   if(!path[0] || path[0] == '/') /* base only, or absolute path requested */
1299     snprintf(xpath, sizeof(xpath), "/%s%s/*", root_node_name, path);
1300   else
1301     snprintf(xpath, sizeof(xpath), "/%s%s/%s/*",
1302              root_node_name, basepath, path);
1303   pobj = xmlXPathEval((xmlChar *)xpath, current_ctxt);
1304   if(!pobj || pobj->type != XPATH_NODESET) {
1305     nc_printf(ncct, "no such object\n");
1306     goto bad;
1307   }
1308   cnt = xmlXPathNodeSetGetLength(pobj->nodesetval);
1309   titled = 0;
1310   for(i=0; i<cnt; i++) {
1311     node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, i);
1312     if(!(node->children && node->children == xmlGetLastChild(node) &&
1313          xmlNodeIsText(node->children))) {
1314       if(!titled++) nc_printf(ncct, "== Subsections ==\n");
1315       nc_printf(ncct, "%s\n", xmlGetNodePath(node) + cliplen);
1316     }
1317   }
1318   xmlXPathFreeObject(pobj);
1319   return 0;
1320  bad:
1321   if(pobj) xmlXPathFreeObject(pobj);
1322   return -1;
1323 }
1324 int
1325 noit_console_config_cd(noit_console_closure_t ncct,
1326                        int argc, char **argv,
1327                        noit_console_state_t *state, void *closure) {
1328   const char *err = "internal error";
1329   char *path, xpath[1024];
1330   noit_conf_t_userdata_t *info;
1331   xmlXPathObjectPtr pobj = NULL;
1332   xmlXPathContextPtr xpath_ctxt = NULL, current_ctxt;
1333   xmlNodePtr node = NULL;
1334   char *dest;
1335
1336   noit_conf_xml_xpath(NULL, &xpath_ctxt);
1337   if(argc != 1 && !closure) {
1338     nc_printf(ncct, "requires one argument\n");
1339     return -1;
1340   }
1341   dest = argc ? argv[0] : (char *)closure;
1342   info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
1343   if(dest[0] == '/')
1344     snprintf(xpath, sizeof(xpath), "/%s%s", root_node_name, dest);
1345   else {
1346     snprintf(xpath, sizeof(xpath), "/%s%s/%s", root_node_name,
1347              info->path, dest);
1348   }
1349   if(xpath[strlen(xpath)-1] == '/') xpath[strlen(xpath)-1] = '\0';
1350
1351   current_ctxt = xpath_ctxt;
1352   pobj = xmlXPathEval((xmlChar *)xpath, current_ctxt);
1353   if(!pobj || pobj->type != XPATH_NODESET ||
1354      xmlXPathNodeSetIsEmpty(pobj->nodesetval)) {
1355     err = "no such section";
1356     goto bad;
1357   }
1358   if(xmlXPathNodeSetGetLength(pobj->nodesetval) > 1) {
1359     err = "ambiguous section";
1360     goto bad;
1361   }
1362
1363   node = (noit_conf_section_t)xmlXPathNodeSetItem(pobj->nodesetval, 0);
1364   if(!node) {
1365     err = "internal XML error";
1366     goto bad;
1367   }
1368   if(!strcmp((char *)node->name, "check") ||
1369      !strcmp((char *)node->name, "noit") ||
1370      !strcmp((char *)node->name, "filterset") ||
1371      !strcmp((char *)node->name, "config")) {
1372     err = "reserved word";
1373     goto bad;
1374   }
1375   path = (char *)xmlGetNodePath(node);
1376   if(strlen(path) < strlen(root_node_name) + 1 ||
1377      strncmp(path + 1, root_node_name, strlen(root_node_name)) ||
1378      (path[strlen(root_node_name) + 1] != '/' &&
1379       path[strlen(root_node_name) + 1] != '\0')) {
1380     err = "new path outside out tree";
1381     goto bad;
1382   }
1383   free(info->path);
1384   if(!strcmp(path + 1, root_node_name))
1385     info->path = strdup("/");
1386   else
1387     info->path = strdup((char *)xmlGetNodePath(node) + 1 +
1388                         strlen(root_node_name));
1389   if(pobj) xmlXPathFreeObject(pobj);
1390   if(closure) noit_console_state_pop(ncct, argc, argv, NULL, NULL);
1391   return 0;
1392  bad:
1393   if(pobj) xmlXPathFreeObject(pobj);
1394   nc_printf(ncct, "%s [%s]\n", err, xpath);
1395   return -1;
1396 }
1397
1398 char *
1399 conf_t_prompt(EditLine *el) {
1400   noit_console_closure_t ncct;
1401   noit_conf_t_userdata_t *info;
1402   static char *tl = "noit(conf)# ";
1403   static char *pfmt = "noit(conf:%s%s)# ";
1404   int path_len, max_len;
1405
1406   el_get(el, EL_USERDATA, (void *)&ncct);
1407   if(!ncct) return tl;
1408   info = noit_console_userdata_get(ncct, NOIT_CONF_T_USERDATA);
1409   if(!info) return tl;
1410
1411   path_len = strlen(info->path);
1412   max_len = sizeof(info->prompt) - (strlen(pfmt) - 4 /* %s%s */) - 1 /* \0 */;
1413   if(path_len > max_len)
1414     snprintf(info->prompt, sizeof(info->prompt),
1415              pfmt, "...", info->path + path_len - max_len + 3 /* ... */);
1416   else
1417     snprintf(info->prompt, sizeof(info->prompt), pfmt, "", info->path);
1418   return info->prompt;
1419 }
1420
1421 #define NEW_STATE(a) (a) = noit_console_state_alloc()
1422 #define ADD_CMD(a,cmd,func,ac,ss,c) \
1423   noit_console_state_add_cmd((a), \
1424     NCSCMD(cmd, func, ac, ss, c))
1425 #define DELEGATE_CMD(a,cmd,ac,ss) \
1426   noit_console_state_add_cmd((a), \
1427     NCSCMD(cmd, noit_console_state_delegate, ac, ss, NULL))
1428
1429 void noit_console_conf_init() {
1430   noit_console_state_t *tl, *_conf_state, *_conf_t_state,
1431                        *_write_state, *_unset_state;
1432
1433   tl = noit_console_state_initial();
1434
1435   /* write <terimal|memory|file> */
1436   NEW_STATE(_write_state);
1437   ADD_CMD(_write_state, "terminal", noit_conf_write_terminal, NULL, NULL, NULL);
1438   ADD_CMD(_write_state, "file", noit_conf_write_file_console, NULL, NULL, NULL);
1439   /* write memory?  It's to a file, but I like router syntax */
1440   ADD_CMD(_write_state, "memory", noit_conf_write_file_console, NULL, NULL, NULL);
1441
1442   NEW_STATE(_unset_state);
1443   ADD_CMD(_unset_state, "section",
1444           noit_console_config_section, NULL, NULL, (void *)1);
1445
1446   NEW_STATE(_conf_t_state);
1447   _conf_t_state->console_prompt_function = conf_t_prompt;
1448   noit_console_state_add_cmd(_conf_t_state, &console_command_exit);
1449
1450   ADD_CMD(_conf_t_state, "ls", noit_console_generic_show, NULL, NULL, NULL);
1451   ADD_CMD(_conf_t_state, "cd", noit_console_config_cd, NULL, NULL, NULL);
1452   ADD_CMD(_conf_t_state, "section",
1453           noit_console_config_section, NULL, NULL, (void *)0);
1454
1455   DELEGATE_CMD(_conf_t_state, "write",
1456                noit_console_opt_delegate, _write_state);
1457   DELEGATE_CMD(_conf_t_state, "no", noit_console_opt_delegate, _unset_state);
1458
1459   NEW_STATE(_conf_state);
1460   ADD_CMD(_conf_state, "terminal",
1461           noit_console_state_conf_terminal, NULL, _conf_t_state, NULL);
1462
1463   ADD_CMD(tl, "configure",
1464           noit_console_state_delegate, noit_console_opt_delegate,
1465           _conf_state, NULL);
1466   ADD_CMD(tl, "write",
1467           noit_console_state_delegate, noit_console_opt_delegate,
1468           _write_state, NULL);
1469 }
1470
Note: See TracBrowser for help on using the browser.