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