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