Add support for a custom user agent at compile-time
[collectd.git] / src / curl_xml.c
1 /**
2  * collectd - src/curl_xml.c
3  * Copyright (C) 2009,2010       Amit Gupta
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Amit Gupta <amit.gupta221 at gmail.com>
20  **/
21
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25 #include "configfile.h"
26 #include "utils_llist.h"
27
28 #include <libxml/parser.h>
29 #include <libxml/tree.h>
30 #include <libxml/xpath.h>
31 #include <libxml/xpathInternals.h>
32
33 #include <curl/curl.h>
34
35 #define CX_DEFAULT_HOST "localhost"
36
37 /*
38  * Private data structures
39  */
40 struct cx_values_s /* {{{ */
41 {
42   char path[DATA_MAX_NAME_LEN];
43   size_t path_len;
44 };
45 typedef struct cx_values_s cx_values_t;
46 /* }}} */
47
48 struct cx_xpath_s /* {{{ */
49 {
50   char *path;
51   char *type;
52   cx_values_t *values;
53   int values_len;
54   char *instance_prefix;
55   char *instance;
56   int is_table;
57   unsigned long magic;
58 };
59 typedef struct cx_xpath_s cx_xpath_t;
60 /* }}} */
61
62 struct cx_namespace_s /* {{{ */
63 {
64   char *prefix;
65   char *url;
66 };
67 typedef struct cx_namespace_s cx_namespace_t;
68 /* }}} */
69
70 struct cx_s /* {{{ */
71 {
72   char *instance;
73   char *host;
74
75   char *url;
76   char *user;
77   char *pass;
78   char *credentials;
79   _Bool verify_peer;
80   _Bool verify_host;
81   char *cacert;
82   char *post_body;
83   struct curl_slist *headers;
84
85   cx_namespace_t *namespaces;
86   size_t namespaces_num;
87
88   CURL *curl;
89   char curl_errbuf[CURL_ERROR_SIZE];
90   char *buffer;
91   size_t buffer_size;
92   size_t buffer_fill;
93
94   llist_t *list; /* list of xpath blocks */
95 };
96 typedef struct cx_s cx_t; /* }}} */
97
98 /*
99  * Private functions
100  */
101 static size_t cx_curl_callback (void *buf, /* {{{ */
102     size_t size, size_t nmemb, void *user_data)
103 {
104   size_t len = size * nmemb;
105   cx_t *db;
106
107   db = user_data;
108   if (db == NULL)
109   {
110     ERROR ("curl_xml plugin: cx_curl_callback: "
111            "user_data pointer is NULL.");
112     return (0);
113   }
114
115    if (len <= 0)
116     return (len);
117
118   if ((db->buffer_fill + len) >= db->buffer_size)
119   {
120     char *temp;
121
122     temp = (char *) realloc (db->buffer,
123                     db->buffer_fill + len + 1);
124     if (temp == NULL)
125     {
126       ERROR ("curl_xml plugin: realloc failed.");
127       return (0);
128     }
129     db->buffer = temp;
130     db->buffer_size = db->buffer_fill + len + 1;
131   }
132
133   memcpy (db->buffer + db->buffer_fill, (char *) buf, len);
134   db->buffer_fill += len;
135   db->buffer[db->buffer_fill] = 0;
136
137   return (len);
138 } /* }}} size_t cx_curl_callback */
139
140 static void cx_xpath_free (cx_xpath_t *xpath) /* {{{ */
141 {
142   if (xpath == NULL)
143     return;
144
145   sfree (xpath->path);
146   sfree (xpath->type);
147   sfree (xpath->instance_prefix);
148   sfree (xpath->instance);
149   sfree (xpath->values);
150   sfree (xpath);
151 } /* }}} void cx_xpath_free */
152
153 static void cx_list_free (llist_t *list) /* {{{ */
154 {
155   llentry_t *le;
156
157   le = llist_head (list);
158   while (le != NULL)
159   {
160     llentry_t *le_next;
161
162     le_next = le->next;
163
164     sfree (le->key);
165     cx_xpath_free (le->value);
166
167     le = le_next;
168   }
169
170   llist_destroy (list);
171   list = NULL;
172 } /* }}} void cx_list_free */
173
174 static void cx_free (void *arg) /* {{{ */
175 {
176   cx_t *db;
177   size_t i;
178
179   DEBUG ("curl_xml plugin: cx_free (arg = %p);", arg);
180
181   db = (cx_t *) arg;
182
183   if (db == NULL)
184     return;
185
186   if (db->curl != NULL)
187     curl_easy_cleanup (db->curl);
188   db->curl = NULL;
189
190   if (db->list != NULL)
191     cx_list_free (db->list);
192
193   sfree (db->buffer);
194   sfree (db->instance);
195   sfree (db->host);
196
197   sfree (db->url);
198   sfree (db->user);
199   sfree (db->pass);
200   sfree (db->credentials);
201   sfree (db->cacert);
202   sfree (db->post_body);
203   curl_slist_free_all (db->headers);
204
205   for (i = 0; i < db->namespaces_num; i++)
206   {
207     sfree (db->namespaces[i].prefix);
208     sfree (db->namespaces[i].url);
209   }
210   sfree (db->namespaces);
211
212   sfree (db);
213 } /* }}} void cx_free */
214
215 static int cx_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
216     oconfig_item_t *ci)
217 {
218   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
219   {
220     WARNING ("curl_xml plugin: `%s' needs exactly one string argument.", name);
221     return (-1);
222   }
223
224   *dest = curl_slist_append(*dest, ci->values[0].value.string);
225   if (*dest == NULL)
226     return (-1);
227
228   return (0);
229 } /* }}} int cx_config_append_string */
230
231 static int cx_check_type (const data_set_t *ds, cx_xpath_t *xpath) /* {{{ */
232 {
233   if (!ds)
234   {
235     WARNING ("curl_xml plugin: DataSet `%s' not defined.", xpath->type);
236     return (-1);
237   }
238
239   if (ds->ds_num != xpath->values_len)
240   {
241     WARNING ("curl_xml plugin: DataSet `%s' requires %i values, but config talks about %i",
242         xpath->type, ds->ds_num, xpath->values_len);
243     return (-1);
244   }
245
246   return (0);
247 } /* }}} cx_check_type */
248
249 static xmlXPathObjectPtr cx_evaluate_xpath (xmlXPathContextPtr xpath_ctx, /* {{{ */ 
250            xmlChar *expr)
251 {
252   xmlXPathObjectPtr xpath_obj;
253
254   /* XXX: When to free this? */
255   xpath_obj = xmlXPathEvalExpression(BAD_CAST expr, xpath_ctx);
256   if (xpath_obj == NULL)
257   {
258      WARNING ("curl_xml plugin: "
259                "Error unable to evaluate xpath expression \"%s\". Skipping...", expr);
260      return NULL;
261   }
262
263   return xpath_obj;
264 } /* }}} cx_evaluate_xpath */
265
266 static int cx_if_not_text_node (xmlNodePtr node) /* {{{ */
267 {
268   if (node->type == XML_TEXT_NODE || node->type == XML_ATTRIBUTE_NODE ||
269       node->type == XML_ELEMENT_NODE)
270     return (0);
271
272   WARNING ("curl_xml plugin: "
273            "Node \"%s\" doesn't seem to be a text node. Skipping...", node->name);
274   return -1;
275 } /* }}} cx_if_not_text_node */
276
277 static int cx_handle_single_value_xpath (xmlXPathContextPtr xpath_ctx, /* {{{ */
278     cx_xpath_t *xpath,
279     const data_set_t *ds, value_list_t *vl, int index)
280 {
281   xmlXPathObjectPtr values_node_obj;
282   xmlNodeSetPtr values_node;
283   int tmp_size;
284   char *node_value;
285
286   values_node_obj = cx_evaluate_xpath (xpath_ctx, BAD_CAST xpath->values[index].path);
287   if (values_node_obj == NULL)
288     return (-1); /* Error already logged. */
289
290   values_node = values_node_obj->nodesetval;
291   tmp_size = (values_node) ? values_node->nodeNr : 0;
292
293   if (tmp_size == 0)
294   {
295     WARNING ("curl_xml plugin: "
296         "relative xpath expression \"%s\" doesn't match any of the nodes. "
297         "Skipping...", xpath->values[index].path);
298     xmlXPathFreeObject (values_node_obj);
299     return (-1);
300   }
301
302   if (tmp_size > 1)
303   {
304     WARNING ("curl_xml plugin: "
305         "relative xpath expression \"%s\" is expected to return "
306         "only one node. Skipping...", xpath->values[index].path);
307     xmlXPathFreeObject (values_node_obj);
308     return (-1);
309   }
310
311   /* ignoring the element if other than textnode/attribute*/
312   if (cx_if_not_text_node(values_node->nodeTab[0]))
313   {
314     WARNING ("curl_xml plugin: "
315         "relative xpath expression \"%s\" is expected to return "
316         "only text/attribute node which is not the case. Skipping...", 
317         xpath->values[index].path);
318     xmlXPathFreeObject (values_node_obj);
319     return (-1);
320   }
321
322   node_value = (char *) xmlNodeGetContent(values_node->nodeTab[0]);
323   switch (ds->ds[index].type)
324   {
325     case DS_TYPE_COUNTER:
326       vl->values[index].counter = (counter_t) strtoull (node_value,
327           /* endptr = */ NULL, /* base = */ 0);
328       break;
329     case DS_TYPE_DERIVE:
330       vl->values[index].derive = (derive_t) strtoll (node_value,
331           /* endptr = */ NULL, /* base = */ 0);
332       break;
333     case DS_TYPE_ABSOLUTE:
334       vl->values[index].absolute = (absolute_t) strtoull (node_value,
335           /* endptr = */ NULL, /* base = */ 0);
336       break;
337     case DS_TYPE_GAUGE: 
338       vl->values[index].gauge = (gauge_t) strtod (node_value,
339           /* endptr = */ NULL);
340   }
341
342   /* free up object */
343   xmlXPathFreeObject (values_node_obj);
344
345   /* We have reached here which means that
346    * we have got something to work */
347   return (0);
348 } /* }}} int cx_handle_single_value_xpath */
349
350 static int cx_handle_all_value_xpaths (xmlXPathContextPtr xpath_ctx, /* {{{ */
351     cx_xpath_t *xpath,
352     const data_set_t *ds, value_list_t *vl)
353 {
354   value_t values[xpath->values_len];
355   int status;
356   int i;
357
358   assert (xpath->values_len > 0);
359   assert (xpath->values_len == vl->values_len);
360   assert (xpath->values_len == ds->ds_num);
361   vl->values = values;
362
363   for (i = 0; i < xpath->values_len; i++)
364   {
365     status = cx_handle_single_value_xpath (xpath_ctx, xpath, ds, vl, i);
366     if (status != 0)
367       return (-1); /* An error has been printed. */
368   } /* for (i = 0; i < xpath->values_len; i++) */
369
370   plugin_dispatch_values (vl);
371   vl->values = NULL;
372
373   return (0);
374 } /* }}} int cx_handle_all_value_xpaths */
375
376 static int cx_handle_instance_xpath (xmlXPathContextPtr xpath_ctx, /* {{{ */
377     cx_xpath_t *xpath, value_list_t *vl,
378     _Bool is_table)
379 {
380   xmlXPathObjectPtr instance_node_obj = NULL;
381   xmlNodeSetPtr instance_node = NULL;
382
383   memset (vl->type_instance, 0, sizeof (vl->type_instance));
384
385   /* If the base xpath returns more than one block, the result is assumed to be
386    * a table. The `Instance' option is not optional in this case. Check for the
387    * condition and inform the user. */
388   if (is_table && (vl->type_instance == NULL))
389   {
390     WARNING ("curl_xml plugin: "
391         "Base-XPath %s is a table (more than one result was returned), "
392         "but no instance-XPath has been defined.",
393         xpath->path);
394     return (-1);
395   }
396
397   /* instance has to be an xpath expression */
398   if (xpath->instance != NULL)
399   {
400     int tmp_size;
401
402     instance_node_obj = cx_evaluate_xpath (xpath_ctx, BAD_CAST xpath->instance);
403     if (instance_node_obj == NULL)
404       return (-1); /* error is logged already */
405
406     instance_node = instance_node_obj->nodesetval;
407     tmp_size = (instance_node) ? instance_node->nodeNr : 0;
408
409     if (tmp_size <= 0)
410     {
411       WARNING ("curl_xml plugin: "
412           "relative xpath expression for 'InstanceFrom' \"%s\" doesn't match "
413           "any of the nodes. Skipping the node.", xpath->instance);
414       xmlXPathFreeObject (instance_node_obj);
415       return (-1);
416     }
417
418     if (tmp_size > 1)
419     {
420       WARNING ("curl_xml plugin: "
421           "relative xpath expression for 'InstanceFrom' \"%s\" is expected "
422           "to return only one text node. Skipping the node.", xpath->instance);
423       xmlXPathFreeObject (instance_node_obj);
424       return (-1);
425     }
426
427     /* ignoring the element if other than textnode/attribute */
428     if (cx_if_not_text_node(instance_node->nodeTab[0]))
429     {
430       WARNING ("curl_xml plugin: "
431           "relative xpath expression \"%s\" is expected to return only text node "
432           "which is not the case. Skipping the node.", xpath->instance);
433       xmlXPathFreeObject (instance_node_obj);
434       return (-1);
435     }
436   } /* if (xpath->instance != NULL) */
437
438   if (xpath->instance_prefix != NULL)
439   {
440     if (instance_node != NULL)
441       ssnprintf (vl->type_instance, sizeof (vl->type_instance),"%s%s",
442           xpath->instance_prefix, (char *) xmlNodeGetContent(instance_node->nodeTab[0]));
443     else
444       sstrncpy (vl->type_instance, xpath->instance_prefix,
445           sizeof (vl->type_instance));
446   }
447   else
448   {
449     /* If instance_prefix and instance_node are NULL, then
450      * don't set the type_instance */
451     if (instance_node != NULL)
452       sstrncpy (vl->type_instance, (char *) xmlNodeGetContent(instance_node->nodeTab[0]),
453           sizeof (vl->type_instance));
454   }
455
456   /* Free `instance_node_obj' this late, because `instance_node' points to
457    * somewhere inside this structure. */
458   xmlXPathFreeObject (instance_node_obj);
459
460   return (0);
461 } /* }}} int cx_handle_instance_xpath */
462
463 static int  cx_handle_base_xpath (char const *plugin_instance, /* {{{ */
464     char const *host,
465     xmlXPathContextPtr xpath_ctx, const data_set_t *ds, 
466     char *base_xpath, cx_xpath_t *xpath)
467 {
468   int total_nodes;
469   int i;
470
471   xmlXPathObjectPtr base_node_obj = NULL;
472   xmlNodeSetPtr base_nodes = NULL;
473
474   value_list_t vl = VALUE_LIST_INIT;
475
476   base_node_obj = cx_evaluate_xpath (xpath_ctx, BAD_CAST base_xpath); 
477   if (base_node_obj == NULL)
478     return -1; /* error is logged already */
479
480   base_nodes = base_node_obj->nodesetval;
481   total_nodes = (base_nodes) ? base_nodes->nodeNr : 0;
482
483   if (total_nodes == 0)
484   {
485      ERROR ("curl_xml plugin: "
486               "xpath expression \"%s\" doesn't match any of the nodes. "
487               "Skipping the xpath block...", base_xpath);
488      xmlXPathFreeObject (base_node_obj);
489      return -1;
490   }
491
492   /* If base_xpath returned multiple results, then */
493   /* Instance in the xpath block is required */ 
494   if (total_nodes > 1 && xpath->instance == NULL)
495   {
496     ERROR ("curl_xml plugin: "
497              "InstanceFrom is must in xpath block since the base xpath expression \"%s\" "
498              "returned multiple results. Skipping the xpath block...", base_xpath);
499     return -1;
500   }
501
502   /* set the values for the value_list */
503   vl.values_len = ds->ds_num;
504   sstrncpy (vl.type, xpath->type, sizeof (vl.type));
505   sstrncpy (vl.plugin, "curl_xml", sizeof (vl.plugin));
506   sstrncpy (vl.host, (host != NULL) ? host : hostname_g, sizeof (vl.host));
507   if (plugin_instance != NULL)
508     sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); 
509
510   for (i = 0; i < total_nodes; i++)
511   {
512     int status;
513
514     xpath_ctx->node = base_nodes->nodeTab[i];
515
516     status = cx_handle_instance_xpath (xpath_ctx, xpath, &vl,
517         /* is_table = */ (total_nodes > 1));
518     if (status != 0)
519       continue; /* An error has already been reported. */
520
521     status = cx_handle_all_value_xpaths (xpath_ctx, xpath, ds, &vl);
522     if (status != 0)
523       continue; /* An error has been logged. */
524   } /* for (i = 0; i < total_nodes; i++) */
525
526   /* free up the allocated memory */
527   xmlXPathFreeObject (base_node_obj); 
528
529   return (0); 
530 } /* }}} cx_handle_base_xpath */
531
532 static int cx_handle_parsed_xml(xmlDocPtr doc, /* {{{ */ 
533                        xmlXPathContextPtr xpath_ctx, cx_t *db)
534 {
535   llentry_t *le;
536   const data_set_t *ds;
537   cx_xpath_t *xpath;
538   int status=-1;
539   
540
541   le = llist_head (db->list);
542   while (le != NULL)
543   {
544     /* get the ds */
545     xpath = (cx_xpath_t *) le->value;
546     ds = plugin_get_ds (xpath->type);
547
548     if ( (cx_check_type(ds, xpath) == 0) &&
549          (cx_handle_base_xpath(db->instance, db->host,
550                                xpath_ctx, ds, le->key, xpath) == 0) )
551       status = 0; /* we got atleast one success */
552
553     le = le->next;
554   } /* while (le != NULL) */
555
556   return status;
557 } /* }}} cx_handle_parsed_xml */
558
559 static int cx_parse_stats_xml(xmlChar* xml, cx_t *db) /* {{{ */
560 {
561   int status;
562   xmlDocPtr doc;
563   xmlXPathContextPtr xpath_ctx;
564   size_t i;
565
566   /* Load the XML */
567   doc = xmlParseDoc(xml);
568   if (doc == NULL)
569   {
570     ERROR ("curl_xml plugin: Failed to parse the xml document  - %s", xml);
571     return (-1);
572   }
573
574   xpath_ctx = xmlXPathNewContext(doc);
575   if(xpath_ctx == NULL)
576   {
577     ERROR ("curl_xml plugin: Failed to create the xml context");
578     xmlFreeDoc(doc);
579     return (-1);
580   }
581
582   for (i = 0; i < db->namespaces_num; i++)
583   {
584     cx_namespace_t const *ns = db->namespaces + i;
585     status = xmlXPathRegisterNs (xpath_ctx,
586         BAD_CAST ns->prefix, BAD_CAST ns->url);
587     if (status != 0)
588     {
589       ERROR ("curl_xml plugin: "
590           "unable to register NS with prefix=\"%s\" and href=\"%s\"\n",
591           ns->prefix, ns->url);
592       xmlXPathFreeContext(xpath_ctx);
593       xmlFreeDoc (doc);
594       return (status);
595     }
596   }
597
598   status = cx_handle_parsed_xml (doc, xpath_ctx, db);
599   /* Cleanup */
600   xmlXPathFreeContext(xpath_ctx);
601   xmlFreeDoc(doc);
602   return status;
603 } /* }}} cx_parse_stats_xml */
604
605 static int cx_curl_perform (cx_t *db, CURL *curl) /* {{{ */
606 {
607   int status;
608   long rc;
609   char *ptr;
610   char *url;
611
612   db->buffer_fill = 0; 
613   status = curl_easy_perform (curl);
614   if (status != CURLE_OK)
615   {
616     ERROR ("curl_xml plugin: curl_easy_perform failed with status %i: %s (%s)",
617            status, db->curl_errbuf, url);
618     return (-1);
619   }
620
621   curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
622   curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
623
624   /* The response code is zero if a non-HTTP transport was used. */
625   if ((rc != 0) && (rc != 200))
626   {
627     ERROR ("curl_xml plugin: curl_easy_perform failed with response code %ld (%s)",
628            rc, url);
629     return (-1);
630   }
631
632   ptr = db->buffer;
633
634   status = cx_parse_stats_xml(BAD_CAST ptr, db);
635   db->buffer_fill = 0;
636
637   return status;
638 } /* }}} int cx_curl_perform */
639
640 static int cx_read (user_data_t *ud) /* {{{ */
641 {
642   cx_t *db;
643
644   if ((ud == NULL) || (ud->data == NULL))
645   {
646     ERROR ("curl_xml plugin: cx_read: Invalid user data.");
647     return (-1);
648   }
649
650   db = (cx_t *) ud->data;
651
652   return cx_curl_perform (db, db->curl);
653 } /* }}} int cx_read */
654
655 /* Configuration handling functions {{{ */
656
657 static int cx_config_add_values (const char *name, cx_xpath_t *xpath, /* {{{ */
658                                       oconfig_item_t *ci)
659 {
660   int i;
661
662   if (ci->values_num < 1)
663   {
664     WARNING ("curl_xml plugin: `ValuesFrom' needs at least one argument.");
665     return (-1);
666   }
667
668   for (i = 0; i < ci->values_num; i++)
669     if (ci->values[i].type != OCONFIG_TYPE_STRING)
670     {
671       WARNING ("curl_xml plugin: `ValuesFrom' needs only string argument.");
672       return (-1);
673     }
674
675   sfree (xpath->values);
676
677   xpath->values_len = 0;
678   xpath->values = (cx_values_t *) malloc (sizeof (cx_values_t) * ci->values_num);
679   if (xpath->values == NULL)
680     return (-1);
681   xpath->values_len = ci->values_num;
682
683   /* populate cx_values_t structure */
684   for (i = 0; i < ci->values_num; i++)
685   {
686     xpath->values[i].path_len = sizeof (ci->values[i].value.string);
687     sstrncpy (xpath->values[i].path, ci->values[i].value.string, sizeof (xpath->values[i].path));
688   }
689
690   return (0); 
691 } /* }}} cx_config_add_values */
692
693 static int cx_config_add_xpath (cx_t *db, /* {{{ */
694                                    oconfig_item_t *ci)
695 {
696   cx_xpath_t *xpath;
697   int status;
698   int i;
699
700   xpath = (cx_xpath_t *) malloc (sizeof (*xpath));
701   if (xpath == NULL)
702   {
703     ERROR ("curl_xml plugin: malloc failed.");
704     return (-1);
705   }
706   memset (xpath, 0, sizeof (*xpath));
707
708   status = cf_util_get_string (ci, &xpath->path);
709   if (status != 0)
710   {
711     sfree (xpath);
712     return (status);
713   }
714
715   /* error out if xpath->path is an empty string */
716   if (*xpath->path == 0)
717   {
718     ERROR ("curl_xml plugin: invalid xpath. "
719            "xpath value can't be an empty string");
720     return (-1);
721   }
722
723   status = 0;
724   for (i = 0; i < ci->children_num; i++)
725   {
726     oconfig_item_t *child = ci->children + i;
727
728     if (strcasecmp ("Type", child->key) == 0)
729       status = cf_util_get_string (child, &xpath->type);
730     else if (strcasecmp ("InstancePrefix", child->key) == 0)
731       status = cf_util_get_string (child, &xpath->instance_prefix);
732     else if (strcasecmp ("InstanceFrom", child->key) == 0)
733       status = cf_util_get_string (child, &xpath->instance);
734     else if (strcasecmp ("ValuesFrom", child->key) == 0)
735       status = cx_config_add_values ("ValuesFrom", xpath, child);
736     else
737     {
738       WARNING ("curl_xml plugin: Option `%s' not allowed here.", child->key);
739       status = -1;
740     }
741
742     if (status != 0)
743       break;
744   } /* for (i = 0; i < ci->children_num; i++) */
745
746   if (status == 0 && xpath->type == NULL)
747   {
748     WARNING ("curl_xml plugin: `Type' missing in `xpath' block.");
749     status = -1;
750   }
751
752   if (status == 0)
753   {
754     char *name;
755     llentry_t *le;
756
757     if (db->list == NULL)
758     {
759       db->list = llist_create();
760       if (db->list == NULL)
761       {
762         ERROR ("curl_xml plugin: list creation failed.");
763         return (-1);
764       }
765     }
766
767     name = strdup(xpath->path);
768     if (name == NULL)
769     {
770         ERROR ("curl_xml plugin: strdup failed.");
771         return (-1);
772     }
773
774     le = llentry_create (name, xpath);
775     if (le == NULL)
776     {
777       ERROR ("curl_xml plugin: llentry_create failed.");
778       return (-1);
779     }
780
781     llist_append (db->list, le);
782   }
783
784   return (status);
785 } /* }}} int cx_config_add_xpath */
786
787 static int cx_config_add_namespace (cx_t *db, /* {{{ */
788     oconfig_item_t *ci)
789 {
790   cx_namespace_t *ns;
791
792   if ((ci->values_num != 2)
793       || (ci->values[0].type != OCONFIG_TYPE_STRING)
794       || (ci->values[1].type != OCONFIG_TYPE_STRING))
795   {
796     WARNING ("curl_xml plugin: The `Namespace' option "
797              "needs exactly two string arguments.");
798     return (EINVAL);
799   }
800
801   ns = realloc (db->namespaces, sizeof (*db->namespaces)
802       * (db->namespaces_num + 1));
803   if (ns == NULL)
804   {
805     ERROR ("curl_xml plugin: realloc failed.");
806     return (ENOMEM);
807   }
808   db->namespaces = ns;
809   ns = db->namespaces + db->namespaces_num;
810   memset (ns, 0, sizeof (*ns));
811
812   ns->prefix = strdup (ci->values[0].value.string);
813   ns->url = strdup (ci->values[1].value.string);
814
815   if ((ns->prefix == NULL) || (ns->url == NULL))
816   {
817     sfree (ns->prefix);
818     sfree (ns->url);
819     ERROR ("curl_xml plugin: strdup failed.");
820     return (ENOMEM);
821   }
822
823   db->namespaces_num++;
824   return (0);
825 } /* }}} int cx_config_add_namespace */
826
827 /* Initialize db->curl */
828 static int cx_init_curl (cx_t *db) /* {{{ */
829 {
830   db->curl = curl_easy_init ();
831   if (db->curl == NULL)
832   {
833     ERROR ("curl_xml plugin: curl_easy_init failed.");
834     return (-1);
835   }
836
837   curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
838   curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cx_curl_callback);
839   curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
840   curl_easy_setopt (db->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
841   curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
842   curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
843
844   if (db->user != NULL)
845   {
846     size_t credentials_size;
847
848     credentials_size = strlen (db->user) + 2;
849     if (db->pass != NULL)
850       credentials_size += strlen (db->pass);
851
852     db->credentials = (char *) malloc (credentials_size);
853     if (db->credentials == NULL)
854     {
855       ERROR ("curl_xml plugin: malloc failed.");
856       return (-1);
857     }
858
859     ssnprintf (db->credentials, credentials_size, "%s:%s",
860                db->user, (db->pass == NULL) ? "" : db->pass);
861     curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
862   }
863
864   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, db->verify_peer ? 1L : 0L);
865   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
866                     db->verify_host ? 2L : 0L);
867   if (db->cacert != NULL)
868     curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
869   if (db->headers != NULL)
870     curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
871   if (db->post_body != NULL)
872     curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
873
874   return (0);
875 } /* }}} int cx_init_curl */
876
877 static int cx_config_add_url (oconfig_item_t *ci) /* {{{ */
878 {
879   cx_t *db;
880   int status = 0;
881   int i;
882
883   if ((ci->values_num != 1)
884       || (ci->values[0].type != OCONFIG_TYPE_STRING))
885   {
886     WARNING ("curl_xml plugin: The `URL' block "
887              "needs exactly one string argument.");
888     return (-1);
889   }
890
891   db = (cx_t *) malloc (sizeof (*db));
892   if (db == NULL)
893   {
894     ERROR ("curl_xml plugin: malloc failed.");
895     return (-1);
896   }
897   memset (db, 0, sizeof (*db));
898
899   if (strcasecmp ("URL", ci->key) == 0)
900   {
901     status = cf_util_get_string (ci, &db->url);
902     if (status != 0)
903     {
904       sfree (db);
905       return (status);
906     }
907   }
908   else
909   {
910     ERROR ("curl_xml plugin: cx_config: "
911            "Invalid key: %s", ci->key);
912     return (-1);
913   }
914
915   /* Fill the `cx_t' structure.. */
916   for (i = 0; i < ci->children_num; i++)
917   {
918     oconfig_item_t *child = ci->children + i;
919
920     if (strcasecmp ("Instance", child->key) == 0)
921       status = cf_util_get_string (child, &db->instance);
922     else if (strcasecmp ("Host", child->key) == 0)
923       status = cf_util_get_string (child, &db->host);
924     else if (strcasecmp ("User", child->key) == 0)
925       status = cf_util_get_string (child, &db->user);
926     else if (strcasecmp ("Password", child->key) == 0)
927       status = cf_util_get_string (child, &db->pass);
928     else if (strcasecmp ("VerifyPeer", child->key) == 0)
929       status = cf_util_get_boolean (child, &db->verify_peer);
930     else if (strcasecmp ("VerifyHost", child->key) == 0)
931       status = cf_util_get_boolean (child, &db->verify_host);
932     else if (strcasecmp ("CACert", child->key) == 0)
933       status = cf_util_get_string (child, &db->cacert);
934     else if (strcasecmp ("xpath", child->key) == 0)
935       status = cx_config_add_xpath (db, child);
936     else if (strcasecmp ("Header", child->key) == 0)
937       status = cx_config_append_string ("Header", &db->headers, child);
938     else if (strcasecmp ("Post", child->key) == 0)
939       status = cf_util_get_string (child, &db->post_body);
940     else if (strcasecmp ("Namespace", child->key) == 0)
941       status = cx_config_add_namespace (db, child);
942     else
943     {
944       WARNING ("curl_xml plugin: Option `%s' not allowed here.", child->key);
945       status = -1;
946     }
947
948     if (status != 0)
949       break;
950   }
951
952   if (status == 0)
953   {
954     if (db->list == NULL)
955     {
956       WARNING ("curl_xml plugin: No (valid) `Key' block "
957                "within `URL' block `%s'.", db->url);
958       status = -1;
959     }
960     if (status == 0)
961       status = cx_init_curl (db);
962   }
963
964   /* If all went well, register this database for reading */
965   if (status == 0)
966   {
967     user_data_t ud;
968     char *cb_name;
969
970     if (db->instance == NULL)
971       db->instance = strdup("default");
972
973     DEBUG ("curl_xml plugin: Registering new read callback: %s",
974            db->instance);
975
976     memset (&ud, 0, sizeof (ud));
977     ud.data = (void *) db;
978     ud.free_func = cx_free;
979
980     cb_name = ssnprintf_alloc ("curl_xml-%s-%s", db->instance, db->url);
981     plugin_register_complex_read (/* group = */ "curl_xml", cb_name, cx_read,
982                                   /* interval = */ NULL, &ud);
983     sfree (cb_name);
984   }
985   else
986   {
987     cx_free (db);
988     return (-1);
989   }
990
991   return (0);
992 } /* }}} int cx_config_add_url */
993
994 /* }}} End of configuration handling functions */
995
996 static int cx_config (oconfig_item_t *ci) /* {{{ */
997 {
998   int success;
999   int errors;
1000   int status;
1001   int i;
1002
1003   success = 0;
1004   errors = 0;
1005
1006   for (i = 0; i < ci->children_num; i++)
1007   {
1008     oconfig_item_t *child = ci->children + i;
1009
1010     if (strcasecmp ("URL", child->key) == 0)
1011     {
1012       status = cx_config_add_url (child);
1013       if (status == 0)
1014         success++;
1015       else
1016         errors++;
1017     }
1018     else
1019     {
1020       WARNING ("curl_xml plugin: Option `%s' not allowed here.", child->key);
1021       errors++;
1022     }
1023   }
1024
1025   if ((success == 0) && (errors > 0))
1026   {
1027     ERROR ("curl_xml plugin: All statements failed.");
1028     return (-1);
1029   }
1030
1031   return (0);
1032 } /* }}} int cx_config */
1033
1034 void module_register (void)
1035 {
1036   plugin_register_complex_config ("curl_xml", cx_config);
1037 } /* void module_register */
1038
1039 /* vim: set sw=2 sts=2 et fdm=marker : */