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