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