curl_xml plugin: Added support for XML namespaces
[collectd.git] / src / curl_xml.c
index 240be66..db5cd61 100644 (file)
@@ -28,6 +28,7 @@
 #include <libxml/parser.h>
 #include <libxml/tree.h>
 #include <libxml/xpath.h>
+#include <libxml/xpathInternals.h>
 
 #include <curl/curl.h>
 
@@ -70,6 +71,9 @@ struct cx_s /* {{{ */
   _Bool verify_peer;
   _Bool verify_host;
   char *cacert;
+  char *post_body;
+  struct curl_slist *headers;
+  char *namespaces;
 
   CURL *curl;
   char curl_errbuf[CURL_ERROR_SIZE];
@@ -184,10 +188,29 @@ static void cx_free (void *arg) /* {{{ */
   sfree (db->pass);
   sfree (db->credentials);
   sfree (db->cacert);
+  sfree (db->post_body);
+  curl_slist_free_all (db->headers);
+  sfree (db->namespaces);
 
   sfree (db);
 } /* }}} void cx_free */
 
+static int cx_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
+    oconfig_item_t *ci)
+{
+  if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
+  {
+    WARNING ("curl_xml plugin: `%s' needs exactly one string argument.", name);
+    return (-1);
+  }
+
+  *dest = curl_slist_append(*dest, ci->values[0].value.string);
+  if (*dest == NULL)
+    return (-1);
+
+  return (0);
+} /* }}} int cx_config_append_string */
+
 static int cx_check_type (const data_set_t *ds, cx_xpath_t *xpath) /* {{{ */
 {
   if (!ds)
@@ -225,7 +248,8 @@ static xmlXPathObjectPtr cx_evaluate_xpath (xmlXPathContextPtr xpath_ctx, /* {{{
 
 static int cx_if_not_text_node (xmlNodePtr node) /* {{{ */
 {
-  if (node->type == XML_TEXT_NODE || node->type == XML_ATTRIBUTE_NODE)
+  if (node->type == XML_TEXT_NODE || node->type == XML_ATTRIBUTE_NODE ||
+      node->type == XML_ELEMENT_NODE)
     return (0);
 
   WARNING ("curl_xml plugin: "
@@ -233,6 +257,98 @@ static int cx_if_not_text_node (xmlNodePtr node) /* {{{ */
   return -1;
 } /* }}} cx_if_not_text_node */
 
+/**
+ * cx_register_namespaces:
+ * @xpath_ctx:         the pointer to an XPath context.
+ * @nslist:            the list of known namespaces in
+ *                     "<prefix1>=<href1> <prefix2>=href2> ..." format.
+ *
+ * Registers namespaces from @nslist in @xpath_ctx.
+ *
+ * Returns 0 on success and a negative value otherwise.
+ *
+ * author:     Aleksey Sanin
+ *
+ * The following license statement applies to the function
+ * cx_register_namespaces only:
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is fur-
+ * nished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FIT-
+ * NESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+ * DANIEL VEILLARD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CON-
+ * NECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name of Daniel Veillard shall not
+ * be used in advertising or otherwise to promote the sale, use or other deal-
+ * ings in this Software without prior written authorization from him.
+ */
+static int cx_register_namespaces(xmlXPathContextPtr xpath_ctx, /* {{{ */
+    const xmlChar* nslist)
+{
+    xmlChar* nslistdup;
+    xmlChar* prefix;
+    xmlChar* href;
+    xmlChar* next;
+
+    assert(xpath_ctx);
+    assert(nslist);
+
+    nslistdup = xmlStrdup(nslist);
+    if(nslistdup == NULL) {
+        ERROR ("curl_xml plugin: "
+              "unable to strdup namespaces list");
+       return (-1);
+    }
+
+    next = nslistdup;
+    while(next != NULL) {
+       /* skip spaces */
+       while((*next) == ' ') next++;
+       if((*next) == '\0') break;
+
+       /* find prefix */
+       prefix = next;
+       next = (xmlChar*)xmlStrchr(next, '=');
+       if(next == NULL) {
+            ERROR ("curl_xml plugin: "
+                  "invalid namespaces list format");
+           xmlFree(nslistdup);
+           return (-1);
+       }
+       *(next++) = '\0';
+
+       /* find href */
+       href = next;
+       next = (xmlChar*)xmlStrchr(next, ' ');
+       if(next != NULL) {
+           *(next++) = '\0';
+       }
+
+       /* do register namespace */
+       if(xmlXPathRegisterNs(xpath_ctx, prefix, href) != 0) {
+            ERROR ("curl_xml plugin: "
+                  "unable to register NS with prefix=\"%s\" and href=\"%s\"\n",
+                   prefix, href);
+           xmlFree(nslistdup);
+           return (-1);
+       }
+    }
+
+    xmlFree(nslistdup);
+    return (0);
+} /* }}} cx_register_namespaces */
+
 static int cx_handle_single_value_xpath (xmlXPathContextPtr xpath_ctx, /* {{{ */
     cx_xpath_t *xpath,
     const data_set_t *ds, value_list_t *vl, int index)
@@ -342,7 +458,7 @@ static int cx_handle_instance_xpath (xmlXPathContextPtr xpath_ctx, /* {{{ */
   memset (vl->type_instance, 0, sizeof (vl->type_instance));
 
   /* If the base xpath returns more than one block, the result is assumed to be
-   * a table. The `Instnce' option is not optional in this case. Check for the
+   * a table. The `Instance' option is not optional in this case. Check for the
    * condition and inform the user. */
   if (is_table && (vl->type_instance == NULL))
   {
@@ -365,7 +481,7 @@ static int cx_handle_instance_xpath (xmlXPathContextPtr xpath_ctx, /* {{{ */
     instance_node = instance_node_obj->nodesetval;
     tmp_size = (instance_node) ? instance_node->nodeNr : 0;
 
-    if ( (tmp_size == 0) && (is_table) )
+    if (tmp_size <= 0)
     {
       WARNING ("curl_xml plugin: "
           "relative xpath expression for 'InstanceFrom' \"%s\" doesn't match "
@@ -419,7 +535,8 @@ static int cx_handle_instance_xpath (xmlXPathContextPtr xpath_ctx, /* {{{ */
   return (0);
 } /* }}} int cx_handle_instance_xpath */
 
-static int  cx_handle_base_xpath (char *plugin_instance, /* {{{ */
+static int  cx_handle_base_xpath (char const *plugin_instance, /* {{{ */
+    char const *host,
     xmlXPathContextPtr xpath_ctx, const data_set_t *ds, 
     char *base_xpath, cx_xpath_t *xpath)
 {
@@ -461,7 +578,7 @@ static int  cx_handle_base_xpath (char *plugin_instance, /* {{{ */
   vl.values_len = ds->ds_num;
   sstrncpy (vl.type, xpath->type, sizeof (vl.type));
   sstrncpy (vl.plugin, "curl_xml", sizeof (vl.plugin));
-  sstrncpy (vl.host, hostname_g, sizeof (vl.host));
+  sstrncpy (vl.host, (host != NULL) ? host : hostname_g, sizeof (vl.host));
   if (plugin_instance != NULL)
     sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); 
 
@@ -504,7 +621,8 @@ static int cx_handle_parsed_xml(xmlDocPtr doc, /* {{{ */
     ds = plugin_get_ds (xpath->type);
 
     if ( (cx_check_type(ds, xpath) == 0) &&
-         (cx_handle_base_xpath(db->instance, xpath_ctx, ds, le->key, xpath) == 0) )
+         (cx_handle_base_xpath(db->instance, db->host,
+                               xpath_ctx, ds, le->key, xpath) == 0) )
       status = 0; /* we got atleast one success */
 
     le = le->next;
@@ -535,6 +653,13 @@ static int cx_parse_stats_xml(xmlChar* xml, cx_t *db) /* {{{ */
     return (-1);
   }
 
+  if((db->namespaces != NULL) &&
+     (cx_register_namespaces(xpath_ctx, BAD_CAST db->namespaces) < 0))
+  {
+    xmlFreeDoc(doc);
+    return (-1);
+  }
+
   status = cx_handle_parsed_xml (doc, xpath_ctx, db);
   /* Cleanup */
   xmlXPathFreeContext(xpath_ctx);
@@ -551,24 +676,24 @@ static int cx_curl_perform (cx_t *db, CURL *curl) /* {{{ */
 
   db->buffer_fill = 0; 
   status = curl_easy_perform (curl);
+  if (status != CURLE_OK)
+  {
+    ERROR ("curl_xml plugin: curl_easy_perform failed with status %i: %s (%s)",
+           status, db->curl_errbuf, url);
+    return (-1);
+  }
 
   curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
   curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
 
-  if (rc != 200)
+  /* The response code is zero if a non-HTTP transport was used. */
+  if ((rc != 0) && (rc != 200))
   {
     ERROR ("curl_xml plugin: curl_easy_perform failed with response code %ld (%s)",
            rc, url);
     return (-1);
   }
 
-  if (status != 0)
-  {
-    ERROR ("curl_xml plugin: curl_easy_perform failed with status %i: %s (%s)",
-           status, db->curl_errbuf, url);
-    return (-1);
-  }
-
   ptr = db->buffer;
 
   status = cx_parse_stats_xml(BAD_CAST ptr, db);
@@ -734,6 +859,7 @@ static int cx_init_curl (cx_t *db) /* {{{ */
     return (-1);
   }
 
+  curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
   curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cx_curl_callback);
   curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
   curl_easy_setopt (db->curl, CURLOPT_USERAGENT,
@@ -766,6 +892,10 @@ static int cx_init_curl (cx_t *db) /* {{{ */
                     db->verify_host ? 2L : 0L);
   if (db->cacert != NULL)
     curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
+  if (db->headers != NULL)
+    curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
+  if (db->post_body != NULL)
+    curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
 
   return (0);
 } /* }}} int cx_init_curl */
@@ -829,6 +959,12 @@ static int cx_config_add_url (oconfig_item_t *ci) /* {{{ */
       status = cf_util_get_string (child, &db->cacert);
     else if (strcasecmp ("xpath", child->key) == 0)
       status = cx_config_add_xpath (db, child);
+    else if (strcasecmp ("Header", child->key) == 0)
+      status = cx_config_append_string ("Header", &db->headers, child);
+    else if (strcasecmp ("Post", child->key) == 0)
+      status = cf_util_get_string (child, &db->post_body);
+    else if (strcasecmp ("Namespaces", child->key) == 0)
+      status = cf_util_get_string (child, &db->namespaces);
     else
     {
       WARNING ("curl_xml plugin: Option `%s' not allowed here.", child->key);
@@ -870,7 +1006,7 @@ static int cx_config_add_url (oconfig_item_t *ci) /* {{{ */
     ssnprintf (cb_name, sizeof (cb_name), "curl_xml-%s-%s",
                db->instance, db->url);
 
-    plugin_register_complex_read (cb_name, cx_read,
+    plugin_register_complex_read (/* group = */ NULL, cb_name, cx_read,
                                   /* interval = */ NULL, &ud);
   }
   else