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