Merge branch 'collectd-5.3' into collectd-5.4
[collectd.git] / src / curl_json.c
1 /**
2  * collectd - src/curl_json.c
3  * Copyright (C) 2009       Doug MacEachern
4  * Copyright (C) 2006-2013  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   unsigned long magic;
57   char *path;
58   char *type;
59   char *instance;
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 update_key)
182 {
183   cj_t *db = (cj_t *)ctx;
184
185   if (!db->state[db->depth].in_array)
186     return;
187
188   db->state[db->depth].index++;
189
190   if (update_key)
191   {
192     char name[DATA_MAX_NAME_LEN];
193
194     ssnprintf (name, sizeof (name), "%d", db->state[db->depth].index - 1);
195
196     cj_cb_map_key (ctx, (unsigned char *)name, (yajl_len_t) strlen (name));
197   }
198 }
199
200 /* yajl callbacks */
201 #define CJ_CB_ABORT    0
202 #define CJ_CB_CONTINUE 1
203
204 static int cj_cb_boolean (void * ctx, int boolVal)
205 {
206   cj_cb_inc_array_index (ctx, /* update_key = */ 0);
207   return (CJ_CB_CONTINUE);
208 }
209
210 static int cj_cb_null (void * ctx)
211 {
212   cj_cb_inc_array_index (ctx, /* update_key = */ 0);
213   return (CJ_CB_CONTINUE);
214 }
215
216 static int cj_cb_number (void *ctx,
217     const char *number, yajl_len_t number_len)
218 {
219   char buffer[number_len + 1];
220
221   cj_t *db = (cj_t *)ctx;
222   cj_key_t *key = db->state[db->depth].key;
223   value_t vt;
224   int type;
225   int status;
226
227   /* Create a null-terminated version of the string. */
228   memcpy (buffer, number, number_len);
229   buffer[sizeof (buffer) - 1] = 0;
230
231   if ((key == NULL) || !CJ_IS_KEY (key)) {
232     if (key != NULL)
233       NOTICE ("curl_json plugin: Found \"%s\", but the configuration expects"
234               " a map.", buffer);
235     cj_cb_inc_array_index (ctx, /* update_key = */ 0);
236     return (CJ_CB_CONTINUE);
237   } else {
238     cj_cb_inc_array_index (ctx, /* update_key = */ 1);
239   }
240
241   type = cj_get_type (key);
242   status = parse_value (buffer, &vt, type);
243   if (status != 0)
244   {
245     NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
246     return (CJ_CB_CONTINUE);
247   }
248
249   cj_submit (db, key, &vt);
250   return (CJ_CB_CONTINUE);
251 } /* int cj_cb_number */
252
253 /* Queries the key-tree of the parent context for "in_name" and, if found,
254  * updates the "key" field of the current context. Otherwise, "key" is set to
255  * NULL. */
256 static int cj_cb_map_key (void *ctx,
257     unsigned char const *in_name, yajl_len_t in_name_len)
258 {
259   cj_t *db = (cj_t *)ctx;
260   c_avl_tree_t *tree;
261
262   tree = db->state[db->depth-1].tree;
263
264   if (tree != NULL)
265   {
266     cj_key_t *value = NULL;
267     char *name;
268     size_t name_len;
269
270     /* Create a null-terminated version of the name. */
271     name = db->state[db->depth].name;
272     name_len = COUCH_MIN ((size_t) in_name_len,
273         sizeof (db->state[db->depth].name) - 1);
274     memcpy (name, in_name, name_len);
275     name[name_len] = 0;
276
277     if (c_avl_get (tree, name, (void *) &value) == 0)
278       db->state[db->depth].key = value;
279     else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
280       db->state[db->depth].key = value;
281     else
282       db->state[db->depth].key = NULL;
283   }
284
285   return (CJ_CB_CONTINUE);
286 }
287
288 static int cj_cb_string (void *ctx, const unsigned char *val,
289     yajl_len_t len)
290 {
291   /* Handle the string as if it was a number. */
292   return (cj_cb_number (ctx, (const char *) val, len));
293 } /* int cj_cb_string */
294
295 static int cj_cb_start (void *ctx)
296 {
297   cj_t *db = (cj_t *)ctx;
298   if (++db->depth >= YAJL_MAX_DEPTH)
299   {
300     ERROR ("curl_json plugin: %s depth exceeds max, aborting.",
301            db->url ? db->url : db->sock);
302     return (CJ_CB_ABORT);
303   }
304   return (CJ_CB_CONTINUE);
305 }
306
307 static int cj_cb_end (void *ctx)
308 {
309   cj_t *db = (cj_t *)ctx;
310   db->state[db->depth].tree = NULL;
311   --db->depth;
312   return (CJ_CB_CONTINUE);
313 }
314
315 static int cj_cb_start_map (void *ctx)
316 {
317   cj_cb_inc_array_index (ctx, /* update_key = */ 1);
318   return cj_cb_start (ctx);
319 }
320
321 static int cj_cb_end_map (void *ctx)
322 {
323   return cj_cb_end (ctx);
324 }
325
326 static int cj_cb_start_array (void * ctx)
327 {
328   cj_t *db = (cj_t *)ctx;
329   cj_cb_inc_array_index (ctx, /* update_key = */ 1);
330   if (db->depth+1 < YAJL_MAX_DEPTH) {
331     db->state[db->depth+1].in_array = 1;
332     db->state[db->depth+1].index = 0;
333   }
334   return cj_cb_start (ctx);
335 }
336
337 static int cj_cb_end_array (void * ctx)
338 {
339   cj_t *db = (cj_t *)ctx;
340   db->state[db->depth].in_array = 0;
341   return cj_cb_end (ctx);
342 }
343
344 static yajl_callbacks ycallbacks = {
345   cj_cb_null, /* null */
346   cj_cb_boolean, /* boolean */
347   NULL, /* integer */
348   NULL, /* double */
349   cj_cb_number,
350   cj_cb_string,
351   cj_cb_start_map,
352   cj_cb_map_key,
353   cj_cb_end_map,
354   cj_cb_start_array,
355   cj_cb_end_array
356 };
357
358 /* end yajl callbacks */
359
360 static void cj_key_free (cj_key_t *key) /* {{{ */
361 {
362   if (key == NULL)
363     return;
364
365   sfree (key->path);
366   sfree (key->type);
367   sfree (key->instance);
368
369   sfree (key);
370 } /* }}} void cj_key_free */
371
372 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
373 {
374   char *name;
375   void *value;
376
377   while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
378   {
379     cj_key_t *key = (cj_key_t *)value;
380
381     if (CJ_IS_KEY(key))
382       cj_key_free (key);
383     else
384       cj_tree_free ((c_avl_tree_t *)value);
385
386     sfree (name);
387   }
388
389   c_avl_destroy (tree);
390 } /* }}} void cj_tree_free */
391
392 static void cj_free (void *arg) /* {{{ */
393 {
394   cj_t *db;
395
396   DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
397
398   db = (cj_t *) arg;
399
400   if (db == NULL)
401     return;
402
403   if (db->curl != NULL)
404     curl_easy_cleanup (db->curl);
405   db->curl = NULL;
406
407   if (db->tree != NULL)
408     cj_tree_free (db->tree);
409   db->tree = NULL;
410
411   sfree (db->instance);
412   sfree (db->host);
413
414   sfree (db->sock);
415
416   sfree (db->url);
417   sfree (db->user);
418   sfree (db->pass);
419   sfree (db->credentials);
420   sfree (db->cacert);
421   sfree (db->post_body);
422   curl_slist_free_all (db->headers);
423
424   sfree (db);
425 } /* }}} void cj_free */
426
427 /* Configuration handling functions {{{ */
428
429 static c_avl_tree_t *cj_avl_create(void)
430 {
431   return c_avl_create ((int (*) (const void *, const void *)) strcmp);
432 }
433
434 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
435     oconfig_item_t *ci)
436 {
437   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
438   {
439     WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
440     return (-1);
441   }
442
443   *dest = curl_slist_append(*dest, ci->values[0].value.string);
444   if (*dest == NULL)
445     return (-1);
446
447   return (0);
448 } /* }}} int cj_config_append_string */
449
450 static int cj_config_add_key (cj_t *db, /* {{{ */
451                                    oconfig_item_t *ci)
452 {
453   cj_key_t *key;
454   int status;
455   int i;
456
457   if ((ci->values_num != 1)
458       || (ci->values[0].type != OCONFIG_TYPE_STRING))
459   {
460     WARNING ("curl_json plugin: The `Key' block "
461              "needs exactly one string argument.");
462     return (-1);
463   }
464
465   key = (cj_key_t *) malloc (sizeof (*key));
466   if (key == NULL)
467   {
468     ERROR ("curl_json plugin: malloc failed.");
469     return (-1);
470   }
471   memset (key, 0, sizeof (*key));
472   key->magic = CJ_KEY_MAGIC;
473
474   if (strcasecmp ("Key", ci->key) == 0)
475   {
476     status = cf_util_get_string (ci, &key->path);
477     if (status != 0)
478     {
479       sfree (key);
480       return (status);
481     }
482   }
483   else
484   {
485     ERROR ("curl_json plugin: cj_config: "
486            "Invalid key: %s", ci->key);
487     return (-1);
488   }
489
490   status = 0;
491   for (i = 0; i < ci->children_num; i++)
492   {
493     oconfig_item_t *child = ci->children + i;
494
495     if (strcasecmp ("Type", child->key) == 0)
496       status = cf_util_get_string (child, &key->type);
497     else if (strcasecmp ("Instance", child->key) == 0)
498       status = cf_util_get_string (child, &key->instance);
499     else
500     {
501       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
502       status = -1;
503     }
504
505     if (status != 0)
506       break;
507   } /* for (i = 0; i < ci->children_num; i++) */
508
509   while (status == 0)
510   {
511     if (key->type == NULL)
512     {
513       WARNING ("curl_json plugin: `Type' missing in `Key' block.");
514       status = -1;
515     }
516
517     break;
518   } /* while (status == 0) */
519
520   /* store path in a tree that will match the json map structure, example:
521    * "httpd/requests/count",
522    * "httpd/requests/current" ->
523    * { "httpd": { "requests": { "count": $key, "current": $key } } }
524    */
525   if (status == 0)
526   {
527     char *ptr;
528     char *name;
529     char ent[PATH_MAX];
530     c_avl_tree_t *tree;
531
532     if (db->tree == NULL)
533       db->tree = cj_avl_create();
534
535     tree = db->tree;
536     name = key->path;
537     ptr = key->path;
538     if (*ptr == '/')
539       ++ptr;
540
541     name = ptr;
542     while (*ptr)
543     {
544       if (*ptr == '/')
545       {
546         c_avl_tree_t *value;
547         int len;
548
549         len = ptr-name;
550         if (len == 0)
551           break;
552         len = COUCH_MIN(len, sizeof (ent)-1);
553         sstrncpy (ent, name, len+1);
554
555         if (c_avl_get (tree, ent, (void *) &value) != 0)
556         {
557           value = cj_avl_create ();
558           c_avl_insert (tree, strdup (ent), value);
559         }
560
561         tree = value;
562         name = ptr+1;
563       }
564       ++ptr;
565     }
566     if (*name)
567       c_avl_insert (tree, strdup(name), key);
568     else
569     {
570       ERROR ("curl_json plugin: invalid key: %s", key->path);
571       status = -1;
572     }
573   }
574
575   return (status);
576 } /* }}} int cj_config_add_key */
577
578 static int cj_init_curl (cj_t *db) /* {{{ */
579 {
580   db->curl = curl_easy_init ();
581   if (db->curl == NULL)
582   {
583     ERROR ("curl_json plugin: curl_easy_init failed.");
584     return (-1);
585   }
586
587   curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
588   curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
589   curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
590   curl_easy_setopt (db->curl, CURLOPT_USERAGENT,
591                     PACKAGE_NAME"/"PACKAGE_VERSION);
592   curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
593   curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
594
595   if (db->user != NULL)
596   {
597     size_t credentials_size;
598
599     credentials_size = strlen (db->user) + 2;
600     if (db->pass != NULL)
601       credentials_size += strlen (db->pass);
602
603     db->credentials = (char *) malloc (credentials_size);
604     if (db->credentials == NULL)
605     {
606       ERROR ("curl_json plugin: malloc failed.");
607       return (-1);
608     }
609
610     ssnprintf (db->credentials, credentials_size, "%s:%s",
611                db->user, (db->pass == NULL) ? "" : db->pass);
612     curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
613   }
614
615   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
616   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
617                     db->verify_host ? 2L : 0L);
618   if (db->cacert != NULL)
619     curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
620   if (db->headers != NULL)
621     curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
622   if (db->post_body != NULL)
623     curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
624
625   return (0);
626 } /* }}} int cj_init_curl */
627
628 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
629 {
630   cj_t *db;
631   int status = 0;
632   int i;
633
634   if ((ci->values_num != 1)
635       || (ci->values[0].type != OCONFIG_TYPE_STRING))
636   {
637     WARNING ("curl_json plugin: The `URL' block "
638              "needs exactly one string argument.");
639     return (-1);
640   }
641
642   db = (cj_t *) malloc (sizeof (*db));
643   if (db == NULL)
644   {
645     ERROR ("curl_json plugin: malloc failed.");
646     return (-1);
647   }
648   memset (db, 0, sizeof (*db));
649
650   if (strcasecmp ("URL", ci->key) == 0)
651     status = cf_util_get_string (ci, &db->url);
652   else if (strcasecmp ("Sock", ci->key) == 0)
653     status = cf_util_get_string (ci, &db->sock);
654   else
655   {
656     ERROR ("curl_json plugin: cj_config: "
657            "Invalid key: %s", ci->key);
658     return (-1);
659   }
660   if (status != 0)
661   {
662     sfree (db);
663     return (status);
664   }
665
666   /* Fill the `cj_t' structure.. */
667   for (i = 0; i < ci->children_num; i++)
668   {
669     oconfig_item_t *child = ci->children + i;
670
671     if (strcasecmp ("Instance", child->key) == 0)
672       status = cf_util_get_string (child, &db->instance);
673     else if (strcasecmp ("Host", child->key) == 0)
674       status = cf_util_get_string (child, &db->host);
675     else if (db->url && strcasecmp ("User", child->key) == 0)
676       status = cf_util_get_string (child, &db->user);
677     else if (db->url && strcasecmp ("Password", child->key) == 0)
678       status = cf_util_get_string (child, &db->pass);
679     else if (db->url && strcasecmp ("VerifyPeer", child->key) == 0)
680       status = cf_util_get_boolean (child, &db->verify_peer);
681     else if (db->url && strcasecmp ("VerifyHost", child->key) == 0)
682       status = cf_util_get_boolean (child, &db->verify_host);
683     else if (db->url && strcasecmp ("CACert", child->key) == 0)
684       status = cf_util_get_string (child, &db->cacert);
685     else if (db->url && strcasecmp ("Header", child->key) == 0)
686       status = cj_config_append_string ("Header", &db->headers, child);
687     else if (db->url && strcasecmp ("Post", child->key) == 0)
688       status = cf_util_get_string (child, &db->post_body);
689     else if (strcasecmp ("Key", child->key) == 0)
690       status = cj_config_add_key (db, child);
691     else
692     {
693       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
694       status = -1;
695     }
696
697     if (status != 0)
698       break;
699   }
700
701   if (status == 0)
702   {
703     if (db->tree == NULL)
704     {
705       WARNING ("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
706                db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
707       status = -1;
708     }
709     if (status == 0 && db->url)
710       status = cj_init_curl (db);
711   }
712
713   /* If all went well, register this database for reading */
714   if (status == 0)
715   {
716     user_data_t ud;
717     char *cb_name;
718
719     if (db->instance == NULL)
720       db->instance = strdup("default");
721
722     DEBUG ("curl_json plugin: Registering new read callback: %s",
723            db->instance);
724
725     memset (&ud, 0, sizeof (ud));
726     ud.data = (void *) db;
727     ud.free_func = cj_free;
728
729     cb_name = ssnprintf_alloc ("curl_json-%s-%s",
730                db->instance, db->url ? db->url : db->sock);
731
732     plugin_register_complex_read (/* group = */ "curl_json", cb_name, cj_read,
733                                   /* interval = */ NULL, &ud);
734     sfree (cb_name);
735   }
736   else
737   {
738     cj_free (db);
739     return (-1);
740   }
741
742   return (0);
743 }
744  /* }}} int cj_config_add_database */
745
746 static int cj_config (oconfig_item_t *ci) /* {{{ */
747 {
748   int success;
749   int errors;
750   int status;
751   int i;
752
753   success = 0;
754   errors = 0;
755
756   for (i = 0; i < ci->children_num; i++)
757   {
758     oconfig_item_t *child = ci->children + i;
759
760     if (strcasecmp ("Sock", child->key) == 0
761         || strcasecmp ("URL", child->key) == 0)
762     {
763       status = cj_config_add_url (child);
764       if (status == 0)
765         success++;
766       else
767         errors++;
768     }
769     else
770     {
771       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
772       errors++;
773     }
774   }
775
776   if ((success == 0) && (errors > 0))
777   {
778     ERROR ("curl_json plugin: All statements failed.");
779     return (-1);
780   }
781
782   return (0);
783 } /* }}} int cj_config */
784
785 /* }}} End of configuration handling functions */
786
787 static void cj_submit (cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
788 {
789   value_list_t vl = VALUE_LIST_INIT;
790   char *host;
791
792   vl.values     = value;
793   vl.values_len = 1;
794
795   if ((db->host == NULL)
796       || (strcmp ("", db->host) == 0)
797       || (strcmp (CJ_DEFAULT_HOST, db->host) == 0))
798     host = hostname_g;
799   else
800     host = db->host;
801
802   if (key->instance == NULL)
803   {
804     if ((db->depth == 0) || (strcmp ("", db->state[db->depth-1].name) == 0))
805       sstrncpy (vl.type_instance, db->state[db->depth].name, sizeof (vl.type_instance));
806     else
807       ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
808           db->state[db->depth-1].name, db->state[db->depth].name);
809   }
810   else
811     sstrncpy (vl.type_instance, key->instance, sizeof (vl.type_instance));
812
813   sstrncpy (vl.host, host, sizeof (vl.host));
814   sstrncpy (vl.plugin, "curl_json", sizeof (vl.plugin));
815   sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
816   sstrncpy (vl.type, key->type, sizeof (vl.type));
817
818   plugin_dispatch_values (&vl);
819 } /* }}} int cj_submit */
820
821 static int cj_sock_perform (cj_t *db) /* {{{ */
822 {
823   char errbuf[1024];
824   struct sockaddr_un sa_unix = {};
825   sa_unix.sun_family = AF_UNIX;
826   sstrncpy (sa_unix.sun_path, db->sock, sizeof (sa_unix.sun_path));
827
828   int fd = socket (AF_UNIX, SOCK_STREAM, 0);
829   if (fd < 0)
830     return (-1);
831   if (connect (fd, (struct sockaddr *)&sa_unix, sizeof(sa_unix)) < 0)
832   {
833     ERROR ("curl_json plugin: connect(%s) failed: %s",
834            (db->sock != NULL) ? db->sock : "<null>",
835            sstrerror(errno, errbuf, sizeof (errbuf)));
836     close (fd);
837     return (-1);
838   }
839
840   ssize_t red;
841   do {
842     unsigned char buffer[4096];
843     red = read (fd, buffer, sizeof(buffer));
844     if (red < 0) {
845         ERROR ("curl_json plugin: read(%s) failed: %s",
846                (db->sock != NULL) ? db->sock : "<null>",
847                sstrerror(errno, errbuf, sizeof (errbuf)));
848         close (fd);
849         return (-1);
850     }
851     if (!cj_curl_callback (buffer, red, 1, db))
852         break;
853   } while (red > 0);
854   close (fd);
855   return (0);
856 } /* }}} int cj_sock_perform */
857
858
859 static int cj_curl_perform(cj_t *db) /* {{{ */
860 {
861   int status;
862   long rc;
863   char *url;
864   url = db->url;
865
866   status = curl_easy_perform (db->curl);
867   if (status != CURLE_OK)
868   {
869     ERROR ("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
870            status, db->curl_errbuf, url);
871     return (-1);
872   }
873
874   curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
875   curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
876
877   /* The response code is zero if a non-HTTP transport was used. */
878   if ((rc != 0) && (rc != 200))
879   {
880     ERROR ("curl_json plugin: curl_easy_perform failed with "
881         "response code %ld (%s)", rc, url);
882     return (-1);
883   }
884   return (0);
885 } /* }}} int cj_curl_perform */
886
887 static int cj_perform (cj_t *db) /* {{{ */
888 {
889   int status;
890   yajl_handle yprev = db->yajl;
891
892   db->yajl = yajl_alloc (&ycallbacks,
893 #if HAVE_YAJL_V2
894       /* alloc funcs = */ NULL,
895 #else
896       /* alloc funcs = */ NULL, NULL,
897 #endif
898       /* context = */ (void *)db);
899   if (db->yajl == NULL)
900   {
901     ERROR ("curl_json plugin: yajl_alloc failed.");
902     db->yajl = yprev;
903     return (-1);
904   }
905
906   if (db->url)
907     status = cj_curl_perform (db);
908   else
909     status = cj_sock_perform (db);
910   if (status < 0)
911   {
912     yajl_free (db->yajl);
913     db->yajl = yprev;
914     return (-1);
915   }
916
917 #if HAVE_YAJL_V2
918     status = yajl_complete_parse(db->yajl);
919 #else
920     status = yajl_parse_complete(db->yajl);
921 #endif
922   if (status != yajl_status_ok)
923   {
924     unsigned char *errmsg;
925
926     errmsg = yajl_get_error (db->yajl, /* verbose = */ 0,
927         /* jsonText = */ NULL, /* jsonTextLen = */ 0);
928     ERROR ("curl_json plugin: yajl_parse_complete failed: %s",
929         (char *) errmsg);
930     yajl_free_error (db->yajl, errmsg);
931     yajl_free (db->yajl);
932     db->yajl = yprev;
933     return (-1);
934   }
935
936   yajl_free (db->yajl);
937   db->yajl = yprev;
938   return (0);
939 } /* }}} int cj_perform */
940
941 static int cj_read (user_data_t *ud) /* {{{ */
942 {
943   cj_t *db;
944
945   if ((ud == NULL) || (ud->data == NULL))
946   {
947     ERROR ("curl_json plugin: cj_read: Invalid user data.");
948     return (-1);
949   }
950
951   db = (cj_t *) ud->data;
952
953   db->depth = 0;
954   memset (&db->state, 0, sizeof(db->state));
955   db->state[db->depth].tree = db->tree;
956   db->key = NULL;
957
958   return cj_perform (db);
959 } /* }}} int cj_read */
960
961 static int cj_init (void) /* {{{ */
962 {
963   /* Call this while collectd is still single-threaded to avoid
964    * initialization issues in libgcrypt. */
965   curl_global_init (CURL_GLOBAL_SSL);
966   return (0);
967 } /* }}} int cj_init */
968
969 void module_register (void)
970 {
971   plugin_register_complex_config ("curl_json", cj_config);
972   plugin_register_init ("curl_json", cj_init);
973 } /* void module_register */
974
975 /* vim: set sw=2 sts=2 et fdm=marker : */