ensure all curl-based plugins follow HTTP redirects
[collectd.git] / src / write_http.c
1 /**
2  * collectd - src/write_http.c
3  * Copyright (C) 2009       Paul Sadauskas
4  * Copyright (C) 2009       Doug MacEachern
5  * Copyright (C) 2007-2014  Florian octo Forster
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; only version 2 of the License is applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Florian octo Forster <octo at collectd.org>
22  *   Doug MacEachern <dougm@hyperic.com>
23  *   Paul Sadauskas <psadauskas@gmail.com>
24  **/
25
26 #include "collectd.h"
27 #include "plugin.h"
28 #include "common.h"
29 #include "utils_cache.h"
30 #include "utils_format_json.h"
31
32 #if HAVE_PTHREAD_H
33 # include <pthread.h>
34 #endif
35
36 #include <curl/curl.h>
37
38 #ifndef WRITE_HTTP_DEFAULT_BUFFER_SIZE
39 # define WRITE_HTTP_DEFAULT_BUFFER_SIZE 4096
40 #endif
41
42 /*
43  * Private variables
44  */
45 struct wh_callback_s
46 {
47         char *location;
48
49         char *user;
50         char *pass;
51         char *credentials;
52         _Bool verify_peer;
53         _Bool verify_host;
54         char *cacert;
55         char *capath;
56         char *clientkey;
57         char *clientcert;
58         char *clientkeypass;
59         long sslversion;
60         _Bool store_rates;
61
62 #define WH_FORMAT_COMMAND 0
63 #define WH_FORMAT_JSON    1
64         int format;
65
66         CURL *curl;
67         char curl_errbuf[CURL_ERROR_SIZE];
68
69         char  *send_buffer;
70         size_t send_buffer_size;
71         size_t send_buffer_free;
72         size_t send_buffer_fill;
73         cdtime_t send_buffer_init_time;
74
75         pthread_mutex_t send_lock;
76 };
77 typedef struct wh_callback_s wh_callback_t;
78
79 static void wh_reset_buffer (wh_callback_t *cb)  /* {{{ */
80 {
81         memset (cb->send_buffer, 0, cb->send_buffer_size);
82         cb->send_buffer_free = cb->send_buffer_size;
83         cb->send_buffer_fill = 0;
84         cb->send_buffer_init_time = cdtime ();
85
86         if (cb->format == WH_FORMAT_JSON)
87         {
88                 format_json_initialize (cb->send_buffer,
89                                 &cb->send_buffer_fill,
90                                 &cb->send_buffer_free);
91         }
92 } /* }}} wh_reset_buffer */
93
94 static int wh_send_buffer (wh_callback_t *cb) /* {{{ */
95 {
96         int status = 0;
97
98         curl_easy_setopt (cb->curl, CURLOPT_POSTFIELDS, cb->send_buffer);
99         status = curl_easy_perform (cb->curl);
100         if (status != CURLE_OK)
101         {
102                 ERROR ("write_http plugin: curl_easy_perform failed with "
103                                 "status %i: %s",
104                                 status, cb->curl_errbuf);
105         }
106         return (status);
107 } /* }}} wh_send_buffer */
108
109 static int wh_callback_init (wh_callback_t *cb) /* {{{ */
110 {
111         struct curl_slist *headers;
112
113         if (cb->curl != NULL)
114                 return (0);
115
116         cb->curl = curl_easy_init ();
117         if (cb->curl == NULL)
118         {
119                 ERROR ("curl plugin: curl_easy_init failed.");
120                 return (-1);
121         }
122
123         curl_easy_setopt (cb->curl, CURLOPT_NOSIGNAL, 1L);
124         curl_easy_setopt (cb->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
125
126         headers = NULL;
127         headers = curl_slist_append (headers, "Accept:  */*");
128         if (cb->format == WH_FORMAT_JSON)
129                 headers = curl_slist_append (headers, "Content-Type: application/json");
130         else
131                 headers = curl_slist_append (headers, "Content-Type: text/plain");
132         headers = curl_slist_append (headers, "Expect:");
133         curl_easy_setopt (cb->curl, CURLOPT_HTTPHEADER, headers);
134
135         curl_easy_setopt (cb->curl, CURLOPT_ERRORBUFFER, cb->curl_errbuf);
136         curl_easy_setopt (cb->curl, CURLOPT_URL, cb->location);
137         curl_easy_setopt (cb->curl, CURLOPT_FOLLOWLOCATION, 1L);
138         curl_easy_setopt (cb->curl, CURLOPT_MAXREDIRS, 50L);
139
140         if (cb->user != NULL)
141         {
142                 size_t credentials_size;
143
144                 credentials_size = strlen (cb->user) + 2;
145                 if (cb->pass != NULL)
146                         credentials_size += strlen (cb->pass);
147
148                 cb->credentials = (char *) malloc (credentials_size);
149                 if (cb->credentials == NULL)
150                 {
151                         ERROR ("curl plugin: malloc failed.");
152                         return (-1);
153                 }
154
155                 ssnprintf (cb->credentials, credentials_size, "%s:%s",
156                                 cb->user, (cb->pass == NULL) ? "" : cb->pass);
157                 curl_easy_setopt (cb->curl, CURLOPT_USERPWD, cb->credentials);
158                 curl_easy_setopt (cb->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
159         }
160
161         curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYPEER, (long) cb->verify_peer);
162         curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYHOST,
163                         cb->verify_host ? 2L : 0L);
164         curl_easy_setopt (cb->curl, CURLOPT_SSLVERSION, cb->sslversion);
165         if (cb->cacert != NULL)
166                 curl_easy_setopt (cb->curl, CURLOPT_CAINFO, cb->cacert);
167         if (cb->capath != NULL)
168                 curl_easy_setopt (cb->curl, CURLOPT_CAPATH, cb->capath);
169
170         if (cb->clientkey != NULL && cb->clientcert != NULL)
171         {
172             curl_easy_setopt (cb->curl, CURLOPT_SSLKEY, cb->clientkey);
173             curl_easy_setopt (cb->curl, CURLOPT_SSLCERT, cb->clientcert);
174
175             if (cb->clientkeypass != NULL)
176                 curl_easy_setopt (cb->curl, CURLOPT_SSLKEYPASSWD, cb->clientkeypass);
177         }
178
179         wh_reset_buffer (cb);
180
181         return (0);
182 } /* }}} int wh_callback_init */
183
184 static int wh_flush_nolock (cdtime_t timeout, wh_callback_t *cb) /* {{{ */
185 {
186         int status;
187
188         DEBUG ("write_http plugin: wh_flush_nolock: timeout = %.3f; "
189                         "send_buffer_fill = %zu;",
190                         CDTIME_T_TO_DOUBLE (timeout),
191                         cb->send_buffer_fill);
192
193         /* timeout == 0  => flush unconditionally */
194         if (timeout > 0)
195         {
196                 cdtime_t now;
197
198                 now = cdtime ();
199                 if ((cb->send_buffer_init_time + timeout) > now)
200                         return (0);
201         }
202
203         if (cb->format == WH_FORMAT_COMMAND)
204         {
205                 if (cb->send_buffer_fill <= 0)
206                 {
207                         cb->send_buffer_init_time = cdtime ();
208                         return (0);
209                 }
210
211                 status = wh_send_buffer (cb);
212                 wh_reset_buffer (cb);
213         }
214         else if (cb->format == WH_FORMAT_JSON)
215         {
216                 if (cb->send_buffer_fill <= 2)
217                 {
218                         cb->send_buffer_init_time = cdtime ();
219                         return (0);
220                 }
221
222                 status = format_json_finalize (cb->send_buffer,
223                                 &cb->send_buffer_fill,
224                                 &cb->send_buffer_free);
225                 if (status != 0)
226                 {
227                         ERROR ("write_http: wh_flush_nolock: "
228                                         "format_json_finalize failed.");
229                         wh_reset_buffer (cb);
230                         return (status);
231                 }
232
233                 status = wh_send_buffer (cb);
234                 wh_reset_buffer (cb);
235         }
236         else
237         {
238                 ERROR ("write_http: wh_flush_nolock: "
239                                 "Unknown format: %i",
240                                 cb->format);
241                 return (-1);
242         }
243
244         return (status);
245 } /* }}} wh_flush_nolock */
246
247 static int wh_flush (cdtime_t timeout, /* {{{ */
248                 const char *identifier __attribute__((unused)),
249                 user_data_t *user_data)
250 {
251         wh_callback_t *cb;
252         int status;
253
254         if (user_data == NULL)
255                 return (-EINVAL);
256
257         cb = user_data->data;
258
259         pthread_mutex_lock (&cb->send_lock);
260
261         if (cb->curl == NULL)
262         {
263                 status = wh_callback_init (cb);
264                 if (status != 0)
265                 {
266                         ERROR ("write_http plugin: wh_callback_init failed.");
267                         pthread_mutex_unlock (&cb->send_lock);
268                         return (-1);
269                 }
270         }
271
272         status = wh_flush_nolock (timeout, cb);
273         pthread_mutex_unlock (&cb->send_lock);
274
275         return (status);
276 } /* }}} int wh_flush */
277
278 static void wh_callback_free (void *data) /* {{{ */
279 {
280         wh_callback_t *cb;
281
282         if (data == NULL)
283                 return;
284
285         cb = data;
286
287         wh_flush_nolock (/* timeout = */ 0, cb);
288
289         if (cb->curl != NULL)
290         {
291                 curl_easy_cleanup (cb->curl);
292                 cb->curl = NULL;
293         }
294         sfree (cb->location);
295         sfree (cb->user);
296         sfree (cb->pass);
297         sfree (cb->credentials);
298         sfree (cb->cacert);
299         sfree (cb->capath);
300         sfree (cb->clientkey);
301         sfree (cb->clientcert);
302         sfree (cb->clientkeypass);
303         sfree (cb->send_buffer);
304
305         sfree (cb);
306 } /* }}} void wh_callback_free */
307
308 static int wh_write_command (const data_set_t *ds, const value_list_t *vl, /* {{{ */
309                 wh_callback_t *cb)
310 {
311         char key[10*DATA_MAX_NAME_LEN];
312         char values[512];
313         char command[1024];
314         size_t command_len;
315
316         int status;
317
318         if (0 != strcmp (ds->type, vl->type)) {
319                 ERROR ("write_http plugin: DS type does not match "
320                                 "value list type");
321                 return -1;
322         }
323
324         /* Copy the identifier to `key' and escape it. */
325         status = FORMAT_VL (key, sizeof (key), vl);
326         if (status != 0) {
327                 ERROR ("write_http plugin: error with format_name");
328                 return (status);
329         }
330         escape_string (key, sizeof (key));
331
332         /* Convert the values to an ASCII representation and put that into
333          * `values'. */
334         status = format_values (values, sizeof (values), ds, vl, cb->store_rates);
335         if (status != 0) {
336                 ERROR ("write_http plugin: error with "
337                                 "wh_value_list_to_string");
338                 return (status);
339         }
340
341         command_len = (size_t) ssnprintf (command, sizeof (command),
342                         "PUTVAL %s interval=%.3f %s\r\n",
343                         key,
344                         CDTIME_T_TO_DOUBLE (vl->interval),
345                         values);
346         if (command_len >= sizeof (command)) {
347                 ERROR ("write_http plugin: Command buffer too small: "
348                                 "Need %zu bytes.", command_len + 1);
349                 return (-1);
350         }
351
352         pthread_mutex_lock (&cb->send_lock);
353
354         if (cb->curl == NULL)
355         {
356                 status = wh_callback_init (cb);
357                 if (status != 0)
358                 {
359                         ERROR ("write_http plugin: wh_callback_init failed.");
360                         pthread_mutex_unlock (&cb->send_lock);
361                         return (-1);
362                 }
363         }
364
365         if (command_len >= cb->send_buffer_free)
366         {
367                 status = wh_flush_nolock (/* timeout = */ 0, cb);
368                 if (status != 0)
369                 {
370                         pthread_mutex_unlock (&cb->send_lock);
371                         return (status);
372                 }
373         }
374         assert (command_len < cb->send_buffer_free);
375
376         /* `command_len + 1' because `command_len' does not include the
377          * trailing null byte. Neither does `send_buffer_fill'. */
378         memcpy (cb->send_buffer + cb->send_buffer_fill,
379                         command, command_len + 1);
380         cb->send_buffer_fill += command_len;
381         cb->send_buffer_free -= command_len;
382
383         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%) \"%s\"",
384                         cb->location,
385                         cb->send_buffer_fill, cb->send_buffer_size,
386                         100.0 * ((double) cb->send_buffer_fill) / ((double) cb->send_buffer_size),
387                         command);
388
389         /* Check if we have enough space for this command. */
390         pthread_mutex_unlock (&cb->send_lock);
391
392         return (0);
393 } /* }}} int wh_write_command */
394
395 static int wh_write_json (const data_set_t *ds, const value_list_t *vl, /* {{{ */
396                 wh_callback_t *cb)
397 {
398         int status;
399
400         pthread_mutex_lock (&cb->send_lock);
401
402         if (cb->curl == NULL)
403         {
404                 status = wh_callback_init (cb);
405                 if (status != 0)
406                 {
407                         ERROR ("write_http plugin: wh_callback_init failed.");
408                         pthread_mutex_unlock (&cb->send_lock);
409                         return (-1);
410                 }
411         }
412
413         status = format_json_value_list (cb->send_buffer,
414                         &cb->send_buffer_fill,
415                         &cb->send_buffer_free,
416                         ds, vl, cb->store_rates);
417         if (status == (-ENOMEM))
418         {
419                 status = wh_flush_nolock (/* timeout = */ 0, cb);
420                 if (status != 0)
421                 {
422                         wh_reset_buffer (cb);
423                         pthread_mutex_unlock (&cb->send_lock);
424                         return (status);
425                 }
426
427                 status = format_json_value_list (cb->send_buffer,
428                                 &cb->send_buffer_fill,
429                                 &cb->send_buffer_free,
430                                 ds, vl, cb->store_rates);
431         }
432         if (status != 0)
433         {
434                 pthread_mutex_unlock (&cb->send_lock);
435                 return (status);
436         }
437
438         DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%)",
439                         cb->location,
440                         cb->send_buffer_fill, cb->send_buffer_size,
441                         100.0 * ((double) cb->send_buffer_fill) / ((double) cb->send_buffer_size));
442
443         /* Check if we have enough space for this command. */
444         pthread_mutex_unlock (&cb->send_lock);
445
446         return (0);
447 } /* }}} int wh_write_json */
448
449 static int wh_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
450                 user_data_t *user_data)
451 {
452         wh_callback_t *cb;
453         int status;
454
455         if (user_data == NULL)
456                 return (-EINVAL);
457
458         cb = user_data->data;
459
460         if (cb->format == WH_FORMAT_JSON)
461                 status = wh_write_json (ds, vl, cb);
462         else
463                 status = wh_write_command (ds, vl, cb);
464
465         return (status);
466 } /* }}} int wh_write */
467
468 static int config_set_format (wh_callback_t *cb, /* {{{ */
469                 oconfig_item_t *ci)
470 {
471         char *string;
472
473         if ((ci->values_num != 1)
474                         || (ci->values[0].type != OCONFIG_TYPE_STRING))
475         {
476                 WARNING ("write_http plugin: The `%s' config option "
477                                 "needs exactly one string argument.", ci->key);
478                 return (-1);
479         }
480
481         string = ci->values[0].value.string;
482         if (strcasecmp ("Command", string) == 0)
483                 cb->format = WH_FORMAT_COMMAND;
484         else if (strcasecmp ("JSON", string) == 0)
485                 cb->format = WH_FORMAT_JSON;
486         else
487         {
488                 ERROR ("write_http plugin: Invalid format string: %s",
489                                 string);
490                 return (-1);
491         }
492
493         return (0);
494 } /* }}} int config_set_format */
495
496 static int wh_config_url (oconfig_item_t *ci) /* {{{ */
497 {
498         wh_callback_t *cb;
499         int buffer_size = 0;
500         user_data_t user_data;
501         int i;
502
503         cb = malloc (sizeof (*cb));
504         if (cb == NULL)
505         {
506                 ERROR ("write_http plugin: malloc failed.");
507                 return (-1);
508         }
509         memset (cb, 0, sizeof (*cb));
510         cb->verify_peer = 1;
511         cb->verify_host = 1;
512         cb->format = WH_FORMAT_COMMAND;
513         cb->sslversion = CURL_SSLVERSION_DEFAULT;
514
515         pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
516
517         cf_util_get_string (ci, &cb->location);
518         if (cb->location == NULL)
519                 return (-1);
520
521         for (i = 0; i < ci->children_num; i++)
522         {
523                 oconfig_item_t *child = ci->children + i;
524
525                 if (strcasecmp ("User", child->key) == 0)
526                         cf_util_get_string (child, &cb->user);
527                 else if (strcasecmp ("Password", child->key) == 0)
528                         cf_util_get_string (child, &cb->pass);
529                 else if (strcasecmp ("VerifyPeer", child->key) == 0)
530                         cf_util_get_boolean (child, &cb->verify_peer);
531                 else if (strcasecmp ("VerifyHost", child->key) == 0)
532                         cf_util_get_boolean (child, &cb->verify_host);
533                 else if (strcasecmp ("CACert", child->key) == 0)
534                         cf_util_get_string (child, &cb->cacert);
535                 else if (strcasecmp ("CAPath", child->key) == 0)
536                         cf_util_get_string (child, &cb->capath);
537                 else if (strcasecmp ("ClientKey", child->key) == 0)
538                         cf_util_get_string (child, &cb->clientkey);
539                 else if (strcasecmp ("ClientCert", child->key) == 0)
540                         cf_util_get_string (child, &cb->clientcert);
541                 else if (strcasecmp ("ClientKeyPass", child->key) == 0)
542                         cf_util_get_string (child, &cb->clientkeypass);
543                 else if (strcasecmp ("SSLVersion", child->key) == 0)
544                 {
545                         char *value = NULL;
546
547                         cf_util_get_string (child, &value);
548
549                         if (value == NULL || strcasecmp ("default", value) == 0)
550                                 cb->sslversion = CURL_SSLVERSION_DEFAULT;
551                         else if (strcasecmp ("SSLv2", value) == 0)
552                                 cb->sslversion = CURL_SSLVERSION_SSLv2;
553                         else if (strcasecmp ("SSLv3", value) == 0)
554                                 cb->sslversion = CURL_SSLVERSION_SSLv3;
555                         else if (strcasecmp ("TLSv1", value) == 0)
556                                 cb->sslversion = CURL_SSLVERSION_TLSv1;
557 #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 34)
558                         else if (strcasecmp ("TLSv1_0", value) == 0)
559                                 cb->sslversion = CURL_SSLVERSION_TLSv1_0;
560                         else if (strcasecmp ("TLSv1_1", value) == 0)
561                                 cb->sslversion = CURL_SSLVERSION_TLSv1_1;
562                         else if (strcasecmp ("TLSv1_2", value) == 0)
563                                 cb->sslversion = CURL_SSLVERSION_TLSv1_2;
564 #endif
565                         else
566                                 ERROR ("write_http plugin: Invalid SSLVersion "
567                                                 "option: %s.", value);
568
569                         sfree(value);
570                 }
571                 else if (strcasecmp ("Format", child->key) == 0)
572                         config_set_format (cb, child);
573                 else if (strcasecmp ("StoreRates", child->key) == 0)
574                         cf_util_get_boolean (child, &cb->store_rates);
575                 else if (strcasecmp ("BufferSize", child->key) == 0)
576                         cf_util_get_int (child, &buffer_size);
577                 else
578                 {
579                         ERROR ("write_http plugin: Invalid configuration "
580                                         "option: %s.", child->key);
581                 }
582         }
583
584         /* Determine send_buffer_size. */
585         cb->send_buffer_size = WRITE_HTTP_DEFAULT_BUFFER_SIZE;
586         if (buffer_size >= 1024)
587                 cb->send_buffer_size = (size_t) buffer_size;
588         else if (buffer_size != 0)
589                 ERROR ("write_http plugin: Ignoring invalid BufferSize setting (%d).",
590                                 buffer_size);
591
592         /* Allocate the buffer. */
593         cb->send_buffer = malloc (cb->send_buffer_size);
594         if (cb->send_buffer == NULL)
595         {
596                 ERROR ("write_http plugin: malloc(%zu) failed.", cb->send_buffer_size);
597                 wh_callback_free (cb);
598                 return (-1);
599         }
600         /* Nulls the buffer and sets ..._free and ..._fill. */
601         wh_reset_buffer (cb);
602
603         DEBUG ("write_http: Registering write callback with URL %s",
604                         cb->location);
605
606         memset (&user_data, 0, sizeof (user_data));
607         user_data.data = cb;
608         user_data.free_func = NULL;
609         plugin_register_flush ("write_http", wh_flush, &user_data);
610
611         user_data.free_func = wh_callback_free;
612         plugin_register_write ("write_http", wh_write, &user_data);
613
614         return (0);
615 } /* }}} int wh_config_url */
616
617 static int wh_config (oconfig_item_t *ci) /* {{{ */
618 {
619         int i;
620
621         for (i = 0; i < ci->children_num; i++)
622         {
623                 oconfig_item_t *child = ci->children + i;
624
625                 if (strcasecmp ("URL", child->key) == 0)
626                         wh_config_url (child);
627                 else
628                 {
629                         ERROR ("write_http plugin: Invalid configuration "
630                                         "option: %s.", child->key);
631                 }
632         }
633
634         return (0);
635 } /* }}} int wh_config */
636
637 static int wh_init (void) /* {{{ */
638 {
639         /* Call this while collectd is still single-threaded to avoid
640          * initialization issues in libgcrypt. */
641         curl_global_init (CURL_GLOBAL_SSL);
642         return (0);
643 } /* }}} int wh_init */
644
645 void module_register (void) /* {{{ */
646 {
647         plugin_register_complex_config ("write_http", wh_config);
648         plugin_register_init ("write_http", wh_init);
649 } /* }}} void module_register */
650
651 /* vim: set fdm=marker sw=8 ts=8 tw=78 et : */