Merge remote-tracking branch 'github/pr/2105'
[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   if (key == NULL) {
251     /* no config for this element. */
252     cj_advance_array(ctx);
253     return CJ_CB_CONTINUE;
254   } else if (!CJ_IS_KEY(key)) {
255     /* the config expects a map or an array. */
256     NOTICE(
257         "curl_json plugin: Found \"%s\", but the configuration expects a map.",
258         buffer);
259     cj_advance_array(ctx);
260     return CJ_CB_CONTINUE;
261   }
262
263   int type = cj_get_type(key);
264   value_t vt;
265   int status = parse_value(buffer, &vt, type);
266   if (status != 0) {
267     NOTICE("curl_json plugin: Unable to parse number: \"%s\"", buffer);
268     cj_advance_array(ctx);
269     return CJ_CB_CONTINUE;
270   }
271
272   cj_submit(db, key, &vt);
273   cj_advance_array(ctx);
274   return CJ_CB_CONTINUE;
275 } /* int cj_cb_number */
276
277 /* Queries the key-tree of the parent context for "in_name" and, if found,
278  * updates the "key" field of the current context. Otherwise, "key" is set to
279  * NULL. */
280 static int cj_cb_map_key(void *ctx, unsigned char const *in_name,
281                          yajl_len_t in_name_len) {
282   char name[in_name_len + 1];
283
284   memmove(name, in_name, in_name_len);
285   name[sizeof(name) - 1] = 0;
286
287   if (cj_load_key(ctx, name) != 0)
288     return CJ_CB_ABORT;
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_end(void *ctx) {
299   cj_t *db = (cj_t *)ctx;
300   db->state[db->depth].tree = NULL;
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   void *value;
369
370   while (c_avl_pick(tree, (void *)&name, (void *)&value) == 0) {
371     cj_key_t *key = (cj_key_t *)value;
372
373     if (CJ_IS_KEY(key))
374       cj_key_free(key);
375     else
376       cj_tree_free((c_avl_tree_t *)value);
377
378     sfree(name);
379   }
380
381   c_avl_destroy(tree);
382 } /* }}} void cj_tree_free */
383
384 static void cj_free(void *arg) /* {{{ */
385 {
386   cj_t *db;
387
388   DEBUG("curl_json plugin: cj_free (arg = %p);", arg);
389
390   db = (cj_t *)arg;
391
392   if (db == NULL)
393     return;
394
395   if (db->curl != NULL)
396     curl_easy_cleanup(db->curl);
397   db->curl = NULL;
398
399   if (db->tree != NULL)
400     cj_tree_free(db->tree);
401   db->tree = NULL;
402
403   sfree(db->instance);
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     c_avl_tree_t *value;
473     if (c_avl_get(tree, name, (void *)&value) != 0) {
474       value = cj_avl_create();
475       c_avl_insert(tree, strdup(name), value);
476     }
477
478     tree = value;
479     start = end + 1;
480   }
481
482   if (strlen(start) == 0) {
483     ERROR("curl_json plugin: invalid key: %s", key->path);
484     return -1;
485   }
486
487   c_avl_insert(tree, strdup(start), key);
488   return 0;
489 } /* }}} int cj_append_key */
490
491 static int cj_config_add_key(cj_t *db, /* {{{ */
492                              oconfig_item_t *ci) {
493   cj_key_t *key;
494   int status;
495
496   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
497     WARNING("curl_json plugin: The `Key' block "
498             "needs exactly one string argument.");
499     return -1;
500   }
501
502   key = calloc(1, sizeof(*key));
503   if (key == NULL) {
504     ERROR("curl_json plugin: calloc failed.");
505     return -1;
506   }
507   key->magic = CJ_KEY_MAGIC;
508
509   if (strcasecmp("Key", ci->key) == 0) {
510     status = cf_util_get_string(ci, &key->path);
511     if (status != 0) {
512       sfree(key);
513       return status;
514     }
515   } else {
516     ERROR("curl_json plugin: cj_config: "
517           "Invalid key: %s",
518           ci->key);
519     cj_key_free(key);
520     return -1;
521   }
522
523   status = 0;
524   for (int i = 0; i < ci->children_num; i++) {
525     oconfig_item_t *child = ci->children + i;
526
527     if (strcasecmp("Type", child->key) == 0)
528       status = cf_util_get_string(child, &key->type);
529     else if (strcasecmp("Instance", child->key) == 0)
530       status = cf_util_get_string(child, &key->instance);
531     else {
532       WARNING("curl_json plugin: Option `%s' not allowed here.", child->key);
533       status = -1;
534     }
535
536     if (status != 0)
537       break;
538   } /* for (i = 0; i < ci->children_num; i++) */
539
540   if (status != 0) {
541     cj_key_free(key);
542     return -1;
543   }
544
545   if (key->type == NULL) {
546     WARNING("curl_json plugin: `Type' missing in `Key' block.");
547     cj_key_free(key);
548     return -1;
549   }
550
551   status = cj_append_key(db, key);
552   if (status != 0) {
553     cj_key_free(key);
554     return -1;
555   }
556
557   return 0;
558 } /* }}} int cj_config_add_key */
559
560 static int cj_init_curl(cj_t *db) /* {{{ */
561 {
562   db->curl = curl_easy_init();
563   if (db->curl == NULL) {
564     ERROR("curl_json plugin: curl_easy_init failed.");
565     return -1;
566   }
567
568   curl_easy_setopt(db->curl, CURLOPT_NOSIGNAL, 1L);
569   curl_easy_setopt(db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
570   curl_easy_setopt(db->curl, CURLOPT_WRITEDATA, db);
571   curl_easy_setopt(db->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
572   curl_easy_setopt(db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
573   curl_easy_setopt(db->curl, CURLOPT_URL, db->url);
574   curl_easy_setopt(db->curl, CURLOPT_FOLLOWLOCATION, 1L);
575   curl_easy_setopt(db->curl, CURLOPT_MAXREDIRS, 50L);
576
577   if (db->user != NULL) {
578 #ifdef HAVE_CURLOPT_USERNAME
579     curl_easy_setopt(db->curl, CURLOPT_USERNAME, db->user);
580     curl_easy_setopt(db->curl, CURLOPT_PASSWORD,
581                      (db->pass == NULL) ? "" : db->pass);
582 #else
583     size_t credentials_size;
584
585     credentials_size = strlen(db->user) + 2;
586     if (db->pass != NULL)
587       credentials_size += strlen(db->pass);
588
589     db->credentials = malloc(credentials_size);
590     if (db->credentials == NULL) {
591       ERROR("curl_json plugin: malloc failed.");
592       return -1;
593     }
594
595     ssnprintf(db->credentials, credentials_size, "%s:%s", db->user,
596               (db->pass == NULL) ? "" : db->pass);
597     curl_easy_setopt(db->curl, CURLOPT_USERPWD, db->credentials);
598 #endif
599
600     if (db->digest)
601       curl_easy_setopt(db->curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
602   }
603
604   curl_easy_setopt(db->curl, CURLOPT_SSL_VERIFYPEER, (long)db->verify_peer);
605   curl_easy_setopt(db->curl, CURLOPT_SSL_VERIFYHOST, db->verify_host ? 2L : 0L);
606   if (db->cacert != NULL)
607     curl_easy_setopt(db->curl, CURLOPT_CAINFO, db->cacert);
608   if (db->headers != NULL)
609     curl_easy_setopt(db->curl, CURLOPT_HTTPHEADER, db->headers);
610   if (db->post_body != NULL)
611     curl_easy_setopt(db->curl, CURLOPT_POSTFIELDS, db->post_body);
612
613 #ifdef HAVE_CURLOPT_TIMEOUT_MS
614   if (db->timeout >= 0)
615     curl_easy_setopt(db->curl, CURLOPT_TIMEOUT_MS, (long)db->timeout);
616   else if (db->interval > 0)
617     curl_easy_setopt(db->curl, CURLOPT_TIMEOUT_MS,
618                      (long)CDTIME_T_TO_MS(db->interval));
619   else
620     curl_easy_setopt(db->curl, CURLOPT_TIMEOUT_MS,
621                      (long)CDTIME_T_TO_MS(plugin_get_interval()));
622 #endif
623
624   return 0;
625 } /* }}} int cj_init_curl */
626
627 static int cj_config_add_url(oconfig_item_t *ci) /* {{{ */
628 {
629   cj_t *db;
630   int status = 0;
631
632   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
633     WARNING("curl_json plugin: The `URL' block "
634             "needs exactly one string argument.");
635     return -1;
636   }
637
638   db = calloc(1, sizeof(*db));
639   if (db == NULL) {
640     ERROR("curl_json plugin: calloc failed.");
641     return -1;
642   }
643
644   db->timeout = -1;
645
646   if (strcasecmp("URL", ci->key) == 0)
647     status = cf_util_get_string(ci, &db->url);
648   else if (strcasecmp("Sock", ci->key) == 0)
649     status = cf_util_get_string(ci, &db->sock);
650   else {
651     ERROR("curl_json plugin: cj_config: "
652           "Invalid key: %s",
653           ci->key);
654     cj_free(db);
655     return -1;
656   }
657   if (status != 0) {
658     sfree(db);
659     return status;
660   }
661
662   /* Fill the `cj_t' structure.. */
663   for (int i = 0; i < ci->children_num; i++) {
664     oconfig_item_t *child = ci->children + i;
665
666     if (strcasecmp("Instance", child->key) == 0)
667       status = cf_util_get_string(child, &db->instance);
668     else if (strcasecmp("Host", child->key) == 0)
669       status = cf_util_get_string(child, &db->host);
670     else if (db->url && strcasecmp("User", child->key) == 0)
671       status = cf_util_get_string(child, &db->user);
672     else if (db->url && strcasecmp("Password", child->key) == 0)
673       status = cf_util_get_string(child, &db->pass);
674     else if (strcasecmp("Digest", child->key) == 0)
675       status = cf_util_get_boolean(child, &db->digest);
676     else if (db->url && strcasecmp("VerifyPeer", child->key) == 0)
677       status = cf_util_get_boolean(child, &db->verify_peer);
678     else if (db->url && strcasecmp("VerifyHost", child->key) == 0)
679       status = cf_util_get_boolean(child, &db->verify_host);
680     else if (db->url && strcasecmp("CACert", child->key) == 0)
681       status = cf_util_get_string(child, &db->cacert);
682     else if (db->url && strcasecmp("Header", child->key) == 0)
683       status = cj_config_append_string("Header", &db->headers, child);
684     else if (db->url && strcasecmp("Post", child->key) == 0)
685       status = cf_util_get_string(child, &db->post_body);
686     else if (strcasecmp("Key", child->key) == 0)
687       status = cj_config_add_key(db, child);
688     else if (strcasecmp("Interval", child->key) == 0)
689       status = cf_util_get_cdtime(child, &db->interval);
690     else if (strcasecmp("Timeout", child->key) == 0)
691       status = cf_util_get_int(child, &db->timeout);
692     else if (strcasecmp("Statistics", child->key) == 0) {
693       db->stats = curl_stats_from_config(child);
694       if (db->stats == NULL)
695         status = -1;
696     } else {
697       WARNING("curl_json plugin: Option `%s' not allowed here.", child->key);
698       status = -1;
699     }
700
701     if (status != 0)
702       break;
703   }
704
705   if (status == 0) {
706     if (db->tree == NULL) {
707       WARNING("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
708               db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
709       status = -1;
710     }
711     if (status == 0 && db->url)
712       status = cj_init_curl(db);
713   }
714
715   /* If all went well, register this database for reading */
716   if (status == 0) {
717     char *cb_name;
718
719     if (db->instance == NULL)
720       db->instance = strdup("default");
721
722     DEBUG("curl_json plugin: Registering new read callback: %s", db->instance);
723
724     cb_name = ssnprintf_alloc("curl_json-%s-%s", db->instance,
725                               db->url ? db->url : db->sock);
726
727     plugin_register_complex_read(/* group = */ NULL, cb_name, cj_read,
728                                  /* interval = */ db->interval,
729                                  &(user_data_t){
730                                      .data = db, .free_func = cj_free,
731                                  });
732     sfree(cb_name);
733   } else {
734     cj_free(db);
735     return -1;
736   }
737
738   return 0;
739 }
740 /* }}} int cj_config_add_database */
741
742 static int cj_config(oconfig_item_t *ci) /* {{{ */
743 {
744   int success;
745   int errors;
746   int status;
747
748   success = 0;
749   errors = 0;
750
751   for (int i = 0; i < ci->children_num; i++) {
752     oconfig_item_t *child = ci->children + i;
753
754     if (strcasecmp("Sock", child->key) == 0 ||
755         strcasecmp("URL", child->key) == 0) {
756       status = cj_config_add_url(child);
757       if (status == 0)
758         success++;
759       else
760         errors++;
761     } else {
762       WARNING("curl_json plugin: Option `%s' not allowed here.", child->key);
763       errors++;
764     }
765   }
766
767   if ((success == 0) && (errors > 0)) {
768     ERROR("curl_json plugin: All statements failed.");
769     return -1;
770   }
771
772   return 0;
773 } /* }}} int cj_config */
774
775 /* }}} End of configuration handling functions */
776
777 static const char *cj_host(cj_t *db) /* {{{ */
778 {
779   if ((db->host == NULL) || (strcmp("", db->host) == 0) ||
780       (strcmp(CJ_DEFAULT_HOST, db->host) == 0))
781     return hostname_g;
782   return db->host;
783 } /* }}} cj_host */
784
785 static void cj_submit_impl(cj_t *db, cj_key_t *key, value_t *value) /* {{{ */
786 {
787   value_list_t vl = VALUE_LIST_INIT;
788
789   vl.values = value;
790   vl.values_len = 1;
791
792   if (key->instance == NULL) {
793     int len = 0;
794     for (int i = 0; i < db->depth; i++)
795       len += ssnprintf(vl.type_instance + len, sizeof(vl.type_instance) - len,
796                        i ? "-%s" : "%s", db->state[i + 1].name);
797   } else
798     sstrncpy(vl.type_instance, key->instance, sizeof(vl.type_instance));
799
800   sstrncpy(vl.host, cj_host(db), sizeof(vl.host));
801   sstrncpy(vl.plugin, "curl_json", sizeof(vl.plugin));
802   sstrncpy(vl.plugin_instance, db->instance, sizeof(vl.plugin_instance));
803   sstrncpy(vl.type, key->type, sizeof(vl.type));
804
805   if (db->interval > 0)
806     vl.interval = db->interval;
807
808   plugin_dispatch_values(&vl);
809 } /* }}} int cj_submit_impl */
810
811 static int cj_sock_perform(cj_t *db) /* {{{ */
812 {
813   char errbuf[1024];
814   struct sockaddr_un sa_unix = {
815       .sun_family = AF_UNIX,
816   };
817   sstrncpy(sa_unix.sun_path, db->sock, sizeof(sa_unix.sun_path));
818
819   int fd = socket(AF_UNIX, SOCK_STREAM, 0);
820   if (fd < 0)
821     return -1;
822   if (connect(fd, (struct sockaddr *)&sa_unix, sizeof(sa_unix)) < 0) {
823     ERROR("curl_json plugin: connect(%s) failed: %s",
824           (db->sock != NULL) ? db->sock : "<null>",
825           sstrerror(errno, errbuf, sizeof(errbuf)));
826     close(fd);
827     return -1;
828   }
829
830   ssize_t red;
831   do {
832     unsigned char buffer[4096];
833     red = read(fd, buffer, sizeof(buffer));
834     if (red < 0) {
835       ERROR("curl_json plugin: read(%s) failed: %s",
836             (db->sock != NULL) ? db->sock : "<null>",
837             sstrerror(errno, errbuf, sizeof(errbuf)));
838       close(fd);
839       return -1;
840     }
841     if (!cj_curl_callback(buffer, red, 1, db))
842       break;
843   } while (red > 0);
844   close(fd);
845   return 0;
846 } /* }}} int cj_sock_perform */
847
848 static int cj_curl_perform(cj_t *db) /* {{{ */
849 {
850   int status;
851   long rc;
852   char *url;
853   url = db->url;
854
855   status = curl_easy_perform(db->curl);
856   if (status != CURLE_OK) {
857     ERROR("curl_json plugin: curl_easy_perform failed with status %i: %s (%s)",
858           status, db->curl_errbuf, url);
859     return -1;
860   }
861   if (db->stats != NULL)
862     curl_stats_dispatch(db->stats, db->curl, cj_host(db), "curl_json",
863                         db->instance);
864
865   curl_easy_getinfo(db->curl, CURLINFO_EFFECTIVE_URL, &url);
866   curl_easy_getinfo(db->curl, CURLINFO_RESPONSE_CODE, &rc);
867
868   /* The response code is zero if a non-HTTP transport was used. */
869   if ((rc != 0) && (rc != 200)) {
870     ERROR("curl_json plugin: curl_easy_perform failed with "
871           "response code %ld (%s)",
872           rc, url);
873     return -1;
874   }
875   return 0;
876 } /* }}} int cj_curl_perform */
877
878 static int cj_perform(cj_t *db) /* {{{ */
879 {
880   int status;
881   yajl_handle yprev = db->yajl;
882
883   db->yajl = yajl_alloc(&ycallbacks,
884 #if HAVE_YAJL_V2
885                         /* alloc funcs = */ NULL,
886 #else
887                         /* alloc funcs = */ NULL, NULL,
888 #endif
889                         /* context = */ (void *)db);
890   if (db->yajl == NULL) {
891     ERROR("curl_json plugin: yajl_alloc failed.");
892     db->yajl = yprev;
893     return -1;
894   }
895
896   if (db->url)
897     status = cj_curl_perform(db);
898   else
899     status = cj_sock_perform(db);
900   if (status < 0) {
901     yajl_free(db->yajl);
902     db->yajl = yprev;
903     return -1;
904   }
905
906 #if HAVE_YAJL_V2
907   status = yajl_complete_parse(db->yajl);
908 #else
909   status = yajl_parse_complete(db->yajl);
910 #endif
911   if (status != yajl_status_ok) {
912     unsigned char *errmsg;
913
914     errmsg = yajl_get_error(db->yajl, /* verbose = */ 0,
915                             /* jsonText = */ NULL, /* jsonTextLen = */ 0);
916     ERROR("curl_json plugin: yajl_parse_complete failed: %s", (char *)errmsg);
917     yajl_free_error(db->yajl, errmsg);
918     yajl_free(db->yajl);
919     db->yajl = yprev;
920     return -1;
921   }
922
923   yajl_free(db->yajl);
924   db->yajl = yprev;
925   return 0;
926 } /* }}} int cj_perform */
927
928 static int cj_read(user_data_t *ud) /* {{{ */
929 {
930   cj_t *db;
931
932   if ((ud == NULL) || (ud->data == NULL)) {
933     ERROR("curl_json plugin: cj_read: Invalid user data.");
934     return -1;
935   }
936
937   db = (cj_t *)ud->data;
938
939   db->depth = 0;
940   memset(&db->state, 0, sizeof(db->state));
941   db->state[db->depth].tree = db->tree;
942
943   return cj_perform(db);
944 } /* }}} int cj_read */
945
946 static int cj_init(void) /* {{{ */
947 {
948   /* Call this while collectd is still single-threaded to avoid
949    * initialization issues in libgcrypt. */
950   curl_global_init(CURL_GLOBAL_SSL);
951   return 0;
952 } /* }}} int cj_init */
953
954 void module_register(void) {
955   plugin_register_complex_config("curl_json", cj_config);
956   plugin_register_init("curl_json", cj_init);
957 } /* void module_register */