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