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