curl_xml: Refactored via cx_get_text_node_value()
[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   memset(vl->type_instance, 0, sizeof(vl->type_instance));
387
388   /* Handle type instance */
389   if (xpath->instance != NULL) {
390     char *node_value = cx_get_text_node_value(xpath_ctx, xpath->instance,
391                                               "from 'InstanceFrom' ");
392     if (node_value == NULL)
393       return -1;
394
395     if (xpath->instance_prefix != NULL)
396       snprintf(vl->type_instance, sizeof(vl->type_instance), "%s%s",
397                xpath->instance_prefix, node_value);
398     else
399       sstrncpy(vl->type_instance, node_value, sizeof(vl->type_instance));
400
401     sfree(node_value);
402   } else if (xpath->instance_prefix != NULL)
403     sstrncpy(vl->type_instance, xpath->instance_prefix,
404              sizeof(vl->type_instance));
405
406   /* Handle plugin instance */
407   if (xpath->plugin_instance_from != NULL) {
408     char *node_value = cx_get_text_node_value(
409         xpath_ctx, xpath->plugin_instance_from, "from 'PluginInstanceFrom' ");
410
411     if (node_value == NULL)
412       return -1;
413
414     sstrncpy(vl->plugin_instance, node_value, sizeof(vl->plugin_instance));
415     sfree(node_value);
416   }
417
418   return 0;
419 } /* }}} int cx_handle_instance_xpath */
420
421 static int cx_handle_xpath(const cx_t *db, /* {{{ */
422                            xmlXPathContextPtr xpath_ctx, cx_xpath_t *xpath) {
423
424   const data_set_t *ds = plugin_get_ds(xpath->type);
425   if (cx_check_type(ds, xpath) != 0)
426     return -1;
427
428   xmlXPathObjectPtr base_node_obj = cx_evaluate_xpath(xpath_ctx, xpath->path);
429   if (base_node_obj == NULL)
430     return -1; /* error is logged already */
431
432   xmlNodeSetPtr base_nodes = base_node_obj->nodesetval;
433   int total_nodes = (base_nodes) ? base_nodes->nodeNr : 0;
434
435   if (total_nodes == 0) {
436     ERROR("curl_xml plugin: "
437           "xpath expression \"%s\" doesn't match any of the nodes. "
438           "Skipping the xpath block...",
439           xpath->path);
440     xmlXPathFreeObject(base_node_obj);
441     return -1;
442   }
443
444   /* If base_xpath returned multiple results, then */
445   /* InstanceFrom or PluginInstanceFrom in the xpath block is required */
446   if (total_nodes > 1 && xpath->instance == NULL &&
447       xpath->plugin_instance_from == NULL) {
448     ERROR("curl_xml plugin: "
449           "InstanceFrom or PluginInstanceFrom is must in xpath block "
450           "since the base xpath expression \"%s\" "
451           "returned multiple results. Skipping the xpath block...",
452           xpath->path);
453     return -1;
454   }
455
456   value_list_t vl = VALUE_LIST_INIT;
457
458   /* set the values for the value_list */
459   vl.values_len = ds->ds_num;
460   sstrncpy(vl.type, xpath->type, sizeof(vl.type));
461   sstrncpy(vl.plugin, (db->plugin_name != NULL) ? db->plugin_name : "curl_xml",
462            sizeof(vl.plugin));
463   sstrncpy(vl.host, cx_host(db), sizeof(vl.host));
464
465   for (int i = 0; i < total_nodes; i++) {
466     xpath_ctx->node = base_nodes->nodeTab[i];
467
468     if (db->instance != NULL)
469       sstrncpy(vl.plugin_instance, db->instance, sizeof(vl.plugin_instance));
470
471     if (cx_handle_instance_xpath(xpath_ctx, xpath, &vl) != 0)
472       continue; /* An error has already been reported. */
473
474     if (cx_handle_all_value_xpaths(xpath_ctx, xpath, ds, &vl) != 0)
475       continue; /* An error has been logged. */
476   }             /* for (i = 0; i < total_nodes; i++) */
477
478   /* free up the allocated memory */
479   xmlXPathFreeObject(base_node_obj);
480
481   return 0;
482 } /* }}} cx_handle_xpath */
483
484 static int cx_handle_parsed_xml(cx_t *db, xmlDocPtr doc, /* {{{ */
485                                 xmlXPathContextPtr xpath_ctx) {
486   int status = -1;
487
488   llentry_t *le = llist_head(db->xpath_list);
489   while (le != NULL) {
490     cx_xpath_t *xpath = (cx_xpath_t *)le->value;
491
492     if (cx_handle_xpath(db, xpath_ctx, xpath) == 0)
493       status = 0; /* we got atleast one success */
494
495     le = le->next;
496   } /* while (le != NULL) */
497
498   return status;
499 } /* }}} cx_handle_parsed_xml */
500
501 static int cx_parse_xml(cx_t *db, char *xml) /* {{{ */
502 {
503   /* Load the XML */
504   xmlDocPtr doc = xmlParseDoc(BAD_CAST xml);
505   if (doc == NULL) {
506     ERROR("curl_xml plugin: Failed to parse the xml document  - %s", xml);
507     return -1;
508   }
509
510   xmlXPathContextPtr xpath_ctx = xmlXPathNewContext(doc);
511   if (xpath_ctx == NULL) {
512     ERROR("curl_xml plugin: Failed to create the xml context");
513     xmlFreeDoc(doc);
514     return -1;
515   }
516
517   for (size_t i = 0; i < db->namespaces_num; i++) {
518     cx_namespace_t const *ns = db->namespaces + i;
519     int status =
520         xmlXPathRegisterNs(xpath_ctx, BAD_CAST ns->prefix, BAD_CAST ns->url);
521     if (status != 0) {
522       ERROR("curl_xml plugin: "
523             "unable to register NS with prefix=\"%s\" and href=\"%s\"\n",
524             ns->prefix, ns->url);
525       xmlXPathFreeContext(xpath_ctx);
526       xmlFreeDoc(doc);
527       return status;
528     }
529   }
530
531   int status = cx_handle_parsed_xml(db, doc, xpath_ctx);
532   /* Cleanup */
533   xmlXPathFreeContext(xpath_ctx);
534   xmlFreeDoc(doc);
535   return status;
536 } /* }}} cx_parse_xml */
537
538 static int cx_read(user_data_t *ud) /* {{{ */
539 {
540   if ((ud == NULL) || (ud->data == NULL)) {
541     ERROR("curl_xml plugin: cx_read: Invalid user data.");
542     return -1;
543   }
544
545   long rc;
546   char *url;
547   cx_t *db = (cx_t *)ud->data;
548
549   db->buffer_fill = 0;
550
551   curl_easy_setopt(db->curl, CURLOPT_URL, db->url);
552
553   int status = curl_easy_perform(db->curl);
554   if (status != CURLE_OK) {
555     ERROR("curl_xml plugin: curl_easy_perform failed with status %i: %s (%s)",
556           status, db->curl_errbuf, db->url);
557     return -1;
558   }
559   if (db->stats != NULL)
560     curl_stats_dispatch(db->stats, db->curl, cx_host(db), "curl_xml",
561                         db->instance);
562
563   curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
564   curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
565
566   /* The response code is zero if a non-HTTP transport was used. */
567   if ((rc != 0) && (rc != 200)) {
568     ERROR(
569         "curl_xml plugin: curl_easy_perform failed with response code %ld (%s)",
570         rc, url);
571     return -1;
572   }
573
574   status = cx_parse_xml(db, db->buffer);
575   db->buffer_fill = 0;
576
577   return status;
578 } /* }}} int cx_read */
579
580 /* Configuration handling functions {{{ */
581
582 static int cx_config_add_values(const char *name, cx_xpath_t *xpath, /* {{{ */
583                                 oconfig_item_t *ci) {
584   if (ci->values_num < 1) {
585     WARNING("curl_xml plugin: `ValuesFrom' needs at least one argument.");
586     return -1;
587   }
588
589   for (int i = 0; i < ci->values_num; i++)
590     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
591       WARNING("curl_xml plugin: `ValuesFrom' needs only string argument.");
592       return -1;
593     }
594
595   sfree(xpath->values);
596
597   xpath->values_len = 0;
598   xpath->values = malloc(sizeof(cx_values_t) * ci->values_num);
599   if (xpath->values == NULL)
600     return -1;
601   xpath->values_len = (size_t)ci->values_num;
602
603   /* populate cx_values_t structure */
604   for (int i = 0; i < ci->values_num; i++) {
605     xpath->values[i].path_len = sizeof(ci->values[i].value.string);
606     sstrncpy(xpath->values[i].path, ci->values[i].value.string,
607              sizeof(xpath->values[i].path));
608   }
609
610   return 0;
611 } /* }}} cx_config_add_values */
612
613 static int cx_config_add_xpath(cx_t *db, oconfig_item_t *ci) /* {{{ */
614 {
615   cx_xpath_t *xpath = calloc(1, sizeof(*xpath));
616   if (xpath == NULL) {
617     ERROR("curl_xml plugin: calloc failed.");
618     return -1;
619   }
620
621   int status = cf_util_get_string(ci, &xpath->path);
622   if (status != 0) {
623     cx_xpath_free(xpath);
624     return status;
625   }
626
627   /* error out if xpath->path is an empty string */
628   if (strlen(xpath->path) == 0) {
629     ERROR("curl_xml plugin: invalid xpath. "
630           "xpath value can't be an empty string");
631     cx_xpath_free(xpath);
632     return -1;
633   }
634
635   status = 0;
636   for (int i = 0; i < ci->children_num; i++) {
637     oconfig_item_t *child = ci->children + i;
638
639     if (strcasecmp("Type", child->key) == 0)
640       status = cf_util_get_string(child, &xpath->type);
641     else if (strcasecmp("InstancePrefix", child->key) == 0)
642       status = cf_util_get_string(child, &xpath->instance_prefix);
643     else if (strcasecmp("InstanceFrom", child->key) == 0)
644       status = cf_util_get_string(child, &xpath->instance);
645     else if (strcasecmp("PluginInstanceFrom", child->key) == 0)
646       status = cf_util_get_string(child, &xpath->plugin_instance_from);
647     else if (strcasecmp("ValuesFrom", child->key) == 0)
648       status = cx_config_add_values("ValuesFrom", xpath, child);
649     else {
650       WARNING("curl_xml plugin: Option `%s' not allowed here.", child->key);
651       status = -1;
652     }
653
654     if (status != 0)
655       break;
656   } /* for (i = 0; i < ci->children_num; i++) */
657
658   if (status != 0) {
659     cx_xpath_free(xpath);
660     return status;
661   }
662
663   if (xpath->type == NULL) {
664     WARNING("curl_xml plugin: `Type' missing in `xpath' block.");
665     cx_xpath_free(xpath);
666     return -1;
667   }
668
669   if (db->xpath_list == NULL) {
670     db->xpath_list = llist_create();
671     if (db->xpath_list == NULL) {
672       ERROR("curl_xml plugin: list creation failed.");
673       cx_xpath_free(xpath);
674       return -1;
675     }
676   }
677
678   llentry_t *le = llentry_create(xpath->path, xpath);
679   if (le == NULL) {
680     ERROR("curl_xml plugin: llentry_create failed.");
681     cx_xpath_free(xpath);
682     return -1;
683   }
684
685   llist_append(db->xpath_list, le);
686   return 0;
687 } /* }}} int cx_config_add_xpath */
688
689 static int cx_config_add_namespace(cx_t *db, /* {{{ */
690                                    oconfig_item_t *ci) {
691
692   if ((ci->values_num != 2) || (ci->values[0].type != OCONFIG_TYPE_STRING) ||
693       (ci->values[1].type != OCONFIG_TYPE_STRING)) {
694     WARNING("curl_xml plugin: The `Namespace' option "
695             "needs exactly two string arguments.");
696     return EINVAL;
697   }
698
699   cx_namespace_t *ns = realloc(
700       db->namespaces, sizeof(*db->namespaces) * (db->namespaces_num + 1));
701   if (ns == NULL) {
702     ERROR("curl_xml plugin: realloc failed.");
703     return ENOMEM;
704   }
705   db->namespaces = ns;
706   ns = db->namespaces + db->namespaces_num;
707   memset(ns, 0, sizeof(*ns));
708
709   ns->prefix = strdup(ci->values[0].value.string);
710   ns->url = strdup(ci->values[1].value.string);
711
712   if ((ns->prefix == NULL) || (ns->url == NULL)) {
713     sfree(ns->prefix);
714     sfree(ns->url);
715     ERROR("curl_xml plugin: strdup failed.");
716     return ENOMEM;
717   }
718
719   db->namespaces_num++;
720   return 0;
721 } /* }}} int cx_config_add_namespace */
722
723 /* Initialize db->curl */
724 static int cx_init_curl(cx_t *db) /* {{{ */
725 {
726   db->curl = curl_easy_init();
727   if (db->curl == NULL) {
728     ERROR("curl_xml plugin: curl_easy_init failed.");
729     return -1;
730   }
731
732   curl_easy_setopt(db->curl, CURLOPT_NOSIGNAL, 1L);
733   curl_easy_setopt(db->curl, CURLOPT_WRITEFUNCTION, cx_curl_callback);
734   curl_easy_setopt(db->curl, CURLOPT_WRITEDATA, db);
735   curl_easy_setopt(db->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
736   curl_easy_setopt(db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
737   curl_easy_setopt(db->curl, CURLOPT_FOLLOWLOCATION, 1L);
738   curl_easy_setopt(db->curl, CURLOPT_MAXREDIRS, 50L);
739
740   if (db->user != NULL) {
741 #ifdef HAVE_CURLOPT_USERNAME
742     curl_easy_setopt(db->curl, CURLOPT_USERNAME, db->user);
743     curl_easy_setopt(db->curl, CURLOPT_PASSWORD,
744                      (db->pass == NULL) ? "" : db->pass);
745 #else
746     size_t credentials_size;
747
748     credentials_size = strlen(db->user) + 2;
749     if (db->pass != NULL)
750       credentials_size += strlen(db->pass);
751
752     db->credentials = malloc(credentials_size);
753     if (db->credentials == NULL) {
754       ERROR("curl_xml plugin: malloc failed.");
755       return -1;
756     }
757
758     snprintf(db->credentials, credentials_size, "%s:%s", db->user,
759              (db->pass == NULL) ? "" : db->pass);
760     curl_easy_setopt(db->curl, CURLOPT_USERPWD, db->credentials);
761 #endif
762
763     if (db->digest)
764       curl_easy_setopt(db->curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
765   }
766
767   curl_easy_setopt(db->curl, CURLOPT_SSL_VERIFYPEER, db->verify_peer ? 1L : 0L);
768   curl_easy_setopt(db->curl, CURLOPT_SSL_VERIFYHOST, db->verify_host ? 2L : 0L);
769   if (db->cacert != NULL)
770     curl_easy_setopt(db->curl, CURLOPT_CAINFO, db->cacert);
771   if (db->headers != NULL)
772     curl_easy_setopt(db->curl, CURLOPT_HTTPHEADER, db->headers);
773   if (db->post_body != NULL)
774     curl_easy_setopt(db->curl, CURLOPT_POSTFIELDS, db->post_body);
775
776 #ifdef HAVE_CURLOPT_TIMEOUT_MS
777   if (db->timeout >= 0)
778     curl_easy_setopt(db->curl, CURLOPT_TIMEOUT_MS, (long)db->timeout);
779   else
780     curl_easy_setopt(db->curl, CURLOPT_TIMEOUT_MS,
781                      (long)CDTIME_T_TO_MS(plugin_get_interval()));
782 #endif
783
784   return 0;
785 } /* }}} int cx_init_curl */
786
787 static int cx_config_add_url(oconfig_item_t *ci) /* {{{ */
788 {
789   int status = 0;
790
791   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
792     WARNING("curl_xml plugin: The `URL' block "
793             "needs exactly one string argument.");
794     return -1;
795   }
796
797   cx_t *db = calloc(1, sizeof(*db));
798   if (db == NULL) {
799     ERROR("curl_xml plugin: calloc failed.");
800     return -1;
801   }
802
803   db->timeout = -1;
804
805   if (strcasecmp("URL", ci->key) == 0) {
806     status = cf_util_get_string(ci, &db->url);
807     if (status != 0) {
808       sfree(db);
809       return status;
810     }
811   } else {
812     ERROR("curl_xml plugin: cx_config: "
813           "Invalid key: %s",
814           ci->key);
815     cx_free(db);
816     return -1;
817   }
818
819   /* Fill the `cx_t' structure.. */
820   for (int i = 0; i < ci->children_num; i++) {
821     oconfig_item_t *child = ci->children + i;
822
823     if (strcasecmp("Instance", child->key) == 0)
824       status = cf_util_get_string(child, &db->instance);
825     else if (strcasecmp("Plugin", child->key) == 0)
826       status = cf_util_get_string(child, &db->plugin_name);
827     else if (strcasecmp("Host", child->key) == 0)
828       status = cf_util_get_string(child, &db->host);
829     else if (strcasecmp("User", child->key) == 0)
830       status = cf_util_get_string(child, &db->user);
831     else if (strcasecmp("Password", child->key) == 0)
832       status = cf_util_get_string(child, &db->pass);
833     else if (strcasecmp("Digest", child->key) == 0)
834       status = cf_util_get_boolean(child, &db->digest);
835     else if (strcasecmp("VerifyPeer", child->key) == 0)
836       status = cf_util_get_boolean(child, &db->verify_peer);
837     else if (strcasecmp("VerifyHost", child->key) == 0)
838       status = cf_util_get_boolean(child, &db->verify_host);
839     else if (strcasecmp("CACert", child->key) == 0)
840       status = cf_util_get_string(child, &db->cacert);
841     else if (strcasecmp("xpath", child->key) == 0)
842       status = cx_config_add_xpath(db, child);
843     else if (strcasecmp("Header", child->key) == 0)
844       status = cx_config_append_string("Header", &db->headers, child);
845     else if (strcasecmp("Post", child->key) == 0)
846       status = cf_util_get_string(child, &db->post_body);
847     else if (strcasecmp("Namespace", child->key) == 0)
848       status = cx_config_add_namespace(db, child);
849     else if (strcasecmp("Timeout", child->key) == 0)
850       status = cf_util_get_int(child, &db->timeout);
851     else if (strcasecmp("Statistics", child->key) == 0) {
852       db->stats = curl_stats_from_config(child);
853       if (db->stats == NULL)
854         status = -1;
855     } else {
856       WARNING("curl_xml plugin: Option `%s' not allowed here.", child->key);
857       status = -1;
858     }
859
860     if (status != 0)
861       break;
862   }
863
864   if (status == 0) {
865     if (db->xpath_list == NULL) {
866       WARNING("curl_xml plugin: No (valid) `xpath' block "
867               "within `URL' block `%s'.",
868               db->url);
869       status = -1;
870     }
871     if (status == 0)
872       status = cx_init_curl(db);
873   }
874
875   /* If all went well, register this database for reading */
876   if (status == 0) {
877     if (db->instance == NULL)
878       db->instance = strdup("default");
879
880     DEBUG("curl_xml plugin: Registering new read callback: %s", db->instance);
881
882     char *cb_name = ssnprintf_alloc("curl_xml-%s-%s", db->instance, db->url);
883
884     plugin_register_complex_read(/* group = */ "curl_xml", cb_name, cx_read,
885                                  /* interval = */ 0,
886                                  &(user_data_t){
887                                      .data = db, .free_func = cx_free,
888                                  });
889     sfree(cb_name);
890   } else {
891     cx_free(db);
892     return -1;
893   }
894
895   return 0;
896 } /* }}} int cx_config_add_url */
897
898 /* }}} End of configuration handling functions */
899
900 static int cx_config(oconfig_item_t *ci) /* {{{ */
901 {
902   int success = 0;
903   int errors = 0;
904
905   for (int i = 0; i < ci->children_num; i++) {
906     oconfig_item_t *child = ci->children + i;
907
908     if (strcasecmp("URL", child->key) == 0) {
909       if (cx_config_add_url(child) == 0)
910         success++;
911       else
912         errors++;
913     } else {
914       WARNING("curl_xml plugin: Option `%s' not allowed here.", child->key);
915       errors++;
916     }
917   }
918
919   if ((success == 0) && (errors > 0)) {
920     ERROR("curl_xml plugin: All statements failed.");
921     return -1;
922   }
923
924   return 0;
925 } /* }}} int cx_config */
926
927 static int cx_init(void) /* {{{ */
928 {
929   /* Call this while collectd is still single-threaded to avoid
930    * initialization issues in libgcrypt. */
931   curl_global_init(CURL_GLOBAL_SSL);
932   return 0;
933 } /* }}} int cx_init */
934
935 void module_register(void) {
936   plugin_register_complex_config("curl_xml", cx_config);
937   plugin_register_init("curl_xml", cx_init);
938 } /* void module_register */