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