Merge remote-tracking branches 'github/pr/392' and 'github/pr/399' into jr/json
[collectd.git] / src / curl_json.c
1 /**
2  * collectd - src/curl_json.c
3  * Copyright (C) 2009       Doug MacEachern
4  * Copyright (C) 2006-2011  Florian octo Forster
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Doug MacEachern <dougm at hyperic.com>
21  *   Florian octo Forster <octo at collectd.org>
22  **/
23
24 #include "collectd.h"
25 #include "common.h"
26 #include "plugin.h"
27 #include "configfile.h"
28 #include "utils_avltree.h"
29 #include "utils_complain.h"
30
31 #include <sys/socket.h>
32 #include <sys/types.h>
33 #include <sys/un.h>
34
35 #include <curl/curl.h>
36
37 #include <yajl/yajl_parse.h>
38 #if HAVE_YAJL_YAJL_VERSION_H
39 # include <yajl/yajl_version.h>
40 #endif
41
42 #if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
43 # define HAVE_YAJL_V2 1
44 #endif
45
46 #define CJ_DEFAULT_HOST "localhost"
47 #define CJ_KEY_MAGIC 0x43484b59UL /* CHKY */
48 #define CJ_IS_KEY(key) ((key)->magic == CJ_KEY_MAGIC)
49 #define CJ_ANY "*"
50 #define COUCH_MIN(x,y) ((x) < (y) ? (x) : (y))
51
52 struct cj_key_s;
53 typedef struct cj_key_s cj_key_t;
54 struct cj_key_s /* {{{ */
55 {
56   char *path;
57   char *type;
58   char *instance;
59   unsigned long magic;
60 };
61 /* }}} */
62
63 struct cj_s /* {{{ */
64 {
65   char *instance;
66   char *host;
67
68   char *sock;
69
70   char *url;
71   char *user;
72   char *pass;
73   char *credentials;
74   _Bool verify_peer;
75   _Bool verify_host;
76   char *cacert;
77   struct curl_slist *headers;
78   char *post_body;
79
80   CURL *curl;
81   char curl_errbuf[CURL_ERROR_SIZE];
82
83   yajl_handle yajl;
84   c_avl_tree_t *tree;
85   cj_key_t *key;
86   int depth;
87   struct {
88     union {
89       c_avl_tree_t *tree;
90       cj_key_t *key;
91     };
92     _Bool in_array;
93     int index;
94     char name[DATA_MAX_NAME_LEN];
95   } state[YAJL_MAX_DEPTH];
96 };
97 typedef struct cj_s cj_t; /* }}} */
98
99 #if HAVE_YAJL_V2
100 typedef size_t yajl_len_t;
101 #else
102 typedef unsigned int yajl_len_t;
103 #endif
104
105 static int cj_read (user_data_t *ud);
106 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value);
107
108 static size_t cj_curl_callback (void *buf, /* {{{ */
109     size_t size, size_t nmemb, void *user_data)
110 {
111   cj_t *db;
112   size_t len;
113   yajl_status status;
114
115   len = size * nmemb;
116
117   if (len <= 0)
118     return (len);
119
120   db = user_data;
121   if (db == NULL)
122     return (0);
123
124   status = yajl_parse(db->yajl, (unsigned char *)buf, len);
125   if (status == yajl_status_ok)
126     return (len);
127 #if !HAVE_YAJL_V2
128   else if (status == yajl_status_insufficient_data)
129     return (len);
130 #endif
131
132   if (status != yajl_status_ok)
133   {
134     unsigned char *msg =
135       yajl_get_error(db->yajl, /* verbose = */ 1,
136           /* jsonText = */ (unsigned char *) buf, (unsigned int) len);
137     ERROR ("curl_json plugin: yajl_parse failed: %s", msg);
138     yajl_free_error(db->yajl, msg);
139     return (0); /* abort write callback */
140   }
141
142   return (len);
143 } /* }}} size_t cj_curl_callback */
144
145 static int cj_get_type (cj_key_t *key)
146 {
147   const data_set_t *ds;
148
149   ds = plugin_get_ds (key->type);
150   if (ds == NULL)
151   {
152     static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
153
154     assert (key->type != NULL);
155     if (strcmp (type, key->type) != 0)
156     {
157       ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
158           key->type);
159       sstrncpy (type, key->type, sizeof (type));
160     }
161
162     return -1;
163   }
164   else if (ds->ds_num > 1)
165   {
166     static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
167
168     c_complain_once (LOG_WARNING, &complaint,
169         "curl_json plugin: The type \"%s\" has more than one data source. "
170         "This is currently not supported. I will return the type of the "
171         "first data source, but this will likely lead to problems later on.",
172         key->type);
173   }
174
175   return ds->ds[0].type;
176 }
177
178 static int cj_cb_map_key (void *ctx, const unsigned char *val,
179     yajl_len_t len);
180
181 static void cj_cb_inc_array_index (void * ctx, _Bool ignore)
182 {
183   cj_t *db = (cj_t *)ctx;
184
185   if (db->state[db->depth].in_array) {
186     if (ignore)
187       db->state[db->depth].index++;
188     else {
189       char name[DATA_MAX_NAME_LEN];
190       cj_cb_map_key (ctx, (unsigned char *)name,
191                      ssnprintf (name, sizeof (name),
192                                 "%d", db->state[db->depth].index++));
193     }
194   }
195 }
196
197 /* yajl callbacks */
198 #define CJ_CB_ABORT    0
199 #define CJ_CB_CONTINUE 1
200
201 static int cj_cb_boolean (void * ctx, int boolVal)
202 {
203   cj_cb_inc_array_index (ctx, 1);
204   return (CJ_CB_CONTINUE);
205 }
206
207 static int cj_cb_null (void * ctx)
208 {
209   cj_cb_inc_array_index (ctx, 1);
210   return (CJ_CB_CONTINUE);
211 }
212
213 /* "number" may not be null terminated, so copy it into a buffer before
214  * parsing. */
215 static int cj_cb_number (void *ctx,
216     const char *number, yajl_len_t number_len)
217 {
218   char buffer[number_len + 1];
219
220   cj_t *db = (cj_t *)ctx;
221   cj_key_t *key = db->state[db->depth].key;
222   value_t vt;
223   int type;
224   int status;
225
226   if ((key == NULL) || !CJ_IS_KEY (key)) {
227     if (key != NULL)
228       NOTICE ("curl_json plugin: Found \"%.*s\", but the configuration expects"
229               " a map.", (int)number_len > number_len ? 0 : (int)number_len,
230               number);
231     cj_cb_inc_array_index (ctx, 1);
232     return (CJ_CB_CONTINUE);
233   } else
234     cj_cb_inc_array_index (ctx, 0);
235
236   memcpy (buffer, number, number_len);
237   buffer[sizeof (buffer) - 1] = 0;
238
239   type = cj_get_type (key);
240   status = parse_value (buffer, &vt, type);
241   if (status != 0)
242   {
243     NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
244     return (CJ_CB_CONTINUE);
245   }
246
247   cj_submit (db, key, &vt);
248   return (CJ_CB_CONTINUE);
249 } /* int cj_cb_number */
250
251 static int cj_cb_map_key (void *ctx, const unsigned char *val,
252     yajl_len_t len)
253 {
254   cj_t *db = (cj_t *)ctx;
255   c_avl_tree_t *tree;
256
257   tree = db->state[db->depth-1].tree;
258
259   if (tree != NULL)
260   {
261     cj_key_t *value;
262     char *name;
263
264     name = db->state[db->depth].name;
265     len = COUCH_MIN(len, sizeof (db->state[db->depth].name)-1);
266     sstrncpy (name, (char *)val, len+1);
267
268     if (c_avl_get (tree, name, (void *) &value) == 0)
269       db->state[db->depth].key = value;
270     else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
271       db->state[db->depth].key = value;
272     else
273       db->state[db->depth].key = NULL;
274   }
275
276   return (CJ_CB_CONTINUE);
277 }
278
279 static int cj_cb_string (void *ctx, const unsigned char *val,
280     yajl_len_t len)
281 {
282   /* Handle the string as if it was a number. */
283   return (cj_cb_number (ctx, (const char *) val, len));
284 } /* int cj_cb_string */
285
286 static int cj_cb_start (void *ctx)
287 {
288   cj_t *db = (cj_t *)ctx;
289   if (++db->depth >= YAJL_MAX_DEPTH)
290   {
291     ERROR ("curl_json plugin: %s depth exceeds max, aborting.",
292            db->url ? db->url : db->sock);
293     return (CJ_CB_ABORT);
294   }
295   return (CJ_CB_CONTINUE);
296 }
297
298 static int cj_cb_end (void *ctx)
299 {
300   cj_t *db = (cj_t *)ctx;
301   db->state[db->depth].tree = NULL;
302   --db->depth;
303   return (CJ_CB_CONTINUE);
304 }
305
306 static int cj_cb_start_map (void *ctx)
307 {
308   cj_cb_inc_array_index (ctx, 0);
309   return cj_cb_start (ctx);
310 }
311
312 static int cj_cb_end_map (void *ctx)
313 {
314   return cj_cb_end (ctx);
315 }
316
317 static int cj_cb_start_array (void * ctx)
318 {
319   cj_t *db = (cj_t *)ctx;
320   cj_cb_inc_array_index (ctx, 0);
321   if (db->depth+1 < YAJL_MAX_DEPTH) {
322     db->state[db->depth+1].in_array = 1;
323     db->state[db->depth+1].index = 0;
324   }
325   return cj_cb_start (ctx);
326 }
327
328 static int cj_cb_end_array (void * ctx)
329 {
330   cj_t *db = (cj_t *)ctx;
331   db->state[db->depth].in_array = 0;
332   return cj_cb_end (ctx);
333 }
334
335 static yajl_callbacks ycallbacks = {
336   cj_cb_null, /* null */
337   cj_cb_boolean, /* boolean */
338   NULL, /* integer */
339   NULL, /* double */
340   cj_cb_number,
341   cj_cb_string,
342   cj_cb_start_map,
343   cj_cb_map_key,
344   cj_cb_end_map,
345   cj_cb_start_array,
346   cj_cb_end_array
347 };
348
349 /* end yajl callbacks */
350
351 static void cj_key_free (cj_key_t *key) /* {{{ */
352 {
353   if (key == NULL)
354     return;
355
356   sfree (key->path);
357   sfree (key->type);
358   sfree (key->instance);
359
360   sfree (key);
361 } /* }}} void cj_key_free */
362
363 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
364 {
365   char *name;
366   void *value;
367
368   while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
369   {
370     cj_key_t *key = (cj_key_t *)value;
371
372     if (CJ_IS_KEY(key))
373       cj_key_free (key);
374     else
375       cj_tree_free ((c_avl_tree_t *)value);
376
377     sfree (name);
378   }
379
380   c_avl_destroy (tree);
381 } /* }}} void cj_tree_free */
382
383 static void cj_free (void *arg) /* {{{ */
384 {
385   cj_t *db;
386
387   DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
388
389   db = (cj_t *) arg;
390
391   if (db == NULL)
392     return;
393
394   if (db->curl != NULL)
395     curl_easy_cleanup (db->curl);
396   db->curl = NULL;
397
398   if (db->tree != NULL)
399     cj_tree_free (db->tree);
400   db->tree = NULL;
401
402   sfree (db->instance);
403   sfree (db->host);
404
405   sfree (db->sock);
406
407   sfree (db->url);
408   sfree (db->user);
409   sfree (db->pass);
410   sfree (db->credentials);
411   sfree (db->cacert);
412   sfree (db->post_body);
413   curl_slist_free_all (db->headers);
414
415   sfree (db);
416 } /* }}} void cj_free */
417
418 /* Configuration handling functions {{{ */
419
420 static c_avl_tree_t *cj_avl_create(void)
421 {
422   return c_avl_create ((int (*) (const void *, const void *)) strcmp);
423 }
424
425 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
426     oconfig_item_t *ci)
427 {
428   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
429   {
430     WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
431     return (-1);
432   }
433
434   *dest = curl_slist_append(*dest, ci->values[0].value.string);
435   if (*dest == NULL)
436     return (-1);
437
438   return (0);
439 } /* }}} int cj_config_append_string */
440
441 static int cj_config_add_key (cj_t *db, /* {{{ */
442                                    oconfig_item_t *ci)
443 {
444   cj_key_t *key;
445   int status;
446   int i;
447
448   if ((ci->values_num != 1)
449       || (ci->values[0].type != OCONFIG_TYPE_STRING))
450   {
451     WARNING ("curl_json plugin: The `Key' block "
452              "needs exactly one string argument.");
453     return (-1);
454   }
455
456   key = (cj_key_t *) malloc (sizeof (*key));
457   if (key == NULL)
458   {
459     ERROR ("curl_json plugin: malloc failed.");
460     return (-1);
461   }
462   memset (key, 0, sizeof (*key));
463   key->magic = CJ_KEY_MAGIC;
464
465   if (strcasecmp ("Key", ci->key) == 0)
466   {
467     status = cf_util_get_string (ci, &key->path);
468     if (status != 0)
469     {
470       sfree (key);
471       return (status);
472     }
473   }
474   else
475   {
476     ERROR ("curl_json plugin: cj_config: "
477            "Invalid key: %s", ci->key);
478     return (-1);
479   }
480
481   status = 0;
482   for (i = 0; i < ci->children_num; i++)
483   {
484     oconfig_item_t *child = ci->children + i;
485
486     if (strcasecmp ("Type", child->key) == 0)
487       status = cf_util_get_string (child, &key->type);
488     else if (strcasecmp ("Instance", child->key) == 0)
489       status = cf_util_get_string (child, &key->instance);
490     else
491     {
492       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
493       status = -1;
494     }
495
496     if (status != 0)
497       break;
498   } /* for (i = 0; i < ci->children_num; i++) */
499
500   while (status == 0)
501   {
502     if (key->type == NULL)
503     {
504       WARNING ("curl_json plugin: `Type' missing in `Key' block.");
505       status = -1;
506     }
507
508     break;
509   } /* while (status == 0) */
510
511   /* store path in a tree that will match the json map structure, example:
512    * "httpd/requests/count",
513    * "httpd/requests/current" ->
514    * { "httpd": { "requests": { "count": $key, "current": $key } } }
515    */
516   if (status == 0)
517   {
518     char *ptr;
519     char *name;
520     char ent[PATH_MAX];
521     c_avl_tree_t *tree;
522
523     if (db->tree == NULL)
524       db->tree = cj_avl_create();
525
526     tree = db->tree;
527     name = key->path;
528     ptr = key->path;
529     if (*ptr == '/')
530       ++ptr;
531
532     name = ptr;
533     while (*ptr)
534     {
535       if (*ptr == '/')
536       {
537         c_avl_tree_t *value;
538         int len;
539
540         len = ptr-name;
541         if (len == 0)
542           break;
543         sstrncpy (ent, name, len+1);
544
545         if (c_avl_get (tree, ent, (void *) &value) != 0)
546         {
547           value = cj_avl_create ();
548           c_avl_insert (tree, strdup (ent), value);
549         }
550
551         tree = value;
552         name = ptr+1;
553       }
554       ++ptr;
555     }
556     if (*name)
557       c_avl_insert (tree, strdup(name), key);
558     else
559     {
560       ERROR ("curl_json plugin: invalid key: %s", key->path);
561       status = -1;
562     }
563   }
564
565   return (status);
566 } /* }}} int cj_config_add_key */
567
568 static int cj_init_curl (cj_t *db) /* {{{ */
569 {
570   db->curl = curl_easy_init ();
571   if (db->curl == NULL)
572   {
573     ERROR ("curl_json plugin: curl_easy_init failed.");
574     return (-1);
575   }
576
577   curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
578   curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
579   curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
580   curl_easy_setopt (db->curl, CURLOPT_USERAGENT,
581                     PACKAGE_NAME"/"PACKAGE_VERSION);
582   curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
583   curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
584
585   if (db->user != NULL)
586   {
587     size_t credentials_size;
588
589     credentials_size = strlen (db->user) + 2;
590     if (db->pass != NULL)
591       credentials_size += strlen (db->pass);
592
593     db->credentials = (char *) malloc (credentials_size);
594     if (db->credentials == NULL)
595     {
596       ERROR ("curl_json plugin: malloc failed.");
597       return (-1);
598     }
599
600     ssnprintf (db->credentials, credentials_size, "%s:%s",
601                db->user, (db->pass == NULL) ? "" : db->pass);
602     curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
603   }
604
605   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
606   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
607                     db->verify_host ? 2L : 0L);
608   if (db->cacert != NULL)
609     curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
610   if (db->headers != NULL)
611     curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
612   if (db->post_body != NULL)
613     curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
614
615   return (0);
616 } /* }}} int cj_init_curl */
617
618 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
619 {
620   cj_t *db;
621   int status = 0;
622   int i;
623
624   if ((ci->values_num != 1)
625       || (ci->values[0].type != OCONFIG_TYPE_STRING))
626   {
627     WARNING ("curl_json plugin: The `URL' block "
628              "needs exactly one string argument.");
629     return (-1);
630   }
631
632   db = (cj_t *) malloc (sizeof (*db));
633   if (db == NULL)
634   {
635     ERROR ("curl_json plugin: malloc failed.");
636     return (-1);
637   }
638   memset (db, 0, sizeof (*db));
639
640   if (strcasecmp ("URL", ci->key) == 0)
641     status = cf_util_get_string (ci, &db->url);
642   else if (strcasecmp ("Sock", ci->key) == 0)
643     status = cf_util_get_string (ci, &db->sock);
644   else
645   {
646     ERROR ("curl_json plugin: cj_config: "
647            "Invalid key: %s", ci->key);
648     return (-1);
649   }
650   if (status != 0)
651   {
652     sfree (db);
653     return (status);
654   }
655
656   /* Fill the `cj_t' structure.. */
657   for (i = 0; i < ci->children_num; i++)
658   {
659     oconfig_item_t *child = ci->children + i;
660
661     if (strcasecmp ("Instance", child->key) == 0)
662       status = cf_util_get_string (child, &db->instance);
663     else if (strcasecmp ("Host", child->key) == 0)
664       status = cf_util_get_string (child, &db->host);
665     else if (db->url && strcasecmp ("User", child->key) == 0)
666       status = cf_util_get_string (child, &db->user);
667     else if (db->url && strcasecmp ("Password", child->key) == 0)
668       status = cf_util_get_string (child, &db->pass);
669     else if (db->url && strcasecmp ("VerifyPeer", child->key) == 0)
670       status = cf_util_get_boolean (child, &db->verify_peer);
671     else if (db->url && strcasecmp ("VerifyHost", child->key) == 0)
672       status = cf_util_get_boolean (child, &db->verify_host);
673     else if (db->url && strcasecmp ("CACert", child->key) == 0)
674       status = cf_util_get_string (child, &db->cacert);
675     else if (db->url && strcasecmp ("Header", child->key) == 0)
676       status = cj_config_append_string ("Header", &db->headers, child);
677     else if (db->url && strcasecmp ("Post", child->key) == 0)
678       status = cf_util_get_string (child, &db->post_body);
679     else if (strcasecmp ("Key", child->key) == 0)
680       status = cj_config_add_key (db, child);
681     else
682     {
683       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
684       status = -1;
685     }
686
687     if (status != 0)
688       break;
689   }
690
691   if (status == 0)
692   {
693     if (db->tree == NULL)
694     {
695       WARNING ("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
696                db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
697       status = -1;
698     }
699     if (status == 0 && db->url)
700       status = cj_init_curl (db);
701   }
702
703   /* If all went well, register this database for reading */
704   if (status == 0)
705   {
706     user_data_t ud;
707     char cb_name[DATA_MAX_NAME_LEN];
708
709     if (db->instance == NULL)
710       db->instance = strdup("default");
711
712     DEBUG ("curl_json plugin: Registering new read callback: %s",
713            db->instance);
714
715     memset (&ud, 0, sizeof (ud));
716     ud.data = (void *) db;
717     ud.free_func = cj_free;
718
719     ssnprintf (cb_name, sizeof (cb_name), "curl_json-%s-%s",
720                db->instance, db->url ? db->url : db->sock);
721
722     plugin_register_complex_read (/* group = */ NULL, cb_name, cj_read,
723                                   /* interval = */ NULL, &ud);
724   }
725   else
726   {
727     cj_free (db);
728     return (-1);
729   }
730
731   return (0);
732 }
733  /* }}} int cj_config_add_database */
734
735 static int cj_config (oconfig_item_t *ci) /* {{{ */
736 {
737   int success;
738   int errors;
739   int status;
740   int i;
741
742   success = 0;
743   errors = 0;
744
745   for (i = 0; i < ci->children_num; i++)
746   {
747     oconfig_item_t *child = ci->children + i;
748
749     if (strcasecmp ("Sock", child->key) == 0
750         || strcasecmp ("URL", child->key) == 0)
751     {
752       status = cj_config_add_url (child);
753       if (status == 0)
754         success++;
755       else
756         errors++;
757     }
758     else
759     {
760       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
761       errors++;
762     }
763   }
764
765   if ((success == 0) && (errors > 0))
766   {
767     ERROR ("curl_json plugin: All statements failed.");
768     return (-1);
769   }
770
771   return (0);
772 } /* }}} int cj_config */
773
774 /* }}} End of configuration handling functions */
775
776 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
777 {
778   value_list_t vl = VALUE_LIST_INIT;
779   char *host;
780
781   vl.values     = value;
782   vl.values_len = 1;
783
784   if ((db->host == NULL)
785       || (strcmp ("", db->host) == 0)
786       || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
787     host = hostname_g;
788   else
789     host = db->host;
790
791   if (key->instance == NULL)
792   {
793     if ((db->depth == 0) || (strcmp ("", db->state[db->depth-1].name) == 0))
794       sstrncpy (vl.type_instance, db->state[db->depth].name, sizeof (vl.type_instance));
795     else
796       ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
797           db->state[db->depth-1].name, db->state[db->depth].name);
798   }
799   else
800     sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
801
802   sstrncpy (vl.host, host, sizeof (vl.host));
803   sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
804   sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
805   sstrncpy (vl.type, key->type, sizeof (vl.type));
806
807   plugin_dispatch_values (&vl);
808 } /* }}} int cj_submit */
809
810 static int cj_sock_perform (cj_t *db) /* {{{ */
811 {
812   char errbuf[1024];
813   struct sockaddr_un sa_unix = {};
814   sa_unix.sun_family = AF_UNIX;
815   sstrncpy (sa_unix.sun_path, db->sock, sizeof (sa_unix.sun_path));
816
817   int fd = socket (AF_UNIX, SOCK_STREAM, 0);
818   if (fd < 0)
819     return (-1);
820   if (connect (fd, (struct sockaddr *)&sa_unix, sizeof(sa_unix)) < 0)
821   {
822     ERROR ("curl_json plugin: connect(%s) failed: %s",
823            (db->sock != NULL) ? db->sock : "<null>",
824            sstrerror(errno, errbuf, sizeof (errbuf)));
825     close (fd);
826     return (-1);
827   }
828
829   ssize_t red;
830   do {
831     unsigned char buffer[4096];
832     red = read (fd, buffer, sizeof(buffer));
833     if (red < 0) {
834         ERROR ("curl_json plugin: read(%s) failed: %s",
835                (db->sock != NULL) ? db->sock : "<null>",
836                sstrerror(errno, errbuf, sizeof (errbuf)));
837         close (fd);
838         return (-1);
839     }
840     if (!cj_curl_callback (buffer, red, 1, db))
841         break;
842   } while (red > 0);
843   close (fd);
844   return (0);
845 } /* }}} int cj_sock_perform */
846
847
848 static int cj_curl_perform(cj_t *db) /* {{{ */
849 {
850   int status;
851   long rc;
852   char *url;
853   url = NULL;
854   curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
855
856   status = curl_easy_perform (db->curl);
857   if (status != CURLE_OK)
858   {
859     ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
860            status, db->curl_errbuf, (url != NULL) ? url : "<null>");
861     return (-1);
862   }
863
864   curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
865
866   /* The response code is zero if a non-HTTP transport was used. */
867   if ((rc != 0) && (rc != 200))
868   {
869     ERROR ("curl_json plugin: curl_easy_perform failed with "
870         "response code %ld (%s)", rc, url);
871     return (-1);
872   }
873   return (0);
874 } /* }}} int cj_curl_perform */
875
876 static int cj_perform (cj_t *db) /* {{{ */
877 {
878   int status;
879   yajl_handle yprev = db->yajl;
880
881   db->yajl = yajl_alloc (&ycallbacks,
882 #if HAVE_YAJL_V2
883       /* alloc funcs = */ NULL,
884 #else
885       /* alloc funcs = */ NULL, NULL,
886 #endif
887       /* context = */ (void *)db);
888   if (db->yajl == NULL)
889   {
890     ERROR ("curl_json plugin: yajl_alloc failed.");
891     db->yajl = yprev;
892     return (-1);
893   }
894
895   if (db->url)
896     status = cj_curl_perform (db);
897   else
898     status = cj_sock_perform (db);
899   if (status < 0)
900   {
901     yajl_free (db->yajl);
902     db->yajl = yprev;
903     return (-1);
904   }
905
906 #if HAVE_YAJL_V2
907     status = yajl_complete_parse(db->yajl);
908 #else
909     status = yajl_parse_complete(db->yajl);
910 #endif
911   if (status != yajl_status_ok)
912   {
913     unsigned char *errmsg;
914
915     errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
916         /* jsonText = */ NULL, /* jsonTextLen = */ 0);
917     ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
918         (char *) errmsg);
919     yajl_free_error (db->yajl, errmsg);
920     yajl_free (db->yajl);
921     db->yajl = yprev;
922     return (-1);
923   }
924
925   yajl_free (db->yajl);
926   db->yajl = yprev;
927   return (0);
928 } /* }}} int cj_perform */
929
930 static int cj_read (user_data_t *ud) /* {{{ */
931 {
932   cj_t *db;
933
934   if ((ud == NULL) || (ud->data == NULL))
935   {
936     ERROR ("curl_json plugin: cj_read: Invalid user data.");
937     return (-1);
938   }
939
940   db = (cj_t *) ud->data;
941
942   db->depth = 0;
943   memset (&db->state, 0, sizeof(db->state));
944   db->state[db->depth].tree = db->tree;
945   db->key = NULL;
946
947   return cj_perform (db);
948 } /* }}} int cj_read */
949
950 void module_register (void)
951 {
952   plugin_register_complex_config ("curl_json", cj_config);
953 } /* void module_register */
954
955 /* vim: set sw=2 sts=2 et fdm=marker : */