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