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