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