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