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