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