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