curl_xml: Add ability to set plugin instance from XML data.
[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 *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   cx_t *db;
111
112   db = user_data;
113   if (db == NULL) {
114     ERROR("curl_xml plugin: cx_curl_callback: "
115           "user_data pointer is NULL.");
116     return 0;
117   }
118
119   if (len == 0)
120     return len;
121
122   if ((db->buffer_fill + len) >= db->buffer_size) {
123     char *temp;
124
125     temp = realloc(db->buffer, db->buffer_fill + len + 1);
126     if (temp == NULL) {
127       ERROR("curl_xml plugin: realloc failed.");
128       return 0;
129     }
130     db->buffer = temp;
131     db->buffer_size = db->buffer_fill + len + 1;
132   }
133
134   memcpy(db->buffer + db->buffer_fill, (char *)buf, len);
135   db->buffer_fill += len;
136   db->buffer[db->buffer_fill] = 0;
137
138   return len;
139 } /* }}} size_t cx_curl_callback */
140
141 static void cx_xpath_free(cx_xpath_t *xpath) /* {{{ */
142 {
143   if (xpath == NULL)
144     return;
145
146   sfree(xpath->path);
147   sfree(xpath->type);
148   sfree(xpath->instance_prefix);
149   sfree(xpath->plugin_instance_from);
150   sfree(xpath->instance);
151   sfree(xpath->values);
152   sfree(xpath);
153 } /* }}} void cx_xpath_free */
154
155 static void cx_list_free(llist_t *list) /* {{{ */
156 {
157   llentry_t *le;
158
159   le = llist_head(list);
160   while (le != NULL) {
161     llentry_t *le_next;
162
163     le_next = le->next;
164
165     sfree(le->key);
166     cx_xpath_free(le->value);
167
168     le = le_next;
169   }
170
171   llist_destroy(list);
172 } /* }}} void cx_list_free */
173
174 static void cx_free(void *arg) /* {{{ */
175 {
176   cx_t *db;
177
178   DEBUG("curl_xml plugin: cx_free (arg = %p);", arg);
179
180   db = (cx_t *)arg;
181
182   if (db == NULL)
183     return;
184
185   if (db->curl != NULL)
186     curl_easy_cleanup(db->curl);
187   db->curl = NULL;
188
189   if (db->list != NULL)
190     cx_list_free(db->list);
191
192   sfree(db->buffer);
193   sfree(db->instance);
194   sfree(db->plugin_name);
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   curl_stats_destroy(db->stats);
205
206   for (size_t i = 0; i < db->namespaces_num; i++) {
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 const char *cx_host(const cx_t *db) /* {{{ */
216 {
217   if (db->host == NULL)
218     return hostname_g;
219   return db->host;
220 } /* }}} cx_host */
221
222 static int cx_config_append_string(const char *name,
223                                    struct curl_slist **dest, /* {{{ */
224                                    oconfig_item_t *ci) {
225   struct curl_slist *temp = NULL;
226   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
227     WARNING("curl_xml plugin: `%s' needs exactly one string argument.", name);
228     return -1;
229   }
230
231   temp = curl_slist_append(*dest, ci->values[0].value.string);
232   if (temp == NULL)
233     return -1;
234
235   *dest = temp;
236
237   return 0;
238 } /* }}} int cx_config_append_string */
239
240 static int cx_check_type(const data_set_t *ds, cx_xpath_t *xpath) /* {{{ */
241 {
242   if (!ds) {
243     WARNING("curl_xml plugin: DataSet `%s' not defined.", xpath->type);
244     return -1;
245   }
246
247   if (ds->ds_num != xpath->values_len) {
248     WARNING("curl_xml plugin: DataSet `%s' requires %zu values, but config "
249             "talks about %zu",
250             xpath->type, ds->ds_num, xpath->values_len);
251     return -1;
252   }
253
254   return 0;
255 } /* }}} cx_check_type */
256
257 static xmlXPathObjectPtr
258 cx_evaluate_xpath(xmlXPathContextPtr xpath_ctx, /* {{{ */
259                   xmlChar *expr) {
260   xmlXPathObjectPtr xpath_obj;
261
262   /* XXX: When to free this? */
263   xpath_obj = xmlXPathEvalExpression(BAD_CAST expr, xpath_ctx);
264   if (xpath_obj == NULL) {
265     WARNING("curl_xml plugin: "
266             "Error unable to evaluate xpath expression \"%s\". Skipping...",
267             expr);
268     return NULL;
269   }
270
271   return xpath_obj;
272 } /* }}} cx_evaluate_xpath */
273
274 static int cx_if_not_text_node(xmlNodePtr node) /* {{{ */
275 {
276   if (node->type == XML_TEXT_NODE || node->type == XML_ATTRIBUTE_NODE ||
277       node->type == XML_ELEMENT_NODE)
278     return 0;
279
280   WARNING("curl_xml plugin: "
281           "Node \"%s\" doesn't seem to be a text node. Skipping...",
282           node->name);
283   return -1;
284 } /* }}} cx_if_not_text_node */
285
286 static int cx_handle_single_value_xpath(xmlXPathContextPtr xpath_ctx, /* {{{ */
287                                         cx_xpath_t *xpath, const data_set_t *ds,
288                                         value_list_t *vl, int index) {
289   xmlXPathObjectPtr values_node_obj;
290   xmlNodeSetPtr values_node;
291   int tmp_size;
292   char *node_value;
293
294   values_node_obj =
295       cx_evaluate_xpath(xpath_ctx, BAD_CAST xpath->values[index].path);
296   if (values_node_obj == NULL)
297     return -1; /* Error already logged. */
298
299   values_node = values_node_obj->nodesetval;
300   tmp_size = (values_node) ? values_node->nodeNr : 0;
301
302   if (tmp_size == 0) {
303     WARNING("curl_xml plugin: "
304             "relative xpath expression \"%s\" doesn't match any of the nodes. "
305             "Skipping...",
306             xpath->values[index].path);
307     xmlXPathFreeObject(values_node_obj);
308     return -1;
309   }
310
311   if (tmp_size > 1) {
312     WARNING("curl_xml plugin: "
313             "relative xpath expression \"%s\" is expected to return "
314             "only one node. Skipping...",
315             xpath->values[index].path);
316     xmlXPathFreeObject(values_node_obj);
317     return -1;
318   }
319
320   /* ignoring the element if other than textnode/attribute*/
321   if (cx_if_not_text_node(values_node->nodeTab[0])) {
322     WARNING("curl_xml plugin: "
323             "relative xpath expression \"%s\" is expected to return "
324             "only text/attribute node which is not the case. Skipping...",
325             xpath->values[index].path);
326     xmlXPathFreeObject(values_node_obj);
327     return -1;
328   }
329
330   node_value = (char *)xmlNodeGetContent(values_node->nodeTab[0]);
331   switch (ds->ds[index].type) {
332   case DS_TYPE_COUNTER:
333     vl->values[index].counter =
334         (counter_t)strtoull(node_value,
335                             /* endptr = */ NULL, /* base = */ 0);
336     break;
337   case DS_TYPE_DERIVE:
338     vl->values[index].derive =
339         (derive_t)strtoll(node_value,
340                           /* endptr = */ NULL, /* base = */ 0);
341     break;
342   case DS_TYPE_ABSOLUTE:
343     vl->values[index].absolute =
344         (absolute_t)strtoull(node_value,
345                              /* endptr = */ NULL, /* base = */ 0);
346     break;
347   case DS_TYPE_GAUGE:
348     vl->values[index].gauge = (gauge_t)strtod(node_value,
349                                               /* endptr = */ NULL);
350   }
351
352   /* free up object */
353   xmlXPathFreeObject(values_node_obj);
354   sfree(node_value);
355
356   /* We have reached here which means that
357    * we have got something to work */
358   return 0;
359 } /* }}} int cx_handle_single_value_xpath */
360
361 static int cx_handle_all_value_xpaths(xmlXPathContextPtr xpath_ctx, /* {{{ */
362                                       cx_xpath_t *xpath, const data_set_t *ds,
363                                       value_list_t *vl) {
364   value_t values[xpath->values_len];
365   int status;
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     status = cx_handle_single_value_xpath(xpath_ctx, xpath, ds, vl, i);
374     if (status != 0)
375       return -1; /* An error has been printed. */
376   }              /* for (i = 0; i < xpath->values_len; i++) */
377
378   plugin_dispatch_values(vl);
379   vl->values = NULL;
380
381   return 0;
382 } /* }}} int cx_handle_all_value_xpaths */
383
384 static int cx_handle_instance_xpath(xmlXPathContextPtr xpath_ctx, /* {{{ */
385                                     cx_xpath_t *xpath, value_list_t *vl) {
386
387   xmlXPathObjectPtr instance_node_obj = NULL;
388   xmlNodeSetPtr instance_node = NULL;
389
390   memset(vl->type_instance, 0, sizeof(vl->type_instance));
391
392   /* instance has to be an xpath expression */
393   if (xpath->instance != NULL) {
394     int tmp_size;
395
396     instance_node_obj = cx_evaluate_xpath(xpath_ctx, BAD_CAST xpath->instance);
397     if (instance_node_obj == NULL)
398       return -1; /* error is logged already */
399
400     instance_node = instance_node_obj->nodesetval;
401     tmp_size = (instance_node) ? instance_node->nodeNr : 0;
402
403     if (tmp_size <= 0) {
404       WARNING(
405           "curl_xml plugin: "
406           "relative xpath expression for 'InstanceFrom' \"%s\" doesn't match "
407           "any of the nodes. Skipping the node.",
408           xpath->instance);
409       xmlXPathFreeObject(instance_node_obj);
410       return -1;
411     }
412
413     if (tmp_size > 1) {
414       WARNING("curl_xml plugin: "
415               "relative xpath expression for 'InstanceFrom' \"%s\" is expected "
416               "to return only one text node. Skipping the node.",
417               xpath->instance);
418       xmlXPathFreeObject(instance_node_obj);
419       return -1;
420     }
421
422     /* ignoring the element if other than textnode/attribute */
423     if (cx_if_not_text_node(instance_node->nodeTab[0])) {
424       WARNING("curl_xml plugin: "
425               "relative xpath expression \"%s\" is expected to return only "
426               "text node "
427               "which is not the case. Skipping the node.",
428               xpath->instance);
429       xmlXPathFreeObject(instance_node_obj);
430       return -1;
431     }
432   } /* if (xpath->instance != NULL) */
433
434   if (xpath->instance_prefix != NULL) {
435     if (instance_node != NULL) {
436       char *node_value = (char *)xmlNodeGetContent(instance_node->nodeTab[0]);
437       snprintf(vl->type_instance, sizeof(vl->type_instance), "%s%s",
438                xpath->instance_prefix, node_value);
439       sfree(node_value);
440     } else
441       sstrncpy(vl->type_instance, xpath->instance_prefix,
442                sizeof(vl->type_instance));
443   } else {
444     /* If instance_prefix and instance_node are NULL, then
445      * don't set the type_instance */
446     if (instance_node != NULL) {
447       char *node_value = (char *)xmlNodeGetContent(instance_node->nodeTab[0]);
448       sstrncpy(vl->type_instance, node_value, sizeof(vl->type_instance));
449       sfree(node_value);
450     }
451   }
452
453   /* Free `instance_node_obj' this late, because `instance_node' points to
454    * somewhere inside this structure. */
455   xmlXPathFreeObject(instance_node_obj);
456
457   /* Part 2, handle PluginInstanceFrom */
458   instance_node_obj = NULL;
459   instance_node = NULL;
460
461   /* plugin_instance_from has to be an xpath expression */
462   if (xpath->plugin_instance_from != NULL) {
463     int tmp_size;
464
465     instance_node_obj = cx_evaluate_xpath(xpath_ctx,
466                                           BAD_CAST xpath->plugin_instance_from);
467     if (instance_node_obj == NULL)
468       return -1; /* error is already logged */
469
470     instance_node = instance_node_obj->nodesetval;
471     tmp_size = (instance_node) ? instance_node->nodeNr : 0;
472
473     if (tmp_size <= 0) {
474       WARNING("curl_xml plugin: "
475               "relative xpath expression for 'PluginInstanceFrom' \"%s\" "
476               "doesn't match any of the nodes. Skipping the node.",
477               xpath->plugin_instance_from);
478       xmlXPathFreeObject(instance_node_obj);
479       return -1;
480     }
481
482     if (tmp_size > 1) {
483       WARNING("curl_xml plugin: "
484               "relative xpath expression for 'PluginInstanceFrom' \"%s\" "
485               "is expected to return only one text node. Skipping the node.",
486               xpath->plugin_instance_from);
487       xmlXPathFreeObject(instance_node_obj);
488       return -1;
489     }
490
491     /* ignoring the element if other than textnode/attribute */
492     if (cx_if_not_text_node(instance_node->nodeTab[0])) {
493       WARNING("curl_xml plugin: "
494               "relative xpath expression \"%s\" is expected to return only "
495               "text node which is not the case. Skipping the node.",
496               xpath->plugin_instance_from);
497       xmlXPathFreeObject(instance_node_obj);
498       return -1;
499     }
500
501     if (instance_node != NULL) {
502       char *node_value = (char *)xmlNodeGetContent(instance_node->nodeTab[0]);
503       sstrncpy (vl->plugin_instance, node_value, sizeof(vl->plugin_instance));
504       sfree(node_value);
505     }
506
507     /* Free `instance_node_obj' this late, because `instance_node' points to
508      * somewhere inside this structure. */
509     xmlXPathFreeObject(instance_node_obj);
510   } /* if (xpath->plugin_instance_from != NULL) */
511
512   return 0;
513 } /* }}} int cx_handle_instance_xpath */
514
515 static int cx_handle_base_xpath(const cx_t *db, /* {{{ */
516                                 xmlXPathContextPtr xpath_ctx,
517                                 const data_set_t *ds, char *base_xpath,
518                                 cx_xpath_t *xpath) {
519   int total_nodes;
520
521   xmlXPathObjectPtr base_node_obj = NULL;
522   xmlNodeSetPtr base_nodes = NULL;
523
524   value_list_t vl = VALUE_LIST_INIT;
525
526   base_node_obj = cx_evaluate_xpath(xpath_ctx, BAD_CAST base_xpath);
527   if (base_node_obj == NULL)
528     return -1; /* error is logged already */
529
530   base_nodes = base_node_obj->nodesetval;
531   total_nodes = (base_nodes) ? base_nodes->nodeNr : 0;
532
533   if (total_nodes == 0) {
534     ERROR("curl_xml plugin: "
535           "xpath expression \"%s\" doesn't match any of the nodes. "
536           "Skipping the xpath block...",
537           base_xpath);
538     xmlXPathFreeObject(base_node_obj);
539     return -1;
540   }
541
542   /* If base_xpath returned multiple results, then */
543   /* InstanceFrom or PluginInstanceFrom in the xpath block is required */ 
544   if (total_nodes > 1 && xpath->instance == NULL
545       && xpath->plugin_instance_from == NULL) {
546     ERROR("curl_xml plugin: "
547           "InstanceFrom or PluginInstanceFrom is must in xpath block "
548           "since the base xpath expression \"%s\" "
549           "returned multiple results. Skipping the xpath block...",
550           base_xpath);
551     return -1;
552   }
553
554   /* set the values for the value_list */
555   vl.values_len = ds->ds_num;
556   sstrncpy(vl.type, xpath->type, sizeof(vl.type));
557   sstrncpy(vl.plugin, (db->plugin_name != NULL) ? db->plugin_name : "curl_xml",
558            sizeof(vl.plugin));
559   sstrncpy(vl.host, cx_host(db), sizeof(vl.host));
560
561   for (int i = 0; i < total_nodes; i++) {
562     int status;
563
564     xpath_ctx->node = base_nodes->nodeTab[i];
565
566     if (db->instance != NULL)
567       sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
568
569     status = cx_handle_instance_xpath(xpath_ctx, xpath, &vl);
570     if (status != 0)
571       continue; /* An error has already been reported. */
572
573     status = cx_handle_all_value_xpaths(xpath_ctx, xpath, ds, &vl);
574     if (status != 0)
575       continue; /* An error has been logged. */
576   }             /* for (i = 0; i < total_nodes; i++) */
577
578   /* free up the allocated memory */
579   xmlXPathFreeObject(base_node_obj);
580
581   return 0;
582 } /* }}} cx_handle_base_xpath */
583
584 static int cx_handle_parsed_xml(xmlDocPtr doc, /* {{{ */
585                                 xmlXPathContextPtr xpath_ctx, cx_t *db) {
586   llentry_t *le;
587   const data_set_t *ds;
588   cx_xpath_t *xpath;
589   int status = -1;
590
591   le = llist_head(db->list);
592   while (le != NULL) {
593     /* get the ds */
594     xpath = (cx_xpath_t *)le->value;
595     ds = plugin_get_ds(xpath->type);
596
597     if ((cx_check_type(ds, xpath) == 0) &&
598         (cx_handle_base_xpath(db, xpath_ctx, ds, le->key, xpath) == 0))
599       status = 0; /* we got atleast one success */
600
601     le = le->next;
602   } /* while (le != NULL) */
603
604   return status;
605 } /* }}} cx_handle_parsed_xml */
606
607 static int cx_parse_stats_xml(xmlChar *xml, cx_t *db) /* {{{ */
608 {
609   int status;
610   xmlDocPtr doc;
611   xmlXPathContextPtr xpath_ctx;
612
613   /* Load the XML */
614   doc = xmlParseDoc(xml);
615   if (doc == NULL) {
616     ERROR("curl_xml plugin: Failed to parse the xml document  - %s", xml);
617     return -1;
618   }
619
620   xpath_ctx = xmlXPathNewContext(doc);
621   if (xpath_ctx == NULL) {
622     ERROR("curl_xml plugin: Failed to create the xml context");
623     xmlFreeDoc(doc);
624     return -1;
625   }
626
627   for (size_t i = 0; i < db->namespaces_num; i++) {
628     cx_namespace_t const *ns = db->namespaces + i;
629     status =
630         xmlXPathRegisterNs(xpath_ctx, BAD_CAST ns->prefix, BAD_CAST ns->url);
631     if (status != 0) {
632       ERROR("curl_xml plugin: "
633             "unable to register NS with prefix=\"%s\" and href=\"%s\"\n",
634             ns->prefix, ns->url);
635       xmlXPathFreeContext(xpath_ctx);
636       xmlFreeDoc(doc);
637       return status;
638     }
639   }
640
641   status = cx_handle_parsed_xml(doc, xpath_ctx, db);
642   /* Cleanup */
643   xmlXPathFreeContext(xpath_ctx);
644   xmlFreeDoc(doc);
645   return status;
646 } /* }}} cx_parse_stats_xml */
647
648 static int cx_curl_perform(cx_t *db, CURL *curl) /* {{{ */
649 {
650   int status;
651   long rc;
652   char *ptr;
653   char *url;
654
655   db->buffer_fill = 0;
656
657   curl_easy_setopt(db->curl, CURLOPT_URL, db->url);
658
659   status = curl_easy_perform(curl);
660   if (status != CURLE_OK) {
661     ERROR("curl_xml plugin: curl_easy_perform failed with status %i: %s (%s)",
662           status, db->curl_errbuf, db->url);
663     return -1;
664   }
665   if (db->stats != NULL)
666     curl_stats_dispatch(db->stats, db->curl, cx_host(db), "curl_xml",
667                         db->instance);
668
669   curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
670   curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
671
672   /* The response code is zero if a non-HTTP transport was used. */
673   if ((rc != 0) && (rc != 200)) {
674     ERROR(
675         "curl_xml plugin: curl_easy_perform failed with response code %ld (%s)",
676         rc, url);
677     return -1;
678   }
679
680   ptr = db->buffer;
681
682   status = cx_parse_stats_xml(BAD_CAST ptr, db);
683   db->buffer_fill = 0;
684
685   return status;
686 } /* }}} int cx_curl_perform */
687
688 static int cx_read(user_data_t *ud) /* {{{ */
689 {
690   cx_t *db;
691
692   if ((ud == NULL) || (ud->data == NULL)) {
693     ERROR("curl_xml plugin: cx_read: Invalid user data.");
694     return -1;
695   }
696
697   db = (cx_t *)ud->data;
698
699   return cx_curl_perform(db, db->curl);
700 } /* }}} int cx_read */
701
702 /* Configuration handling functions {{{ */
703
704 static int cx_config_add_values(const char *name, cx_xpath_t *xpath, /* {{{ */
705                                 oconfig_item_t *ci) {
706   if (ci->values_num < 1) {
707     WARNING("curl_xml plugin: `ValuesFrom' needs at least one argument.");
708     return -1;
709   }
710
711   for (int i = 0; i < ci->values_num; i++)
712     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
713       WARNING("curl_xml plugin: `ValuesFrom' needs only string argument.");
714       return -1;
715     }
716
717   sfree(xpath->values);
718
719   xpath->values_len = 0;
720   xpath->values = malloc(sizeof(cx_values_t) * ci->values_num);
721   if (xpath->values == NULL)
722     return -1;
723   xpath->values_len = (size_t)ci->values_num;
724
725   /* populate cx_values_t structure */
726   for (int i = 0; i < ci->values_num; i++) {
727     xpath->values[i].path_len = sizeof(ci->values[i].value.string);
728     sstrncpy(xpath->values[i].path, ci->values[i].value.string,
729              sizeof(xpath->values[i].path));
730   }
731
732   return 0;
733 } /* }}} cx_config_add_values */
734
735 static int cx_config_add_xpath(cx_t *db, oconfig_item_t *ci) /* {{{ */
736 {
737   cx_xpath_t *xpath;
738   char *name;
739   llentry_t *le;
740   int status;
741
742   xpath = calloc(1, sizeof(*xpath));
743   if (xpath == NULL) {
744     ERROR("curl_xml plugin: calloc failed.");
745     return -1;
746   }
747
748   status = cf_util_get_string(ci, &xpath->path);
749   if (status != 0) {
750     cx_xpath_free(xpath);
751     return status;
752   }
753
754   /* error out if xpath->path is an empty string */
755   if (strlen(xpath->path) == 0) {
756     ERROR("curl_xml plugin: invalid xpath. "
757           "xpath value can't be an empty string");
758     cx_xpath_free(xpath);
759     return -1;
760   }
761
762   status = 0;
763   for (int i = 0; i < ci->children_num; i++) {
764     oconfig_item_t *child = ci->children + i;
765
766     if (strcasecmp("Type", child->key) == 0)
767       status = cf_util_get_string(child, &xpath->type);
768     else if (strcasecmp("InstancePrefix", child->key) == 0)
769       status = cf_util_get_string(child, &xpath->instance_prefix);
770     else if (strcasecmp("InstanceFrom", child->key) == 0)
771       status = cf_util_get_string(child, &xpath->instance);
772     else if (strcasecmp("PluginInstanceFrom", child->key) == 0)
773       status = cf_util_get_string(child, &xpath->plugin_instance_from);
774     else if (strcasecmp("ValuesFrom", child->key) == 0)
775       status = cx_config_add_values("ValuesFrom", xpath, child);
776     else {
777       WARNING("curl_xml plugin: Option `%s' not allowed here.", child->key);
778       status = -1;
779     }
780
781     if (status != 0)
782       break;
783   } /* for (i = 0; i < ci->children_num; i++) */
784
785   if (status != 0) {
786     cx_xpath_free(xpath);
787     return status;
788   }
789
790   if (xpath->type == NULL) {
791     WARNING("curl_xml plugin: `Type' missing in `xpath' block.");
792     cx_xpath_free(xpath);
793     return -1;
794   }
795
796   if (db->list == NULL) {
797     db->list = llist_create();
798     if (db->list == NULL) {
799       ERROR("curl_xml plugin: list creation failed.");
800       cx_xpath_free(xpath);
801       return -1;
802     }
803   }
804
805   name = strdup(xpath->path);
806   if (name == NULL) {
807     ERROR("curl_xml plugin: strdup failed.");
808     cx_xpath_free(xpath);
809     return -1;
810   }
811
812   le = llentry_create(name, xpath);
813   if (le == NULL) {
814     ERROR("curl_xml plugin: llentry_create failed.");
815     cx_xpath_free(xpath);
816     sfree(name);
817     return -1;
818   }
819
820   llist_append(db->list, le);
821   return 0;
822 } /* }}} int cx_config_add_xpath */
823
824 static int cx_config_add_namespace(cx_t *db, /* {{{ */
825                                    oconfig_item_t *ci) {
826   cx_namespace_t *ns;
827
828   if ((ci->values_num != 2) || (ci->values[0].type != OCONFIG_TYPE_STRING) ||
829       (ci->values[1].type != OCONFIG_TYPE_STRING)) {
830     WARNING("curl_xml plugin: The `Namespace' option "
831             "needs exactly two string arguments.");
832     return EINVAL;
833   }
834
835   ns = realloc(db->namespaces,
836                sizeof(*db->namespaces) * (db->namespaces_num + 1));
837   if (ns == NULL) {
838     ERROR("curl_xml plugin: realloc failed.");
839     return ENOMEM;
840   }
841   db->namespaces = ns;
842   ns = db->namespaces + db->namespaces_num;
843   memset(ns, 0, sizeof(*ns));
844
845   ns->prefix = strdup(ci->values[0].value.string);
846   ns->url = strdup(ci->values[1].value.string);
847
848   if ((ns->prefix == NULL) || (ns->url == NULL)) {
849     sfree(ns->prefix);
850     sfree(ns->url);
851     ERROR("curl_xml plugin: strdup failed.");
852     return ENOMEM;
853   }
854
855   db->namespaces_num++;
856   return 0;
857 } /* }}} int cx_config_add_namespace */
858
859 /* Initialize db->curl */
860 static int cx_init_curl(cx_t *db) /* {{{ */
861 {
862   db->curl = curl_easy_init();
863   if (db->curl == NULL) {
864     ERROR("curl_xml plugin: curl_easy_init failed.");
865     return -1;
866   }
867
868   curl_easy_setopt(db->curl, CURLOPT_NOSIGNAL, 1L);
869   curl_easy_setopt(db->curl, CURLOPT_WRITEFUNCTION, cx_curl_callback);
870   curl_easy_setopt(db->curl, CURLOPT_WRITEDATA, db);
871   curl_easy_setopt(db->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
872   curl_easy_setopt(db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
873   curl_easy_setopt(db->curl, CURLOPT_FOLLOWLOCATION, 1L);
874   curl_easy_setopt(db->curl, CURLOPT_MAXREDIRS, 50L);
875
876   if (db->user != NULL) {
877 #ifdef HAVE_CURLOPT_USERNAME
878     curl_easy_setopt(db->curl, CURLOPT_USERNAME, db->user);
879     curl_easy_setopt(db->curl, CURLOPT_PASSWORD,
880                      (db->pass == NULL) ? "" : db->pass);
881 #else
882     size_t credentials_size;
883
884     credentials_size = strlen(db->user) + 2;
885     if (db->pass != NULL)
886       credentials_size += strlen(db->pass);
887
888     db->credentials = malloc(credentials_size);
889     if (db->credentials == NULL) {
890       ERROR("curl_xml plugin: malloc failed.");
891       return -1;
892     }
893
894     snprintf(db->credentials, credentials_size, "%s:%s", db->user,
895              (db->pass == NULL) ? "" : db->pass);
896     curl_easy_setopt(db->curl, CURLOPT_USERPWD, db->credentials);
897 #endif
898
899     if (db->digest)
900       curl_easy_setopt(db->curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
901   }
902
903   curl_easy_setopt(db->curl, CURLOPT_SSL_VERIFYPEER, db->verify_peer ? 1L : 0L);
904   curl_easy_setopt(db->curl, CURLOPT_SSL_VERIFYHOST, db->verify_host ? 2L : 0L);
905   if (db->cacert != NULL)
906     curl_easy_setopt(db->curl, CURLOPT_CAINFO, db->cacert);
907   if (db->headers != NULL)
908     curl_easy_setopt(db->curl, CURLOPT_HTTPHEADER, db->headers);
909   if (db->post_body != NULL)
910     curl_easy_setopt(db->curl, CURLOPT_POSTFIELDS, db->post_body);
911
912 #ifdef HAVE_CURLOPT_TIMEOUT_MS
913   if (db->timeout >= 0)
914     curl_easy_setopt(db->curl, CURLOPT_TIMEOUT_MS, (long)db->timeout);
915   else
916     curl_easy_setopt(db->curl, CURLOPT_TIMEOUT_MS,
917                      (long)CDTIME_T_TO_MS(plugin_get_interval()));
918 #endif
919
920   return 0;
921 } /* }}} int cx_init_curl */
922
923 static int cx_config_add_url(oconfig_item_t *ci) /* {{{ */
924 {
925   cx_t *db;
926   int status = 0;
927
928   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
929     WARNING("curl_xml plugin: The `URL' block "
930             "needs exactly one string argument.");
931     return -1;
932   }
933
934   db = calloc(1, sizeof(*db));
935   if (db == NULL) {
936     ERROR("curl_xml plugin: calloc failed.");
937     return -1;
938   }
939
940   db->timeout = -1;
941
942   if (strcasecmp("URL", ci->key) == 0) {
943     status = cf_util_get_string(ci, &db->url);
944     if (status != 0) {
945       sfree(db);
946       return status;
947     }
948   } else {
949     ERROR("curl_xml plugin: cx_config: "
950           "Invalid key: %s",
951           ci->key);
952     cx_free(db);
953     return -1;
954   }
955
956   /* Fill the `cx_t' structure.. */
957   for (int i = 0; i < ci->children_num; i++) {
958     oconfig_item_t *child = ci->children + i;
959
960     if (strcasecmp("Instance", child->key) == 0)
961       status = cf_util_get_string(child, &db->instance);
962     else if (strcasecmp("PluginName", child->key) == 0)
963       status = cf_util_get_string(child, &db->plugin_name);
964     else if (strcasecmp("Host", child->key) == 0)
965       status = cf_util_get_string(child, &db->host);
966     else if (strcasecmp("User", child->key) == 0)
967       status = cf_util_get_string(child, &db->user);
968     else if (strcasecmp("Password", child->key) == 0)
969       status = cf_util_get_string(child, &db->pass);
970     else if (strcasecmp("Digest", child->key) == 0)
971       status = cf_util_get_boolean(child, &db->digest);
972     else if (strcasecmp("VerifyPeer", child->key) == 0)
973       status = cf_util_get_boolean(child, &db->verify_peer);
974     else if (strcasecmp("VerifyHost", child->key) == 0)
975       status = cf_util_get_boolean(child, &db->verify_host);
976     else if (strcasecmp("CACert", child->key) == 0)
977       status = cf_util_get_string(child, &db->cacert);
978     else if (strcasecmp("xpath", child->key) == 0)
979       status = cx_config_add_xpath(db, child);
980     else if (strcasecmp("Header", child->key) == 0)
981       status = cx_config_append_string("Header", &db->headers, child);
982     else if (strcasecmp("Post", child->key) == 0)
983       status = cf_util_get_string(child, &db->post_body);
984     else if (strcasecmp("Namespace", child->key) == 0)
985       status = cx_config_add_namespace(db, child);
986     else if (strcasecmp("Timeout", child->key) == 0)
987       status = cf_util_get_int(child, &db->timeout);
988     else if (strcasecmp("Statistics", child->key) == 0) {
989       db->stats = curl_stats_from_config(child);
990       if (db->stats == NULL)
991         status = -1;
992     } else {
993       WARNING("curl_xml plugin: Option `%s' not allowed here.", child->key);
994       status = -1;
995     }
996
997     if (status != 0)
998       break;
999   }
1000
1001   if (status == 0) {
1002     if (db->list == NULL) {
1003       WARNING("curl_xml plugin: No (valid) `Key' block "
1004               "within `URL' block `%s'.",
1005               db->url);
1006       status = -1;
1007     }
1008     if (status == 0)
1009       status = cx_init_curl(db);
1010   }
1011
1012   /* If all went well, register this database for reading */
1013   if (status == 0) {
1014     char *cb_name;
1015
1016     if (db->instance == NULL)
1017       db->instance = strdup("default");
1018
1019     DEBUG("curl_xml plugin: Registering new read callback: %s", db->instance);
1020
1021     cb_name = ssnprintf_alloc("curl_xml-%s-%s", db->instance, db->url);
1022
1023     plugin_register_complex_read(/* group = */ "curl_xml", cb_name, cx_read,
1024                                  /* interval = */ 0,
1025                                  &(user_data_t){
1026                                      .data = db, .free_func = cx_free,
1027                                  });
1028     sfree(cb_name);
1029   } else {
1030     cx_free(db);
1031     return -1;
1032   }
1033
1034   return 0;
1035 } /* }}} int cx_config_add_url */
1036
1037 /* }}} End of configuration handling functions */
1038
1039 static int cx_config(oconfig_item_t *ci) /* {{{ */
1040 {
1041   int success;
1042   int errors;
1043   int status;
1044
1045   success = 0;
1046   errors = 0;
1047
1048   for (int i = 0; i < ci->children_num; i++) {
1049     oconfig_item_t *child = ci->children + i;
1050
1051     if (strcasecmp("URL", child->key) == 0) {
1052       status = cx_config_add_url(child);
1053       if (status == 0)
1054         success++;
1055       else
1056         errors++;
1057     } else {
1058       WARNING("curl_xml plugin: Option `%s' not allowed here.", child->key);
1059       errors++;
1060     }
1061   }
1062
1063   if ((success == 0) && (errors > 0)) {
1064     ERROR("curl_xml plugin: All statements failed.");
1065     return -1;
1066   }
1067
1068   return 0;
1069 } /* }}} int cx_config */
1070
1071 static int cx_init(void) /* {{{ */
1072 {
1073   /* Call this while collectd is still single-threaded to avoid
1074    * initialization issues in libgcrypt. */
1075   curl_global_init(CURL_GLOBAL_SSL);
1076   return 0;
1077 } /* }}} int cx_init */
1078
1079 void module_register(void) {
1080   plugin_register_complex_config("curl_xml", cx_config);
1081   plugin_register_init("curl_xml", cx_init);
1082 } /* void module_register */