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