Merge branch 'collectd-5.8'
[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     /* this also frees xpath->path used for le->key */
161     cx_xpath_free(le->value);
162
163     le = le_next;
164   }
165
166   llist_destroy(list);
167 } /* }}} void cx_xpath_list_free */
168
169 static void cx_free(void *arg) /* {{{ */
170 {
171   cx_t *db;
172
173   DEBUG("curl_xml plugin: cx_free (arg = %p);", arg);
174
175   db = (cx_t *)arg;
176
177   if (db == NULL)
178     return;
179
180   if (db->curl != NULL)
181     curl_easy_cleanup(db->curl);
182   db->curl = NULL;
183
184   if (db->xpath_list != NULL)
185     cx_xpath_list_free(db->xpath_list);
186
187   sfree(db->buffer);
188   sfree(db->instance);
189   sfree(db->plugin_name);
190   sfree(db->host);
191
192   sfree(db->url);
193   sfree(db->user);
194   sfree(db->pass);
195   sfree(db->credentials);
196   sfree(db->cacert);
197   sfree(db->post_body);
198   curl_slist_free_all(db->headers);
199   curl_stats_destroy(db->stats);
200
201   for (size_t i = 0; i < db->namespaces_num; i++) {
202     sfree(db->namespaces[i].prefix);
203     sfree(db->namespaces[i].url);
204   }
205   sfree(db->namespaces);
206
207   sfree(db);
208 } /* }}} void cx_free */
209
210 static const char *cx_host(const cx_t *db) /* {{{ */
211 {
212   if (db->host == NULL)
213     return hostname_g;
214   return db->host;
215 } /* }}} cx_host */
216
217 static int cx_config_append_string(const char *name,
218                                    struct curl_slist **dest, /* {{{ */
219                                    oconfig_item_t *ci) {
220   struct curl_slist *temp = NULL;
221   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
222     WARNING("curl_xml plugin: `%s' needs exactly one string argument.", name);
223     return -1;
224   }
225
226   temp = curl_slist_append(*dest, ci->values[0].value.string);
227   if (temp == NULL)
228     return -1;
229
230   *dest = temp;
231
232   return 0;
233 } /* }}} int cx_config_append_string */
234
235 static int cx_check_type(const data_set_t *ds, cx_xpath_t *xpath) /* {{{ */
236 {
237   if (!ds) {
238     WARNING("curl_xml plugin: DataSet `%s' not defined.", xpath->type);
239     return -1;
240   }
241
242   if (ds->ds_num != xpath->values_len) {
243     WARNING("curl_xml plugin: DataSet `%s' requires %zu values, but config "
244             "talks about %zu",
245             xpath->type, ds->ds_num, xpath->values_len);
246     return -1;
247   }
248
249   return 0;
250 } /* }}} cx_check_type */
251
252 static xmlXPathObjectPtr cx_evaluate_xpath(xmlXPathContextPtr xpath_ctx,
253                                            char *expr) /* {{{ */
254 {
255   xmlXPathObjectPtr xpath_obj =
256       xmlXPathEvalExpression(BAD_CAST expr, xpath_ctx);
257   if (xpath_obj == NULL) {
258     WARNING("curl_xml plugin: "
259             "Error unable to evaluate xpath expression \"%s\". Skipping...",
260             expr);
261     return NULL;
262   }
263
264   return xpath_obj;
265 } /* }}} cx_evaluate_xpath */
266
267 static int cx_if_not_text_node(xmlNodePtr node) /* {{{ */
268 {
269   if (node->type == XML_TEXT_NODE || node->type == XML_ATTRIBUTE_NODE ||
270       node->type == XML_ELEMENT_NODE)
271     return 0;
272
273   WARNING("curl_xml plugin: "
274           "Node \"%s\" doesn't seem to be a text node. Skipping...",
275           node->name);
276   return -1;
277 } /* }}} cx_if_not_text_node */
278
279 /*
280  * Returned value should be freed with xmlFree().
281  */
282 static char *cx_get_text_node_value(xmlXPathContextPtr xpath_ctx, /* {{{ */
283                                     char *expr, const char *from_option) {
284   xmlXPathObjectPtr values_node_obj = cx_evaluate_xpath(xpath_ctx, expr);
285   if (values_node_obj == NULL)
286     return NULL; /* Error already logged. */
287
288   xmlNodeSetPtr values_node = values_node_obj->nodesetval;
289   size_t tmp_size = (values_node) ? values_node->nodeNr : 0;
290
291   if (tmp_size == 0) {
292     WARNING("curl_xml plugin: "
293             "relative xpath expression \"%s\" from '%s' doesn't match "
294             "any of the nodes.",
295             expr, from_option);
296     xmlXPathFreeObject(values_node_obj);
297     return NULL;
298   }
299
300   if (tmp_size > 1) {
301     WARNING("curl_xml plugin: "
302             "relative xpath expression \"%s\" from '%s' is expected to return "
303             "only one text node. Skipping the node.",
304             expr, from_option);
305     xmlXPathFreeObject(values_node_obj);
306     return NULL;
307   }
308
309   /* ignoring the element if other than textnode/attribute*/
310   if (cx_if_not_text_node(values_node->nodeTab[0])) {
311     WARNING("curl_xml plugin: "
312             "relative xpath expression \"%s\" from '%s' is expected to return "
313             "only text/attribute node which is not the case. "
314             "Skipping the node.",
315             expr, from_option);
316     xmlXPathFreeObject(values_node_obj);
317     return NULL;
318   }
319
320   char *node_value = (char *)xmlNodeGetContent(values_node->nodeTab[0]);
321
322   /* free up object */
323   xmlXPathFreeObject(values_node_obj);
324
325   return node_value;
326 } /* }}} char * cx_get_text_node_value */
327
328 static int cx_handle_single_value_xpath(xmlXPathContextPtr xpath_ctx, /* {{{ */
329                                         cx_xpath_t *xpath, const data_set_t *ds,
330                                         value_list_t *vl, int index) {
331
332   char *node_value = cx_get_text_node_value(
333       xpath_ctx, xpath->values[index].path, "ValuesFrom");
334
335   if (node_value == NULL)
336     return -1;
337
338   switch (ds->ds[index].type) {
339   case DS_TYPE_COUNTER:
340     vl->values[index].counter =
341         (counter_t)strtoull(node_value,
342                             /* endptr = */ NULL, /* base = */ 0);
343     break;
344   case DS_TYPE_DERIVE:
345     vl->values[index].derive =
346         (derive_t)strtoll(node_value,
347                           /* endptr = */ NULL, /* base = */ 0);
348     break;
349   case DS_TYPE_ABSOLUTE:
350     vl->values[index].absolute =
351         (absolute_t)strtoull(node_value,
352                              /* endptr = */ NULL, /* base = */ 0);
353     break;
354   case DS_TYPE_GAUGE:
355     vl->values[index].gauge = (gauge_t)strtod(node_value,
356                                               /* endptr = */ NULL);
357   }
358
359   xmlFree(node_value);
360
361   /* We have reached here which means that
362    * we have got something to work */
363   return 0;
364 } /* }}} int cx_handle_single_value_xpath */
365
366 static int cx_handle_all_value_xpaths(xmlXPathContextPtr xpath_ctx, /* {{{ */
367                                       cx_xpath_t *xpath, const data_set_t *ds,
368                                       value_list_t *vl) {
369   value_t values[xpath->values_len];
370
371   assert(xpath->values_len > 0);
372   assert(xpath->values_len == vl->values_len);
373   assert(xpath->values_len == ds->ds_num);
374   vl->values = values;
375
376   for (size_t i = 0; i < xpath->values_len; i++) {
377     if (cx_handle_single_value_xpath(xpath_ctx, xpath, ds, vl, i) != 0)
378       return -1; /* An error has been printed. */
379   }              /* for (i = 0; i < xpath->values_len; i++) */
380
381   plugin_dispatch_values(vl);
382   vl->values = NULL;
383
384   return 0;
385 } /* }}} int cx_handle_all_value_xpaths */
386
387 static int cx_handle_instance_xpath(xmlXPathContextPtr xpath_ctx, /* {{{ */
388                                     cx_xpath_t *xpath, value_list_t *vl) {
389
390   /* Handle type instance */
391   if (xpath->instance != NULL) {
392     char *node_value =
393         cx_get_text_node_value(xpath_ctx, xpath->instance, "InstanceFrom");
394     if (node_value == NULL)
395       return -1;
396
397     if (xpath->instance_prefix != NULL)
398       snprintf(vl->type_instance, sizeof(vl->type_instance), "%s%s",
399                xpath->instance_prefix, node_value);
400     else
401       sstrncpy(vl->type_instance, node_value, sizeof(vl->type_instance));
402
403     xmlFree(node_value);
404   } else if (xpath->instance_prefix != NULL)
405     sstrncpy(vl->type_instance, xpath->instance_prefix,
406              sizeof(vl->type_instance));
407
408   /* Handle plugin instance */
409   if (xpath->plugin_instance_from != NULL) {
410     char *node_value = cx_get_text_node_value(
411         xpath_ctx, xpath->plugin_instance_from, "PluginInstanceFrom");
412
413     if (node_value == NULL)
414       return -1;
415
416     sstrncpy(vl->plugin_instance, node_value, sizeof(vl->plugin_instance));
417     xmlFree(node_value);
418   }
419
420   return 0;
421 } /* }}} int cx_handle_instance_xpath */
422
423 static int cx_handle_xpath(const cx_t *db, /* {{{ */
424                            xmlXPathContextPtr xpath_ctx, cx_xpath_t *xpath) {
425
426   const data_set_t *ds = plugin_get_ds(xpath->type);
427   if (cx_check_type(ds, xpath) != 0)
428     return -1;
429
430   xmlXPathObjectPtr base_node_obj = cx_evaluate_xpath(xpath_ctx, xpath->path);
431   if (base_node_obj == NULL)
432     return -1; /* error is logged already */
433
434   xmlNodeSetPtr base_nodes = base_node_obj->nodesetval;
435   int total_nodes = (base_nodes) ? base_nodes->nodeNr : 0;
436
437   if (total_nodes == 0) {
438     ERROR("curl_xml plugin: "
439           "xpath expression \"%s\" doesn't match any of the nodes. "
440           "Skipping the xpath block...",
441           xpath->path);
442     xmlXPathFreeObject(base_node_obj);
443     return -1;
444   }
445
446   /* If base_xpath returned multiple results, then */
447   /* InstanceFrom or PluginInstanceFrom in the xpath block is required */
448   if (total_nodes > 1 && xpath->instance == NULL &&
449       xpath->plugin_instance_from == NULL) {
450     ERROR("curl_xml plugin: "
451           "InstanceFrom or PluginInstanceFrom is must in xpath block "
452           "since the base xpath expression \"%s\" "
453           "returned multiple results. Skipping the xpath block...",
454           xpath->path);
455     xmlXPathFreeObject(base_node_obj);
456     return -1;
457   }
458
459   value_list_t vl = VALUE_LIST_INIT;
460
461   /* set the values for the value_list */
462   vl.values_len = ds->ds_num;
463   sstrncpy(vl.type, xpath->type, sizeof(vl.type));
464   sstrncpy(vl.plugin, (db->plugin_name != NULL) ? db->plugin_name : "curl_xml",
465            sizeof(vl.plugin));
466   sstrncpy(vl.host, cx_host(db), sizeof(vl.host));
467
468   for (int i = 0; i < total_nodes; i++) {
469     xpath_ctx->node = base_nodes->nodeTab[i];
470
471     if (db->instance != NULL)
472       sstrncpy(vl.plugin_instance, db->instance, sizeof(vl.plugin_instance));
473
474     if (cx_handle_instance_xpath(xpath_ctx, xpath, &vl) != 0)
475       continue; /* An error has already been reported. */
476
477     if (cx_handle_all_value_xpaths(xpath_ctx, xpath, ds, &vl) != 0)
478       continue; /* An error has been logged. */
479   }             /* for (i = 0; i < total_nodes; i++) */
480
481   /* free up the allocated memory */
482   xmlXPathFreeObject(base_node_obj);
483
484   return 0;
485 } /* }}} cx_handle_xpath */
486
487 static int cx_handle_parsed_xml(cx_t *db, xmlDocPtr doc, /* {{{ */
488                                 xmlXPathContextPtr xpath_ctx) {
489   int status = -1;
490
491   llentry_t *le = llist_head(db->xpath_list);
492   while (le != NULL) {
493     cx_xpath_t *xpath = (cx_xpath_t *)le->value;
494
495     if (cx_handle_xpath(db, xpath_ctx, xpath) == 0)
496       status = 0; /* we got atleast one success */
497
498     le = le->next;
499   } /* while (le != NULL) */
500
501   return status;
502 } /* }}} cx_handle_parsed_xml */
503
504 static int cx_parse_xml(cx_t *db, char *xml) /* {{{ */
505 {
506   /* Load the XML */
507   xmlDocPtr doc = xmlParseDoc(BAD_CAST xml);
508   if (doc == NULL) {
509     ERROR("curl_xml plugin: Failed to parse the xml document  - %s", xml);
510     return -1;
511   }
512
513   xmlXPathContextPtr xpath_ctx = xmlXPathNewContext(doc);
514   if (xpath_ctx == NULL) {
515     ERROR("curl_xml plugin: Failed to create the xml context");
516     xmlFreeDoc(doc);
517     return -1;
518   }
519
520   for (size_t i = 0; i < db->namespaces_num; i++) {
521     cx_namespace_t const *ns = db->namespaces + i;
522     int status =
523         xmlXPathRegisterNs(xpath_ctx, BAD_CAST ns->prefix, BAD_CAST ns->url);
524     if (status != 0) {
525       ERROR("curl_xml plugin: "
526             "unable to register NS with prefix=\"%s\" and href=\"%s\"\n",
527             ns->prefix, ns->url);
528       xmlXPathFreeContext(xpath_ctx);
529       xmlFreeDoc(doc);
530       return status;
531     }
532   }
533
534   int status = cx_handle_parsed_xml(db, doc, xpath_ctx);
535   /* Cleanup */
536   xmlXPathFreeContext(xpath_ctx);
537   xmlFreeDoc(doc);
538   return status;
539 } /* }}} cx_parse_xml */
540
541 static int cx_read(user_data_t *ud) /* {{{ */
542 {
543   if ((ud == NULL) || (ud->data == NULL)) {
544     ERROR("curl_xml plugin: cx_read: Invalid user data.");
545     return -1;
546   }
547
548   long rc;
549   char *url;
550   cx_t *db = (cx_t *)ud->data;
551
552   db->buffer_fill = 0;
553
554   curl_easy_setopt(db->curl, CURLOPT_URL, db->url);
555
556   int status = curl_easy_perform(db->curl);
557   if (status != CURLE_OK) {
558     ERROR("curl_xml plugin: curl_easy_perform failed with status %i: %s (%s)",
559           status, db->curl_errbuf, db->url);
560     return -1;
561   }
562   if (db->stats != NULL)
563     curl_stats_dispatch(db->stats, db->curl, cx_host(db), "curl_xml",
564                         db->instance);
565
566   curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
567   curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
568
569   /* The response code is zero if a non-HTTP transport was used. */
570   if ((rc != 0) && (rc != 200)) {
571     ERROR(
572         "curl_xml plugin: curl_easy_perform failed with response code %ld (%s)",
573         rc, url);
574     return -1;
575   }
576
577   status = cx_parse_xml(db, db->buffer);
578   db->buffer_fill = 0;
579
580   return status;
581 } /* }}} int cx_read */
582
583 /* Configuration handling functions {{{ */
584
585 static int cx_config_add_values(const char *name, cx_xpath_t *xpath, /* {{{ */
586                                 oconfig_item_t *ci) {
587   if (ci->values_num < 1) {
588     WARNING("curl_xml plugin: `ValuesFrom' needs at least one argument.");
589     return -1;
590   }
591
592   for (int i = 0; i < ci->values_num; i++)
593     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
594       WARNING("curl_xml plugin: `ValuesFrom' needs only string argument.");
595       return -1;
596     }
597
598   sfree(xpath->values);
599
600   xpath->values_len = 0;
601   xpath->values = malloc(sizeof(cx_values_t) * ci->values_num);
602   if (xpath->values == NULL)
603     return -1;
604   xpath->values_len = (size_t)ci->values_num;
605
606   /* populate cx_values_t structure */
607   for (int i = 0; i < ci->values_num; i++) {
608     xpath->values[i].path_len = sizeof(ci->values[i].value.string);
609     sstrncpy(xpath->values[i].path, ci->values[i].value.string,
610              sizeof(xpath->values[i].path));
611   }
612
613   return 0;
614 } /* }}} cx_config_add_values */
615
616 static int cx_config_add_xpath(cx_t *db, oconfig_item_t *ci) /* {{{ */
617 {
618   cx_xpath_t *xpath = calloc(1, sizeof(*xpath));
619   if (xpath == NULL) {
620     ERROR("curl_xml plugin: calloc failed.");
621     return -1;
622   }
623
624   int status = cf_util_get_string(ci, &xpath->path);
625   if (status != 0) {
626     cx_xpath_free(xpath);
627     return status;
628   }
629
630   /* error out if xpath->path is an empty string */
631   if (strlen(xpath->path) == 0) {
632     ERROR("curl_xml plugin: invalid xpath. "
633           "xpath value can't be an empty string");
634     cx_xpath_free(xpath);
635     return -1;
636   }
637
638   status = 0;
639   for (int i = 0; i < ci->children_num; i++) {
640     oconfig_item_t *child = ci->children + i;
641
642     if (strcasecmp("Type", child->key) == 0)
643       status = cf_util_get_string(child, &xpath->type);
644     else if (strcasecmp("InstancePrefix", child->key) == 0)
645       status = cf_util_get_string(child, &xpath->instance_prefix);
646     else if (strcasecmp("InstanceFrom", child->key) == 0)
647       status = cf_util_get_string(child, &xpath->instance);
648     else if (strcasecmp("PluginInstanceFrom", child->key) == 0)
649       status = cf_util_get_string(child, &xpath->plugin_instance_from);
650     else if (strcasecmp("ValuesFrom", child->key) == 0)
651       status = cx_config_add_values("ValuesFrom", xpath, child);
652     else {
653       WARNING("curl_xml plugin: Option `%s' not allowed here.", child->key);
654       status = -1;
655     }
656
657     if (status != 0)
658       break;
659   } /* for (i = 0; i < ci->children_num; i++) */
660
661   if (status != 0) {
662     cx_xpath_free(xpath);
663     return status;
664   }
665
666   if (xpath->type == NULL) {
667     WARNING("curl_xml plugin: `Type' missing in `xpath' block.");
668     cx_xpath_free(xpath);
669     return -1;
670   }
671
672   if (xpath->values_len == 0) {
673     WARNING("curl_xml plugin: `ValuesFrom' missing in `xpath' block.");
674     cx_xpath_free(xpath);
675     return -1;
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   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->instance = strdup("default");
802   if (db->instance == NULL) {
803     ERROR("curl_xml plugin: strdup failed.");
804     sfree(db);
805     return -1;
806   }
807
808   db->xpath_list = llist_create();
809   if (db->xpath_list == NULL) {
810     ERROR("curl_xml plugin: list creation failed.");
811     sfree(db->instance);
812     sfree(db);
813     return -1;
814   }
815
816   db->timeout = -1;
817
818   int status = cf_util_get_string(ci, &db->url);
819   if (status != 0) {
820     llist_destroy(db->xpath_list);
821     sfree(db->instance);
822     sfree(db);
823     return status;
824   }
825
826   /* Fill the `cx_t' structure.. */
827   for (int i = 0; i < ci->children_num; i++) {
828     oconfig_item_t *child = ci->children + i;
829
830     if (strcasecmp("Instance", child->key) == 0)
831       status = cf_util_get_string(child, &db->instance);
832     else if (strcasecmp("Plugin", child->key) == 0)
833       status = cf_util_get_string(child, &db->plugin_name);
834     else if (strcasecmp("Host", child->key) == 0)
835       status = cf_util_get_string(child, &db->host);
836     else if (strcasecmp("User", child->key) == 0)
837       status = cf_util_get_string(child, &db->user);
838     else if (strcasecmp("Password", child->key) == 0)
839       status = cf_util_get_string(child, &db->pass);
840     else if (strcasecmp("Digest", child->key) == 0)
841       status = cf_util_get_boolean(child, &db->digest);
842     else if (strcasecmp("VerifyPeer", child->key) == 0)
843       status = cf_util_get_boolean(child, &db->verify_peer);
844     else if (strcasecmp("VerifyHost", child->key) == 0)
845       status = cf_util_get_boolean(child, &db->verify_host);
846     else if (strcasecmp("CACert", child->key) == 0)
847       status = cf_util_get_string(child, &db->cacert);
848     else if (strcasecmp("xpath", child->key) == 0)
849       status = cx_config_add_xpath(db, child);
850     else if (strcasecmp("Header", child->key) == 0)
851       status = cx_config_append_string("Header", &db->headers, child);
852     else if (strcasecmp("Post", child->key) == 0)
853       status = cf_util_get_string(child, &db->post_body);
854     else if (strcasecmp("Namespace", child->key) == 0)
855       status = cx_config_add_namespace(db, child);
856     else if (strcasecmp("Timeout", child->key) == 0)
857       status = cf_util_get_int(child, &db->timeout);
858     else if (strcasecmp("Statistics", child->key) == 0) {
859       db->stats = curl_stats_from_config(child);
860       if (db->stats == NULL)
861         status = -1;
862     } else {
863       WARNING("curl_xml plugin: Option `%s' not allowed here.", child->key);
864       status = -1;
865     }
866
867     if (status != 0)
868       break;
869   }
870
871   if (status != 0) {
872     cx_free(db);
873     return status;
874   }
875
876   if (llist_size(db->xpath_list) == 0) {
877     WARNING("curl_xml plugin: No `xpath' block within `URL' block `%s'.",
878             db->url);
879     cx_free(db);
880     return -1;
881   }
882
883   if (cx_init_curl(db) != 0) {
884     cx_free(db);
885     return -1;
886   }
887
888   /* If all went well, register this database for reading */
889   DEBUG("curl_xml plugin: Registering new read callback: %s", db->instance);
890
891   char *cb_name = ssnprintf_alloc("curl_xml-%s-%s", db->instance, db->url);
892
893   plugin_register_complex_read(/* group = */ "curl_xml", cb_name, cx_read,
894                                /* interval = */ 0,
895                                &(user_data_t){
896                                    .data = db, .free_func = cx_free,
897                                });
898   sfree(cb_name);
899   return 0;
900 } /* }}} int cx_config_add_url */
901
902 /* }}} End of configuration handling functions */
903
904 static int cx_config(oconfig_item_t *ci) /* {{{ */
905 {
906   int success = 0;
907   int errors = 0;
908
909   for (int i = 0; i < ci->children_num; i++) {
910     oconfig_item_t *child = ci->children + i;
911
912     if (strcasecmp("URL", child->key) == 0) {
913       if (cx_config_add_url(child) == 0)
914         success++;
915       else
916         errors++;
917     } else {
918       WARNING("curl_xml plugin: Option `%s' not allowed here.", child->key);
919       errors++;
920     }
921   }
922
923   if ((success == 0) && (errors > 0)) {
924     ERROR("curl_xml plugin: All statements failed.");
925     return -1;
926   }
927
928   return 0;
929 } /* }}} int cx_config */
930
931 static int cx_init(void) /* {{{ */
932 {
933   /* Call this while collectd is still single-threaded to avoid
934    * initialization issues in libgcrypt. */
935   curl_global_init(CURL_GLOBAL_SSL);
936   return 0;
937 } /* }}} int cx_init */
938
939 void module_register(void) {
940   plugin_register_complex_config("curl_xml", cx_config);
941   plugin_register_init("curl_xml", cx_init);
942 } /* void module_register */