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