openldap: copyright update + minor cleanup
[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   if (status != yajl_status_ok)
135   {
136     unsigned char *msg =
137       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   }
143
144   return (len);
145 } /* }}} size_t cj_curl_callback */
146
147 static int cj_get_type (cj_key_t *key)
148 {
149   const data_set_t *ds;
150
151   ds = plugin_get_ds (key->type);
152   if (ds == NULL)
153   {
154     static char type[DATA_MAX_NAME_LEN] = "!!!invalid!!!";
155
156     assert (key->type != NULL);
157     if (strcmp (type, key->type) != 0)
158     {
159       ERROR ("curl_json plugin: Unable to look up DS type \"%s\".",
160           key->type);
161       sstrncpy (type, key->type, sizeof (type));
162     }
163
164     return -1;
165   }
166   else if (ds->ds_num > 1)
167   {
168     static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
169
170     c_complain_once (LOG_WARNING, &complaint,
171         "curl_json plugin: The type \"%s\" has more than one data source. "
172         "This is currently not supported. I will return the type of the "
173         "first data source, but this will likely lead to problems later on.",
174         key->type);
175   }
176
177   return ds->ds[0].type;
178 }
179
180 static int cj_cb_map_key (void *ctx, const unsigned char *val,
181     yajl_len_t len);
182
183 static void cj_cb_inc_array_index (void *ctx, _Bool update_key)
184 {
185   cj_t *db = (cj_t *)ctx;
186
187   if (!db->state[db->depth].in_array)
188     return;
189
190   db->state[db->depth].index++;
191
192   if (update_key)
193   {
194     char name[DATA_MAX_NAME_LEN];
195
196     ssnprintf (name, sizeof (name), "%d", db->state[db->depth].index - 1);
197
198     cj_cb_map_key (ctx, (unsigned char *)name, (yajl_len_t) strlen (name));
199   }
200 }
201
202 /* yajl callbacks */
203 #define CJ_CB_ABORT    0
204 #define CJ_CB_CONTINUE 1
205
206 static int cj_cb_boolean (void * ctx, int boolVal)
207 {
208   cj_cb_inc_array_index (ctx, /* update_key = */ 0);
209   return (CJ_CB_CONTINUE);
210 }
211
212 static int cj_cb_null (void * ctx)
213 {
214   cj_cb_inc_array_index (ctx, /* update_key = */ 0);
215   return (CJ_CB_CONTINUE);
216 }
217
218 static int cj_cb_number (void *ctx,
219     const char *number, yajl_len_t number_len)
220 {
221   char buffer[number_len + 1];
222
223   cj_t *db = (cj_t *)ctx;
224   cj_key_t *key = db->state[db->depth].key;
225   value_t vt;
226   int type;
227   int status;
228
229   /* Create a null-terminated version of the string. */
230   memcpy (buffer, number, number_len);
231   buffer[sizeof (buffer) - 1] = 0;
232
233   if ((key == NULL) || !CJ_IS_KEY (key)) {
234     if (key != NULL && !db->state[db->depth].in_array/*can be inhomogeneous*/)
235       NOTICE ("curl_json plugin: Found \"%s\", but the configuration expects"
236               " a map.", buffer);
237     cj_cb_inc_array_index (ctx, /* update_key = */ 1);
238     key = db->state[db->depth].key;
239     if (key == NULL) {
240       return (CJ_CB_CONTINUE);
241     }
242   }
243   else
244   {
245     cj_cb_inc_array_index (ctx, /* update_key = */ 1);
246   }
247
248   type = cj_get_type (key);
249   status = parse_value (buffer, &vt, type);
250   if (status != 0)
251   {
252     NOTICE ("curl_json plugin: Unable to parse number: \"%s\"", buffer);
253     return (CJ_CB_CONTINUE);
254   }
255
256   cj_submit (db, key, &vt);
257   return (CJ_CB_CONTINUE);
258 } /* int cj_cb_number */
259
260 /* Queries the key-tree of the parent context for "in_name" and, if found,
261  * updates the "key" field of the current context. Otherwise, "key" is set to
262  * NULL. */
263 static int cj_cb_map_key (void *ctx,
264     unsigned char const *in_name, yajl_len_t in_name_len)
265 {
266   cj_t *db = (cj_t *)ctx;
267   c_avl_tree_t *tree;
268
269   tree = db->state[db->depth-1].tree;
270
271   if (tree != NULL)
272   {
273     cj_key_t *value = NULL;
274     char *name;
275     size_t name_len;
276
277     /* Create a null-terminated version of the name. */
278     name = db->state[db->depth].name;
279     name_len = COUCH_MIN ((size_t) in_name_len,
280         sizeof (db->state[db->depth].name) - 1);
281     memcpy (name, in_name, name_len);
282     name[name_len] = 0;
283
284     if (c_avl_get (tree, name, (void *) &value) == 0) {
285       if (CJ_IS_KEY((cj_key_t*)value)) {
286         db->state[db->depth].key = value;
287       }
288       else {
289         db->state[db->depth].tree = (c_avl_tree_t*) value;
290       }
291     }
292     else if (c_avl_get (tree, CJ_ANY, (void *) &value) == 0)
293       if (CJ_IS_KEY((cj_key_t*)value)) {
294         db->state[db->depth].key = value;
295       }
296       else {
297         db->state[db->depth].tree = (c_avl_tree_t*) value;
298       }
299     else
300       db->state[db->depth].key = NULL;
301   }
302
303   return (CJ_CB_CONTINUE);
304 }
305
306 static int cj_cb_string (void *ctx, const unsigned char *val,
307     yajl_len_t len)
308 {
309   /* Handle the string as if it was a number. */
310   return (cj_cb_number (ctx, (const char *) val, len));
311 } /* int cj_cb_string */
312
313 static int cj_cb_start (void *ctx)
314 {
315   cj_t *db = (cj_t *)ctx;
316   if (++db->depth >= YAJL_MAX_DEPTH)
317   {
318     ERROR ("curl_json plugin: %s depth exceeds max, aborting.",
319            db->url ? db->url : db->sock);
320     return (CJ_CB_ABORT);
321   }
322   return (CJ_CB_CONTINUE);
323 }
324
325 static int cj_cb_end (void *ctx)
326 {
327   cj_t *db = (cj_t *)ctx;
328   db->state[db->depth].tree = NULL;
329   --db->depth;
330   return (CJ_CB_CONTINUE);
331 }
332
333 static int cj_cb_start_map (void *ctx)
334 {
335   cj_cb_inc_array_index (ctx, /* update_key = */ 1);
336   return cj_cb_start (ctx);
337 }
338
339 static int cj_cb_end_map (void *ctx)
340 {
341   return cj_cb_end (ctx);
342 }
343
344 static int cj_cb_start_array (void * ctx)
345 {
346   cj_t *db = (cj_t *)ctx;
347   cj_cb_inc_array_index (ctx, /* update_key = */ 1);
348   if (db->depth+1 < YAJL_MAX_DEPTH) {
349     db->state[db->depth+1].in_array = 1;
350     db->state[db->depth+1].index = 0;
351   }
352   return cj_cb_start (ctx);
353 }
354
355 static int cj_cb_end_array (void * ctx)
356 {
357   cj_t *db = (cj_t *)ctx;
358   db->state[db->depth].in_array = 0;
359   return cj_cb_end (ctx);
360 }
361
362 static yajl_callbacks ycallbacks = {
363   cj_cb_null, /* null */
364   cj_cb_boolean, /* boolean */
365   NULL, /* integer */
366   NULL, /* double */
367   cj_cb_number,
368   cj_cb_string,
369   cj_cb_start_map,
370   cj_cb_map_key,
371   cj_cb_end_map,
372   cj_cb_start_array,
373   cj_cb_end_array
374 };
375
376 /* end yajl callbacks */
377
378 static void cj_key_free (cj_key_t *key) /* {{{ */
379 {
380   if (key == NULL)
381     return;
382
383   sfree (key->path);
384   sfree (key->type);
385   sfree (key->instance);
386
387   sfree (key);
388 } /* }}} void cj_key_free */
389
390 static void cj_tree_free (c_avl_tree_t *tree) /* {{{ */
391 {
392   char *name;
393   void *value;
394
395   while (c_avl_pick (tree, (void *) &name, (void *) &value) == 0)
396   {
397     cj_key_t *key = (cj_key_t *)value;
398
399     if (CJ_IS_KEY(key))
400       cj_key_free (key);
401     else
402       cj_tree_free ((c_avl_tree_t *)value);
403
404     sfree (name);
405   }
406
407   c_avl_destroy (tree);
408 } /* }}} void cj_tree_free */
409
410 static void cj_free (void *arg) /* {{{ */
411 {
412   cj_t *db;
413
414   DEBUG ("curl_json plugin: cj_free (arg = %p);", arg);
415
416   db = (cj_t *) arg;
417
418   if (db == NULL)
419     return;
420
421   if (db->curl != NULL)
422     curl_easy_cleanup (db->curl);
423   db->curl = NULL;
424
425   if (db->tree != NULL)
426     cj_tree_free (db->tree);
427   db->tree = NULL;
428
429   sfree (db->instance);
430   sfree (db->host);
431
432   sfree (db->sock);
433
434   sfree (db->url);
435   sfree (db->user);
436   sfree (db->pass);
437   sfree (db->credentials);
438   sfree (db->cacert);
439   sfree (db->post_body);
440   curl_slist_free_all (db->headers);
441
442   sfree (db);
443 } /* }}} void cj_free */
444
445 /* Configuration handling functions {{{ */
446
447 static c_avl_tree_t *cj_avl_create(void)
448 {
449   return c_avl_create ((int (*) (const void *, const void *)) strcmp);
450 }
451
452 static int cj_config_append_string (const char *name, struct curl_slist **dest, /* {{{ */
453     oconfig_item_t *ci)
454 {
455   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
456   {
457     WARNING ("curl_json plugin: `%s' needs exactly one string argument.", name);
458     return (-1);
459   }
460
461   *dest = curl_slist_append(*dest, ci->values[0].value.string);
462   if (*dest == NULL)
463     return (-1);
464
465   return (0);
466 } /* }}} int cj_config_append_string */
467
468 static int cj_config_add_key (cj_t *db, /* {{{ */
469                                    oconfig_item_t *ci)
470 {
471   cj_key_t *key;
472   int status;
473   int i;
474
475   if ((ci->values_num != 1)
476       || (ci->values[0].type != OCONFIG_TYPE_STRING))
477   {
478     WARNING ("curl_json plugin: The `Key' block "
479              "needs exactly one string argument.");
480     return (-1);
481   }
482
483   key = (cj_key_t *) malloc (sizeof (*key));
484   if (key == NULL)
485   {
486     ERROR ("curl_json plugin: malloc failed.");
487     return (-1);
488   }
489   memset (key, 0, sizeof (*key));
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   while (status == 0)
529   {
530     if (key->type == NULL)
531     {
532       WARNING ("curl_json plugin: `Type' missing in `Key' block.");
533       status = -1;
534     }
535
536     break;
537   } /* while (status == 0) */
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   if (status == 0)
545   {
546     char *ptr;
547     char *name;
548     char ent[PATH_MAX];
549     c_avl_tree_t *tree;
550
551     if (db->tree == NULL)
552       db->tree = cj_avl_create();
553
554     tree = db->tree;
555     ptr = key->path;
556     if (*ptr == '/')
557       ++ptr;
558
559     name = ptr;
560     while (*ptr)
561     {
562       if (*ptr == '/')
563       {
564         c_avl_tree_t *value;
565         size_t len;
566
567         len = ptr-name;
568         if (len == 0)
569           break;
570         len = COUCH_MIN(len, sizeof (ent)-1);
571         sstrncpy (ent, name, len+1);
572
573         if (c_avl_get (tree, ent, (void *) &value) != 0)
574         {
575           value = cj_avl_create ();
576           c_avl_insert (tree, strdup (ent), value);
577         }
578
579         tree = value;
580         name = ptr+1;
581       }
582       ++ptr;
583     }
584     if (*name)
585       c_avl_insert (tree, strdup(name), key);
586     else
587     {
588       ERROR ("curl_json plugin: invalid key: %s", key->path);
589       status = -1;
590     }
591   }
592
593   return (status);
594 } /* }}} int cj_config_add_key */
595
596 static int cj_init_curl (cj_t *db) /* {{{ */
597 {
598   db->curl = curl_easy_init ();
599   if (db->curl == NULL)
600   {
601     ERROR ("curl_json plugin: curl_easy_init failed.");
602     return (-1);
603   }
604
605   curl_easy_setopt (db->curl, CURLOPT_NOSIGNAL, 1L);
606   curl_easy_setopt (db->curl, CURLOPT_WRITEFUNCTION, cj_curl_callback);
607   curl_easy_setopt (db->curl, CURLOPT_WRITEDATA, db);
608   curl_easy_setopt (db->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
609   curl_easy_setopt (db->curl, CURLOPT_ERRORBUFFER, db->curl_errbuf);
610   curl_easy_setopt (db->curl, CURLOPT_URL, db->url);
611   curl_easy_setopt (db->curl, CURLOPT_FOLLOWLOCATION, 1L);
612   curl_easy_setopt (db->curl, CURLOPT_MAXREDIRS, 50L);
613
614   if (db->user != NULL)
615   {
616 #ifdef HAVE_CURLOPT_USERNAME
617     curl_easy_setopt (db->curl, CURLOPT_USERNAME, db->user);
618     curl_easy_setopt (db->curl, CURLOPT_PASSWORD,
619         (db->pass == NULL) ? "" : db->pass);
620 #else
621     size_t credentials_size;
622
623     credentials_size = strlen (db->user) + 2;
624     if (db->pass != NULL)
625       credentials_size += strlen (db->pass);
626
627     db->credentials = (char *) malloc (credentials_size);
628     if (db->credentials == NULL)
629     {
630       ERROR ("curl_json plugin: malloc failed.");
631       return (-1);
632     }
633
634     ssnprintf (db->credentials, credentials_size, "%s:%s",
635                db->user, (db->pass == NULL) ? "" : db->pass);
636     curl_easy_setopt (db->curl, CURLOPT_USERPWD, db->credentials);
637 #endif
638
639     if (db->digest)
640       curl_easy_setopt (db->curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
641   }
642
643   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYPEER, (long) db->verify_peer);
644   curl_easy_setopt (db->curl, CURLOPT_SSL_VERIFYHOST,
645                     db->verify_host ? 2L : 0L);
646   if (db->cacert != NULL)
647     curl_easy_setopt (db->curl, CURLOPT_CAINFO, db->cacert);
648   if (db->headers != NULL)
649     curl_easy_setopt (db->curl, CURLOPT_HTTPHEADER, db->headers);
650   if (db->post_body != NULL)
651     curl_easy_setopt (db->curl, CURLOPT_POSTFIELDS, db->post_body);
652
653 #ifdef HAVE_CURLOPT_TIMEOUT_MS
654   if (db->timeout >= 0)
655     curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS, (long) db->timeout);
656   else if (db->interval > 0)
657     curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS, (long) CDTIME_T_TO_MS(db->timeout));
658   else
659     curl_easy_setopt (db->curl, CURLOPT_TIMEOUT_MS, (long) CDTIME_T_TO_MS(plugin_get_interval()));
660 #endif
661
662   return (0);
663 } /* }}} int cj_init_curl */
664
665 static int cj_config_add_url (oconfig_item_t *ci) /* {{{ */
666 {
667   cj_t *db;
668   int status = 0;
669   int i;
670
671   if ((ci->values_num != 1)
672       || (ci->values[0].type != OCONFIG_TYPE_STRING))
673   {
674     WARNING ("curl_json plugin: The `URL' block "
675              "needs exactly one string argument.");
676     return (-1);
677   }
678
679   db = (cj_t *) malloc (sizeof (*db));
680   if (db == NULL)
681   {
682     ERROR ("curl_json plugin: malloc failed.");
683     return (-1);
684   }
685   memset (db, 0, sizeof (*db));
686
687   db->timeout = -1;
688
689   if (strcasecmp ("URL", ci->key) == 0)
690     status = cf_util_get_string (ci, &db->url);
691   else if (strcasecmp ("Sock", ci->key) == 0)
692     status = cf_util_get_string (ci, &db->sock);
693   else
694   {
695     ERROR ("curl_json plugin: cj_config: "
696            "Invalid key: %s", ci->key);
697     cj_free (db);
698     return (-1);
699   }
700   if (status != 0)
701   {
702     sfree (db);
703     return (status);
704   }
705
706   /* Fill the `cj_t' structure.. */
707   for (i = 0; i < ci->children_num; i++)
708   {
709     oconfig_item_t *child = ci->children + i;
710
711     if (strcasecmp ("Instance", child->key) == 0)
712       status = cf_util_get_string (child, &db->instance);
713     else if (strcasecmp ("Host", child->key) == 0)
714       status = cf_util_get_string (child, &db->host);
715     else if (db->url && strcasecmp ("User", child->key) == 0)
716       status = cf_util_get_string (child, &db->user);
717     else if (db->url && strcasecmp ("Password", child->key) == 0)
718       status = cf_util_get_string (child, &db->pass);
719     else if (strcasecmp ("Digest", child->key) == 0)
720       status = cf_util_get_boolean (child, &db->digest);
721     else if (db->url && strcasecmp ("VerifyPeer", child->key) == 0)
722       status = cf_util_get_boolean (child, &db->verify_peer);
723     else if (db->url && strcasecmp ("VerifyHost", child->key) == 0)
724       status = cf_util_get_boolean (child, &db->verify_host);
725     else if (db->url && strcasecmp ("CACert", child->key) == 0)
726       status = cf_util_get_string (child, &db->cacert);
727     else if (db->url && strcasecmp ("Header", child->key) == 0)
728       status = cj_config_append_string ("Header", &db->headers, child);
729     else if (db->url && strcasecmp ("Post", child->key) == 0)
730       status = cf_util_get_string (child, &db->post_body);
731     else if (strcasecmp ("Key", child->key) == 0)
732       status = cj_config_add_key (db, child);
733     else if (strcasecmp ("Interval", child->key) == 0)
734       status = cf_util_get_cdtime(child, &db->interval);
735     else if (strcasecmp ("Timeout", child->key) == 0)
736       status = cf_util_get_int (child, &db->timeout);
737     else
738     {
739       WARNING ("curl_json plugin: Option `%s' not allowed here.", child->key);
740       status = -1;
741     }
742
743     if (status != 0)
744       break;
745   }
746
747   if (status == 0)
748   {
749     if (db->tree == NULL)
750     {
751       WARNING ("curl_json plugin: No (valid) `Key' block within `%s' \"`%s'\".",
752                db->url ? "URL" : "Sock", db->url ? db->url : db->sock);
753       status = -1;
754     }
755     if (status == 0 && db->url)
756       status = cj_init_curl (db);
757   }
758
759   /* If all went well, register this database for reading */
760   if (status == 0)
761   {
762     user_data_t ud;
763     char *cb_name;
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,
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 : */