summaryrefslogtreecommitdiffstats
path: root/plugins/check_curl.c
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/check_curl.c')
-rw-r--r--plugins/check_curl.c1890
1 files changed, 1890 insertions, 0 deletions
diff --git a/plugins/check_curl.c b/plugins/check_curl.c
new file mode 100644
index 00000000..e26d8d3f
--- /dev/null
+++ b/plugins/check_curl.c
@@ -0,0 +1,1890 @@
1/*****************************************************************************
2*
3* Monitoring check_curl plugin
4*
5* License: GPL
6* Copyright (c) 1999-2017 Monitoring Plugins Development Team
7*
8* Description:
9*
10* This file contains the check_curl plugin
11*
12* This plugin tests the HTTP service on the specified host. It can test
13* normal (http) and secure (https) servers, follow redirects, search for
14* strings and regular expressions, check connection times, and report on
15* certificate expiration times.
16*
17* This plugin uses functions from the curl library, see
18* http://curl.haxx.se
19*
20* This program is free software: you can redistribute it and/or modify
21* it under the terms of the GNU General Public License as published by
22* the Free Software Foundation, either version 3 of the License, or
23* (at your option) any later version.
24*
25* This program is distributed in the hope that it will be useful,
26* but WITHOUT ANY WARRANTY; without even the implied warranty of
27* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28* GNU General Public License for more details.
29*
30* You should have received a copy of the GNU General Public License
31* along with this program. If not, see <http://www.gnu.org/licenses/>.
32*
33*
34*****************************************************************************/
35const char *progname = "check_curl";
36
37const char *copyright = "2006-2017";
38const char *email = "devel@monitoring-plugins.org";
39
40#include <ctype.h>
41
42#include "common.h"
43#include "utils.h"
44
45#ifndef LIBCURL_PROTOCOL_HTTP
46#error libcurl compiled without HTTP support, compiling check_curl plugin does not makes a lot of sense
47#endif
48
49#include "curl/curl.h"
50#include "curl/easy.h"
51
52#include "picohttpparser.h"
53
54#define MAKE_LIBCURL_VERSION(major, minor, patch) ((major)*0x10000 + (minor)*0x100 + (patch))
55
56#define DEFAULT_BUFFER_SIZE 2048
57#define DEFAULT_SERVER_URL "/"
58#define HTTP_EXPECT "HTTP/1."
59enum {
60 HTTP_PORT = 80,
61 HTTPS_PORT = 443,
62 MAX_PORT = 65535
63};
64
65/* for buffers for header and body */
66typedef struct {
67 char *buf;
68 size_t buflen;
69 size_t bufsize;
70} curlhelp_write_curlbuf;
71
72/* for buffering the data sent in PUT */
73typedef struct {
74 char *buf;
75 size_t buflen;
76 off_t pos;
77} curlhelp_read_curlbuf;
78
79/* for parsing the HTTP status line */
80typedef struct {
81 int http_major; /* major version of the protocol, always 1 (HTTP/0.9
82 * never reached the big internet most likely) */
83 int http_minor; /* minor version of the protocol, usually 0 or 1 */
84 int http_code; /* HTTP return code as in RFC 2145 */
85 int http_subcode; /* Microsoft IIS extension, HTTP subcodes, see
86 * http://support.microsoft.com/kb/318380/en-us */
87 const char *msg; /* the human readable message */
88 char *first_line; /* a copy of the first line */
89} curlhelp_statusline;
90
91/* to know the underlying SSL library used by libcurl */
92typedef enum curlhelp_ssl_library {
93 CURLHELP_SSL_LIBRARY_UNKNOWN,
94 CURLHELP_SSL_LIBRARY_OPENSSL,
95 CURLHELP_SSL_LIBRARY_LIBRESSL,
96 CURLHELP_SSL_LIBRARY_GNUTLS,
97 CURLHELP_SSL_LIBRARY_NSS
98} curlhelp_ssl_library;
99
100enum {
101 REGS = 2,
102 MAX_RE_SIZE = 256
103};
104#include "regex.h"
105regex_t preg;
106regmatch_t pmatch[REGS];
107char regexp[MAX_RE_SIZE];
108int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE;
109int errcode;
110int invert_regex = 0;
111
112char *server_address;
113char *host_name;
114char *server_url = DEFAULT_SERVER_URL;
115unsigned short server_port = HTTP_PORT;
116int virtual_port = 0;
117int host_name_length;
118char output_header_search[30] = "";
119char output_string_search[30] = "";
120char *warning_thresholds = NULL;
121char *critical_thresholds = NULL;
122int days_till_exp_warn, days_till_exp_crit;
123thresholds *thlds;
124char user_agent[DEFAULT_BUFFER_SIZE];
125int verbose = 0;
126int show_extended_perfdata = FALSE;
127int min_page_len = 0;
128int max_page_len = 0;
129char *http_method = NULL;
130char *http_post_data = NULL;
131char *http_content_type = NULL;
132CURL *curl;
133struct curl_slist *header_list = NULL;
134curlhelp_write_curlbuf body_buf;
135curlhelp_write_curlbuf header_buf;
136curlhelp_statusline status_line;
137curlhelp_read_curlbuf put_buf;
138char http_header[DEFAULT_BUFFER_SIZE];
139long code;
140long socket_timeout = DEFAULT_SOCKET_TIMEOUT;
141double total_time;
142double time_connect;
143double time_appconnect;
144double time_headers;
145double time_firstbyte;
146char errbuf[CURL_ERROR_SIZE+1];
147CURLcode res;
148char url[DEFAULT_BUFFER_SIZE];
149char msg[DEFAULT_BUFFER_SIZE];
150char perfstring[DEFAULT_BUFFER_SIZE];
151char header_expect[MAX_INPUT_BUFFER] = "";
152char string_expect[MAX_INPUT_BUFFER] = "";
153char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT;
154int server_expect_yn = 0;
155char user_auth[MAX_INPUT_BUFFER] = "";
156int display_html = FALSE;
157int onredirect = STATE_OK;
158int use_ssl = FALSE;
159int use_sni = TRUE;
160int check_cert = FALSE;
161typedef union {
162 struct curl_slist* to_info;
163 struct curl_certinfo* to_certinfo;
164} cert_ptr_union;
165cert_ptr_union cert_ptr;
166int ssl_version = CURL_SSLVERSION_DEFAULT;
167char *client_cert = NULL;
168char *client_privkey = NULL;
169char *ca_cert = NULL;
170int is_openssl_callback = FALSE;
171#ifdef HAVE_SSL
172#ifdef USE_OPENSSL
173X509 *cert = NULL;
174#endif /* USE_OPENSSL */
175#endif /* HAVE_SSL */
176int no_body = FALSE;
177int maximum_age = -1;
178int address_family = AF_UNSPEC;
179curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN;
180
181int process_arguments (int, char**);
182void handle_curl_option_return_code (CURLcode res, const char* option);
183int check_http (void);
184void print_help (void);
185void print_usage (void);
186void print_curl_version (void);
187int curlhelp_initwritebuffer (curlhelp_write_curlbuf*);
188int curlhelp_buffer_write_callback (void*, size_t , size_t , void*);
189void curlhelp_freewritebuffer (curlhelp_write_curlbuf*);
190int curlhelp_initreadbuffer (curlhelp_read_curlbuf *, const char *, size_t);
191int curlhelp_buffer_read_callback (void *, size_t , size_t , void *);
192void curlhelp_freereadbuffer (curlhelp_read_curlbuf *);
193curlhelp_ssl_library curlhelp_get_ssl_library (CURL*);
194const char* curlhelp_get_ssl_library_string (curlhelp_ssl_library);
195int net_noopenssl_check_certificate (cert_ptr_union*, int, int);
196
197int curlhelp_parse_statusline (const char*, curlhelp_statusline *);
198void curlhelp_free_statusline (curlhelp_statusline *);
199char *perfd_time_ssl (double microsec);
200char *get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header);
201int check_document_dates (const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]);
202
203void remove_newlines (char *);
204void test_file (char *);
205
206int
207main (int argc, char **argv)
208{
209 int result = STATE_UNKNOWN;
210
211 setlocale (LC_ALL, "");
212 bindtextdomain (PACKAGE, LOCALEDIR);
213 textdomain (PACKAGE);
214
215 /* Parse extra opts if any */
216 argv = np_extra_opts (&argc, argv, progname);
217
218 /* set defaults */
219 snprintf( user_agent, DEFAULT_BUFFER_SIZE, "%s/v%s (monitoring-plugins %s)",
220 progname, NP_VERSION, VERSION);
221
222 /* parse arguments */
223 if (process_arguments (argc, argv) == ERROR)
224 usage4 (_("Could not parse arguments"));
225
226 if (display_html == TRUE)
227 printf ("<A HREF=\"%s://%s:%d%s\" target=\"_blank\">",
228 use_ssl ? "https" : "http", host_name ? host_name : server_address,
229 server_port, server_url);
230
231 result = check_http ();
232 return result;
233}
234
235#ifdef HAVE_SSL
236#ifdef USE_OPENSSL
237
238int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
239{
240 /* TODO: we get all certificates of the chain, so which ones
241 * should we test?
242 * TODO: is the last certificate always the server certificate?
243 */
244 cert = X509_STORE_CTX_get_current_cert(x509_ctx);
245 return 1;
246}
247
248CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm)
249{
250 SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback);
251
252 return CURLE_OK;
253}
254
255#endif /* USE_OPENSSL */
256#endif /* HAVE_SSL */
257
258/* Checks if the server 'reply' is one of the expected 'statuscodes' */
259static int
260expected_statuscode (const char *reply, const char *statuscodes)
261{
262 char *expected, *code;
263 int result = 0;
264
265 if ((expected = strdup (statuscodes)) == NULL)
266 die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n"));
267
268 for (code = strtok (expected, ","); code != NULL; code = strtok (NULL, ","))
269 if (strstr (reply, code) != NULL) {
270 result = 1;
271 break;
272 }
273
274 free (expected);
275 return result;
276}
277
278void
279handle_curl_option_return_code (CURLcode res, const char* option)
280{
281 if (res != CURLE_OK) {
282 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Error while setting cURL option '%s': cURL returned %d - %s"),
283 option, res, curl_easy_strerror(res));
284 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
285 }
286}
287
288int
289check_http (void)
290{
291 int result = STATE_OK;
292 int page_len = 0;
293
294 /* initialize curl */
295 if (curl_global_init (CURL_GLOBAL_DEFAULT) != CURLE_OK)
296 die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n");
297
298 if ((curl = curl_easy_init()) == NULL)
299 die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n");
300
301 if (verbose >= 1)
302 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_VERBOSE, TRUE), "CURLOPT_VERBOSE");
303
304 /* print everything on stdout like check_http would do */
305 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_STDERR, stdout), "CURLOPT_STDERR");
306
307 /* initialize buffer for body of the answer */
308 if (curlhelp_initwritebuffer(&body_buf) < 0)
309 die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n");
310 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_WRITEFUNCTION");
311 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEDATA, (void *)&body_buf), "CURLOPT_WRITEDATA");
312
313 /* initialize buffer for header of the answer */
314 if (curlhelp_initwritebuffer( &header_buf ) < 0)
315 die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for header\n" );
316 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HEADERFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_HEADERFUNCTION");
317 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEHEADER, (void *)&header_buf), "CURLOPT_WRITEHEADER");
318
319 /* set the error buffer */
320 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, errbuf), "CURLOPT_ERRORBUFFER");
321
322 /* set timeouts */
323 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, socket_timeout), "CURLOPT_CONNECTTIMEOUT");
324 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_TIMEOUT, socket_timeout), "CURLOPT_TIMEOUT");
325
326 /* compose URL */
327 snprintf (url, DEFAULT_BUFFER_SIZE, "%s://%s%s", use_ssl ? "https" : "http",
328 host_name, server_url);
329 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, url), "CURLOPT_URL");
330
331 /* set port */
332 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PORT, server_port), "CURLOPT_PORT");
333
334 /* set HTTP method */
335 if (http_method) {
336 if (!strcmp(http_method, "POST"))
337 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POST, 1), "CURLOPT_POST");
338 else if (!strcmp(http_method, "PUT"))
339 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_UPLOAD, 1), "CURLOPT_UPLOAD");
340 else
341 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CUSTOMREQUEST, http_method), "CURLOPT_CUSTOMREQUEST");
342 }
343
344 /* set hostname (virtual hosts) */
345 if(host_name != NULL) {
346 if((virtual_port != HTTP_PORT && !use_ssl) || (virtual_port != HTTPS_PORT && use_ssl)) {
347 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s:%d", host_name, virtual_port);
348 } else {
349 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s", host_name);
350 }
351 header_list = curl_slist_append (header_list, http_header);
352 }
353
354 /* always close connection, be nice to servers */
355 snprintf (http_header, DEFAULT_BUFFER_SIZE, "Connection: close");
356 header_list = curl_slist_append (header_list, http_header);
357
358 /* set HTTP headers */
359 handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPHEADER, header_list ), "CURLOPT_HTTPHEADER");
360
361#ifdef LIBCURL_FEATURE_SSL
362
363 /* set SSL version, warn about unsecure or unsupported versions */
364 if (use_ssl) {
365 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLVERSION, ssl_version), "CURLOPT_SSLVERSION");
366 }
367
368 /* client certificate and key to present to server (SSL) */
369 if (client_cert)
370 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLCERT, client_cert), "CURLOPT_SSLCERT");
371 if (client_privkey)
372 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLKEY, client_privkey), "CURLOPT_SSLKEY");
373 if (ca_cert) {
374 /* per default if we have a CA verify both the peer and the
375 * hostname in the certificate, can be switched off later */
376 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO");
377 handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER");
378 handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST");
379 } else {
380 /* backward-compatible behaviour, be tolerant in checks
381 * TODO: depending on more options have aspects we want
382 * to be less tolerant about ssl verfications
383 */
384 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0), "CURLOPT_SSL_VERIFYPEER");
385 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0), "CURLOPT_SSL_VERIFYHOST");
386 }
387
388 /* detect SSL library used by libcurl */
389 ssl_library = curlhelp_get_ssl_library (curl);
390
391 /* try hard to get a stack of certificates to verify against */
392 if (check_cert)
393#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1)
394 /* inform curl to report back certificates */
395 switch (ssl_library) {
396 case CURLHELP_SSL_LIBRARY_OPENSSL:
397 case CURLHELP_SSL_LIBRARY_LIBRESSL:
398 /* set callback to extract certificate with OpenSSL context function (works with
399 * OpenSSL-style libraries only!) */
400#ifdef USE_OPENSSL
401 /* libcurl and monitoring plugins built with OpenSSL, good */
402 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION");
403 is_openssl_callback = TRUE;
404#else /* USE_OPENSSL */
405#endif /* USE_OPENSSL */
406 /* libcurl is built with OpenSSL, monitoring plugins, so falling
407 * back to manually extracting certificate information */
408 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
409 break;
410
411 case CURLHELP_SSL_LIBRARY_NSS:
412#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
413 /* NSS: support for CERTINFO is implemented since 7.34.0 */
414 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
415#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
416 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n", curlhelp_get_ssl_library_string (ssl_library));
417#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
418 break;
419
420 case CURLHELP_SSL_LIBRARY_GNUTLS:
421#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0)
422 /* GnuTLS: support for CERTINFO is implemented since 7.42.0 */
423 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
424#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */
425 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n", curlhelp_get_ssl_library_string (ssl_library));
426#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */
427 break;
428
429 case CURLHELP_SSL_LIBRARY_UNKNOWN:
430 default:
431 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (unknown SSL library '%s', must implement first)\n", curlhelp_get_ssl_library_string (ssl_library));
432 break;
433 }
434#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */
435 /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */
436 if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL || ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL)
437 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION");
438 else
439 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (no CURLOPT_SSL_CTX_FUNCTION, no OpenSSL library or libcurl too old and has no CURLOPT_CERTINFO)\n");
440#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */
441
442#endif /* LIBCURL_FEATURE_SSL */
443
444 /* set default or user-given user agent identification */
445 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERAGENT, user_agent), "CURLOPT_USERAGENT");
446
447 /* authentication */
448 if (strcmp(user_auth, ""))
449 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERPWD, user_auth), "CURLOPT_USERPWD");
450
451 /* TODO: parameter auth method, bitfield of following methods:
452 * CURLAUTH_BASIC (default)
453 * CURLAUTH_DIGEST
454 * CURLAUTH_DIGEST_IE
455 * CURLAUTH_NEGOTIATE
456 * CURLAUTH_NTLM
457 * CURLAUTH_NTLM_WB
458 *
459 * convenience tokens for typical sets of methods:
460 * CURLAUTH_ANYSAFE: most secure, without BASIC
461 * or CURLAUTH_ANY: most secure, even BASIC if necessary
462 *
463 * handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST ), "CURLOPT_HTTPAUTH");
464 */
465
466 /* handle redirections */
467 if (onredirect == STATE_DEPENDENT) {
468 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1), "CURLOPT_FOLLOWLOCATION");
469 /* TODO: handle the following aspects of redirection
470 CURLOPT_POSTREDIR: method switch
471 CURLINFO_REDIRECT_URL: custom redirect option
472 CURLOPT_REDIRECT_PROTOCOLS
473 CURLINFO_REDIRECT_COUNT
474 */
475 }
476
477 /* no-body */
478 if (no_body)
479 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_NOBODY, 1), "CURLOPT_NOBODY");
480
481 /* IPv4 or IPv6 forced DNS resolution */
482 if (address_family == AF_UNSPEC)
483 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_WHATEVER)");
484 else if (address_family == AF_INET)
485 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V4)");
486#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6)
487 else if (address_family == AF_INET6)
488 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V6)");
489#endif
490
491 /* either send http POST data (any data, not only POST)*/
492 if (!strcmp(http_method, "POST") ||!strcmp(http_method, "PUT")) {
493 /* set content of payload for POST and PUT */
494 if (http_content_type) {
495 snprintf (http_header, DEFAULT_BUFFER_SIZE, "Content-Type: %s", http_content_type);
496 header_list = curl_slist_append (header_list, http_header);
497 }
498 /* NULL indicates "HTTP Continue" in libcurl, provide an empty string
499 * in case of no POST/PUT data */
500 if (!http_post_data)
501 http_post_data = "";
502 if (!strcmp(http_method, "POST")) {
503 /* POST method, set payload with CURLOPT_POSTFIELDS */
504 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POSTFIELDS, http_post_data), "CURLOPT_POSTFIELDS");
505 } else if (!strcmp(http_method, "PUT")) {
506 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READFUNCTION, (curl_read_callback)curlhelp_buffer_read_callback), "CURLOPT_READFUNCTION");
507 curlhelp_initreadbuffer (&put_buf, http_post_data, strlen (http_post_data));
508 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READDATA, (void *)&put_buf), "CURLOPT_READDATA");
509 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_INFILESIZE, (curl_off_t)strlen (http_post_data)), "CURLOPT_INFILESIZE");
510 }
511 }
512
513 /* do the request */
514 res = curl_easy_perform(curl);
515
516 if (verbose>=2 && http_post_data)
517 printf ("**** REQUEST CONTENT ****\n%s\n", http_post_data);
518
519 /* free header list, we don't need it anymore */
520 curl_slist_free_all(header_list);
521
522 /* Curl errors, result in critical Nagios state */
523 if (res != CURLE_OK) {
524 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: cURL returned %d - %s"),
525 server_port, res, curl_easy_strerror(res));
526 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
527 }
528
529 /* certificate checks */
530#ifdef LIBCURL_FEATURE_SSL
531 if (use_ssl == TRUE) {
532 if (check_cert == TRUE) {
533 if (is_openssl_callback) {
534#ifdef USE_OPENSSL
535 /* check certificate with OpenSSL functions, curl has been built against OpenSSL
536 * and we actually have OpenSSL in the monitoring tools
537 */
538 result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit);
539 return result;
540#else /* USE_OPENSSL */
541 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL callback used and not linked against OpenSSL\n");
542#endif /* USE_OPENSSL */
543 } else {
544 int i;
545 struct curl_slist *slist;
546
547 cert_ptr.to_info = NULL;
548 res = curl_easy_getinfo (curl, CURLINFO_CERTINFO, &cert_ptr.to_info);
549 if (!res && cert_ptr.to_info) {
550#ifdef USE_OPENSSL
551 /* We have no OpenSSL in libcurl, but we can use OpenSSL for X509 cert parsing
552 * We only check the first certificate and assume it's the one of the server
553 */
554 const char* raw_cert = NULL;
555 for (i = 0; i < cert_ptr.to_certinfo->num_of_certs; i++) {
556 for (slist = cert_ptr.to_certinfo->certinfo[i]; slist; slist = slist->next) {
557 if (verbose >= 2)
558 printf ("%d ** %s\n", i, slist->data);
559 if (strncmp (slist->data, "Cert:", 5) == 0) {
560 raw_cert = &slist->data[5];
561 goto GOT_FIRST_CERT;
562 }
563 }
564 }
565GOT_FIRST_CERT:
566 if (!raw_cert) {
567 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates from CERTINFO information - certificate data was empty"));
568 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
569 }
570 BIO* cert_BIO = BIO_new (BIO_s_mem());
571 BIO_write (cert_BIO, raw_cert, strlen(raw_cert));
572 cert = PEM_read_bio_X509 (cert_BIO, NULL, NULL, NULL);
573 if (!cert) {
574 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot read certificate from CERTINFO information - BIO error"));
575 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
576 }
577 BIO_free (cert_BIO);
578 result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit);
579 return result;
580#else /* USE_OPENSSL */
581 /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our disposal,
582 * so we use the libcurl CURLINFO data
583 */
584 result = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit);
585 return result;
586#endif /* USE_OPENSSL */
587 } else {
588 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates - cURL returned %d - %s"),
589 res, curl_easy_strerror(res));
590 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
591 }
592 }
593 }
594 }
595#endif /* LIBCURL_FEATURE_SSL */
596
597 /* we got the data and we executed the request in a given time, so we can append
598 * performance data to the answer always
599 */
600 handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_TOTAL_TIME, &total_time), "CURLINFO_TOTAL_TIME");
601 if(show_extended_perfdata) {
602 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &time_connect), "CURLINFO_CONNECT_TIME");
603 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &time_appconnect), "CURLINFO_APPCONNECT_TIME");
604 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &time_headers), "CURLINFO_PRETRANSFER_TIME");
605 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &time_firstbyte), "CURLINFO_STARTTRANSFER_TIME");
606 snprintf(perfstring, DEFAULT_BUFFER_SIZE, "time=%.6gs;%.6g;%.6g;; size=%dB;;; time_connect=%.6gs;;;; %s time_headers=%.6gs;;;; time_firstbyte=%.6gs;;;; time_transfer=%.6gs;;;;",
607 total_time,
608 warning_thresholds != NULL ? (double)thlds->warning->end : 0.0,
609 critical_thresholds != NULL ? (double)thlds->critical->end : 0.0,
610 (int)body_buf.buflen,
611 time_connect,
612 use_ssl == TRUE ? perfd_time_ssl(time_appconnect-time_connect) : "",
613 (time_headers - time_appconnect),
614 (time_firstbyte - time_headers),
615 (total_time-time_firstbyte)
616 );
617 } else {
618 snprintf(perfstring, DEFAULT_BUFFER_SIZE, "time=%.6gs;%.6g;%.6g;; size=%dB;;;",
619 total_time,
620 warning_thresholds != NULL ? (double)thlds->warning->end : 0.0,
621 critical_thresholds != NULL ? (double)thlds->critical->end : 0.0,
622 (int)body_buf.buflen);
623 }
624
625 /* return a CRITICAL status if we couldn't read any data */
626 if (strlen(header_buf.buf) == 0 && strlen(body_buf.buf) == 0)
627 die (STATE_CRITICAL, _("HTTP CRITICAL - No header received from host\n"));
628
629 /* get status line of answer, check sanity of HTTP code */
630 if (curlhelp_parse_statusline (header_buf.buf, &status_line) < 0) {
631 snprintf (msg, DEFAULT_BUFFER_SIZE, "Unparseable status line in %.3g seconds response time|%s\n",
632 code, total_time, perfstring);
633 die (STATE_CRITICAL, "HTTP CRITICAL HTTP/1.x %d unknown - %s", code, msg);
634 }
635
636 /* get result code from cURL */
637 handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE");
638 if (verbose>=2)
639 printf ("* curl CURLINFO_RESPONSE_CODE is %d\n", code);
640
641 /* print status line, header, body if verbose */
642 if (verbose >= 2) {
643 printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header_buf.buf,
644 (no_body ? " [[ skipped ]]" : body_buf.buf));
645 }
646
647 /* make sure the status line matches the response we are looking for */
648 if (!expected_statuscode(status_line.first_line, server_expect)) {
649 /* TODO: fix first_line being cut off */
650 if (server_port == HTTP_PORT)
651 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host: %s\n"), status_line.first_line);
652 else
653 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: %s\n"), server_port, status_line.first_line);
654 die (STATE_CRITICAL, "HTTP CRITICAL - %s", msg);
655 }
656
657 /* TODO: implement -d header tests */
658 if( server_expect_yn ) {
659 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Status line output matched \"%s\" - "), server_expect);
660 if (verbose)
661 printf ("%s\n",msg);
662 result = STATE_OK;
663 }
664 else {
665 /* illegal return codes result in a critical state */
666 if (code >= 600 || code < 100) {
667 die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%d, %.40s)\n"), status_line.http_code, status_line.msg);
668 /* server errors result in a critical state */
669 } else if (code >= 500) {
670 result = STATE_CRITICAL;
671 /* client errors result in a warning state */
672 } else if (code >= 400) {
673 result = STATE_WARNING;
674 /* check redirected page if specified */
675 } else if (code >= 300) {
676 if (onredirect == STATE_DEPENDENT) {
677 code = status_line.http_code;
678 }
679 result = max_state_alt (onredirect, result);
680 /* TODO: make sure the last status line has been
681 parsed into the status_line structure
682 */
683 /* all other codes are considered ok */
684 } else {
685 result = STATE_OK;
686 }
687 }
688
689 /* check status codes, set exit status accordingly */
690 if( status_line.http_code != code ) {
691 die (STATE_CRITICAL, _("HTTP CRITICAL HTTP/%d.%d %d %s - different HTTP codes (cUrl has %ld)\n"),
692 status_line.http_major, status_line.http_minor,
693 status_line.http_code, status_line.msg, code);
694 }
695
696 if (maximum_age >= 0) {
697 result = max_state_alt(check_document_dates(&header_buf, &msg), result);
698 }
699
700 /* Page and Header content checks go here */
701
702 if (strlen (header_expect)) {
703 if (!strstr (header_buf.buf, header_expect)) {
704 strncpy(&output_header_search[0],header_expect,sizeof(output_header_search));
705 if(output_header_search[sizeof(output_header_search)-1]!='\0') {
706 bcopy("...",&output_header_search[sizeof(output_header_search)-4],4);
707 }
708 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%sheader '%s' not found on '%s://%s:%d%s', "), msg, output_header_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url);
709 result = STATE_CRITICAL;
710 }
711 }
712
713 if (strlen (string_expect)) {
714 if (!strstr (body_buf.buf, string_expect)) {
715 strncpy(&output_string_search[0],string_expect,sizeof(output_string_search));
716 if(output_string_search[sizeof(output_string_search)-1]!='\0') {
717 bcopy("...",&output_string_search[sizeof(output_string_search)-4],4);
718 }
719 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%sstring '%s' not found on '%s://%s:%d%s', "), msg, output_string_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url);
720 result = STATE_CRITICAL;
721 }
722 }
723
724 if (strlen (regexp)) {
725 errcode = regexec (&preg, body_buf.buf, REGS, pmatch, 0);
726 if ((errcode == 0 && invert_regex == 0) || (errcode == REG_NOMATCH && invert_regex == 1)) {
727 /* OK - No-op to avoid changing the logic around it */
728 result = max_state_alt(STATE_OK, result);
729 }
730 else if ((errcode == REG_NOMATCH && invert_regex == 0) || (errcode == 0 && invert_regex == 1)) {
731 if (invert_regex == 0)
732 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spattern not found, "), msg);
733 else
734 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spattern found, "), msg);
735 result = STATE_CRITICAL;
736 }
737 else {
738 /* FIXME: Shouldn't that be UNKNOWN? */
739 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
740 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%sExecute Error: %s, "), msg, errbuf);
741 result = STATE_CRITICAL;
742 }
743 }
744
745 /* make sure the page is of an appropriate size
746 * TODO: as far I can tell check_http gets the full size of header and
747 * if -N is not given header+body. Does this make sense?
748 *
749 * TODO: check_http.c had a get_length function, the question is really
750 * here what to use? the raw data size of the header_buf, the value of
751 * Content-Length, both and warn if they differ? Should the length be
752 * header+body or only body?
753 *
754 * One possible policy:
755 * - use header_buf.buflen (warning, if it mismatches to the Content-Length value
756 * - if -N (nobody) is given, use Content-Length only and hope the server set
757 * the value correcly
758 */
759 page_len = header_buf.buflen + body_buf.buflen;
760 if ((max_page_len > 0) && (page_len > max_page_len)) {
761 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spage size %d too large, "), msg, page_len);
762 result = max_state_alt(STATE_WARNING, result);
763 } else if ((min_page_len > 0) && (page_len < min_page_len)) {
764 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spage size %d too small, "), msg, page_len);
765 result = max_state_alt(STATE_WARNING, result);
766 }
767
768 /* -w, -c: check warning and critical level */
769 result = max_state_alt(get_status(total_time, thlds), result);
770
771 /* Cut-off trailing characters */
772 if(msg[strlen(msg)-2] == ',')
773 msg[strlen(msg)-2] = '\0';
774 else
775 msg[strlen(msg)-3] = '\0';
776
777 /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */
778 die (result, "HTTP %s: HTTP/%d.%d %d %s%s%s - %d bytes in %.3f second response time %s|%s\n",
779 state_text(result), status_line.http_major, status_line.http_minor,
780 status_line.http_code, status_line.msg,
781 strlen(msg) > 0 ? " - " : "",
782 msg, page_len, total_time,
783 (display_html ? "</A>" : ""),
784 perfstring);
785
786 /* proper cleanup after die? */
787 curlhelp_free_statusline(&status_line);
788 curl_easy_cleanup (curl);
789 curl_global_cleanup ();
790 curlhelp_freewritebuffer (&body_buf);
791 curlhelp_freewritebuffer (&header_buf);
792 if (!strcmp (http_method, "PUT")) {
793 curlhelp_freereadbuffer (&put_buf);
794 }
795
796 return result;
797}
798
799/* check whether a file exists */
800void
801test_file (char *path)
802{
803 if (access(path, R_OK) == 0)
804 return;
805 usage2 (_("file does not exist or is not readable"), path);
806}
807
808int
809process_arguments (int argc, char **argv)
810{
811 char *p;
812 int c = 1;
813 char *temp;
814
815 enum {
816 INVERT_REGEX = CHAR_MAX + 1,
817 SNI_OPTION,
818 CA_CERT_OPTION
819 };
820
821 int option = 0;
822 int got_plus = 0;
823 static struct option longopts[] = {
824 STD_LONG_OPTS,
825 {"link", no_argument, 0, 'L'},
826 {"nohtml", no_argument, 0, 'n'},
827 {"ssl", optional_argument, 0, 'S'},
828 {"sni", no_argument, 0, SNI_OPTION},
829 {"post", required_argument, 0, 'P'},
830 {"method", required_argument, 0, 'j'},
831 {"IP-address", required_argument, 0, 'I'},
832 {"url", required_argument, 0, 'u'},
833 {"port", required_argument, 0, 'p'},
834 {"authorization", required_argument, 0, 'a'},
835 {"header-string", required_argument, 0, 'd'},
836 {"string", required_argument, 0, 's'},
837 {"expect", required_argument, 0, 'e'},
838 {"regex", required_argument, 0, 'r'},
839 {"ereg", required_argument, 0, 'r'},
840 {"eregi", required_argument, 0, 'R'},
841 {"linespan", no_argument, 0, 'l'},
842 {"onredirect", required_argument, 0, 'f'},
843 {"certificate", required_argument, 0, 'C'},
844 {"client-cert", required_argument, 0, 'J'},
845 {"private-key", required_argument, 0, 'K'},
846 {"ca-cert", required_argument, 0, CA_CERT_OPTION},
847 {"useragent", required_argument, 0, 'A'},
848 {"header", required_argument, 0, 'k'},
849 {"no-body", no_argument, 0, 'N'},
850 {"max-age", required_argument, 0, 'M'},
851 {"content-type", required_argument, 0, 'T'},
852 {"pagesize", required_argument, 0, 'm'},
853 {"invert-regex", no_argument, NULL, INVERT_REGEX},
854 {"use-ipv4", no_argument, 0, '4'},
855 {"use-ipv6", no_argument, 0, '6'},
856 {"extended-perfdata", no_argument, 0, 'E'},
857 {0, 0, 0, 0}
858 };
859
860 if (argc < 2)
861 return ERROR;
862
863 /* support check_http compatible arguments */
864 for (c = 1; c < argc; c++) {
865 if (strcmp ("-to", argv[c]) == 0)
866 strcpy (argv[c], "-t");
867 if (strcmp ("-hn", argv[c]) == 0)
868 strcpy (argv[c], "-H");
869 if (strcmp ("-wt", argv[c]) == 0)
870 strcpy (argv[c], "-w");
871 if (strcmp ("-ct", argv[c]) == 0)
872 strcpy (argv[c], "-c");
873 if (strcmp ("-nohtml", argv[c]) == 0)
874 strcpy (argv[c], "-n");
875 }
876
877 while (1) {
878 c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:p:d:e:s:R:r:u:f:C:J:K:nLS::m:M:NE", longopts, &option);
879 if (c == -1 || c == EOF || c == 1)
880 break;
881
882 switch (c) {
883 case 'h':
884 print_help();
885 exit(STATE_UNKNOWN);
886 break;
887 case 'V':
888 print_revision(progname, NP_VERSION);
889 print_curl_version();
890 exit(STATE_UNKNOWN);
891 break;
892 case 'v':
893 verbose++;
894 break;
895 case 't': /* timeout period */
896 if (!is_intnonneg (optarg))
897 usage2 (_("Timeout interval must be a positive integer"), optarg);
898 else
899 socket_timeout = (int)strtol (optarg, NULL, 10);
900 break;
901 case 'c': /* critical time threshold */
902 critical_thresholds = optarg;
903 break;
904 case 'w': /* warning time threshold */
905 warning_thresholds = optarg;
906 break;
907 case 'H': /* virtual host */
908 host_name = strdup (optarg);
909 if (host_name[0] == '[') {
910 if ((p = strstr (host_name, "]:")) != NULL) { /* [IPv6]:port */
911 virtual_port = atoi (p + 2);
912 /* cut off the port */
913 host_name_length = strlen (host_name) - strlen (p) - 1;
914 free (host_name);
915 host_name = strndup (optarg, host_name_length);
916 }
917 } else if ((p = strchr (host_name, ':')) != NULL
918 && strchr (++p, ':') == NULL) { /* IPv4:port or host:port */
919 virtual_port = atoi (p);
920 /* cut off the port */
921 host_name_length = strlen (host_name) - strlen (p) - 1;
922 free (host_name);
923 host_name = strndup (optarg, host_name_length);
924 }
925 break;
926 case 'I': /* internet address */
927 server_address = strdup (optarg);
928 break;
929 case 'u': /* URL path */
930 server_url = strdup (optarg);
931 break;
932 case 'p': /* Server port */
933 if (!is_intnonneg (optarg))
934 usage2 (_("Invalid port number, expecting a non-negative number"), optarg);
935 else {
936 if( strtol(optarg, NULL, 10) > MAX_PORT)
937 usage2 (_("Invalid port number, supplied port number is too big"), optarg);
938 server_port = (unsigned short)strtol(optarg, NULL, 10);
939 }
940 break;
941 case 'a': /* authorization info */
942 strncpy (user_auth, optarg, MAX_INPUT_BUFFER - 1);
943 user_auth[MAX_INPUT_BUFFER - 1] = 0;
944 break;
945 case 'P': /* HTTP POST data in URL encoded format; ignored if settings already */
946 if (! http_post_data)
947 http_post_data = strdup (optarg);
948 if (! http_method)
949 http_method = strdup("POST");
950 break;
951 case 'j': /* Set HTTP method */
952 if (http_method)
953 free(http_method);
954 http_method = strdup (optarg);
955 break;
956 case 'A': /* useragent */
957 snprintf (user_agent, DEFAULT_BUFFER_SIZE, optarg);
958 break;
959 case 'k': /* Additional headers */
960 header_list = curl_slist_append(header_list, optarg);
961 break;
962 case 'L': /* show html link */
963 display_html = TRUE;
964 break;
965 case 'n': /* do not show html link */
966 display_html = FALSE;
967 break;
968 case 'C': /* Check SSL cert validity */
969#ifdef LIBCURL_FEATURE_SSL
970 if ((temp=strchr(optarg,','))!=NULL) {
971 *temp='\0';
972 if (!is_intnonneg (optarg))
973 usage2 (_("Invalid certificate expiration period"), optarg);
974 days_till_exp_warn = atoi(optarg);
975 *temp=',';
976 temp++;
977 if (!is_intnonneg (temp))
978 usage2 (_("Invalid certificate expiration period"), temp);
979 days_till_exp_crit = atoi (temp);
980 }
981 else {
982 days_till_exp_crit=0;
983 if (!is_intnonneg (optarg))
984 usage2 (_("Invalid certificate expiration period"), optarg);
985 days_till_exp_warn = atoi (optarg);
986 }
987 check_cert = TRUE;
988 goto enable_ssl;
989#endif
990 case 'J': /* use client certificate */
991#ifdef LIBCURL_FEATURE_SSL
992 test_file(optarg);
993 client_cert = optarg;
994 goto enable_ssl;
995#endif
996 case 'K': /* use client private key */
997#ifdef LIBCURL_FEATURE_SSL
998 test_file(optarg);
999 client_privkey = optarg;
1000 goto enable_ssl;
1001#endif
1002#ifdef LIBCURL_FEATURE_SSL
1003 case CA_CERT_OPTION: /* use CA chain file */
1004 test_file(optarg);
1005 ca_cert = optarg;
1006 goto enable_ssl;
1007#endif
1008 case 'S': /* use SSL */
1009#ifdef LIBCURL_FEATURE_SSL
1010 enable_ssl:
1011 use_ssl = TRUE;
1012 /* ssl_version initialized to CURL_SSLVERSION_TLSv1_0 as a default.
1013 * Only set if it's non-zero. This helps when we include multiple
1014 * parameters, like -S and -C combinations */
1015 ssl_version = CURL_SSLVERSION_TLSv1_0;
1016 if (c=='S' && optarg != NULL) {
1017 char *plus_ptr = strchr(optarg, '+');
1018 if (plus_ptr) {
1019 got_plus = 1;
1020 *plus_ptr = '\0';
1021 }
1022
1023 if (optarg[0] == '2')
1024 ssl_version = CURL_SSLVERSION_SSLv2;
1025 else if (optarg[0] == '3')
1026 ssl_version = CURL_SSLVERSION_SSLv3;
1027 else if (!strcmp (optarg, "1") || !strcmp (optarg, "1.0"))
1028#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1029 ssl_version = CURL_SSLVERSION_TLSv1_0;
1030#else
1031 ssl_version = CURL_SSLVERSION_DEFAULT;
1032#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1033 else if (!strcmp (optarg, "1.1"))
1034#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1035 ssl_version = CURL_SSLVERSION_TLSv1_1;
1036#else
1037 ssl_version = CURL_SSLVERSION_DEFAULT;
1038#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1039 else if (!strcmp (optarg, "1.2"))
1040#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1041 ssl_version = CURL_SSLVERSION_TLSv1_2;
1042#else
1043 ssl_version = CURL_SSLVERSION_DEFAULT;
1044#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1045 else if (!strcmp (optarg, "1.3"))
1046#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0)
1047 ssl_version = CURL_SSLVERSION_TLSv1_3;
1048#else
1049 ssl_version = CURL_SSLVERSION_DEFAULT;
1050#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) */
1051 else
1052 usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2 (with optional '+' suffix)"));
1053 }
1054#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0)
1055 if (got_plus) {
1056 switch (ssl_version) {
1057 case CURL_SSLVERSION_TLSv1_3:
1058 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3;
1059 break;
1060 case CURL_SSLVERSION_TLSv1_2:
1061 case CURL_SSLVERSION_TLSv1_1:
1062 case CURL_SSLVERSION_TLSv1_0:
1063 ssl_version |= CURL_SSLVERSION_MAX_DEFAULT;
1064 break;
1065 }
1066 } else {
1067 switch (ssl_version) {
1068 case CURL_SSLVERSION_TLSv1_3:
1069 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3;
1070 break;
1071 case CURL_SSLVERSION_TLSv1_2:
1072 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_2;
1073 break;
1074 case CURL_SSLVERSION_TLSv1_1:
1075 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_1;
1076 break;
1077 case CURL_SSLVERSION_TLSv1_0:
1078 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_0;
1079 break;
1080 }
1081 }
1082#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) */
1083 if (verbose >= 2)
1084 printf(_("* Set SSL/TLS version to %d\n"), ssl_version);
1085 if (server_port == HTTP_PORT)
1086 server_port = HTTPS_PORT;
1087 break;
1088#else /* LIBCURL_FEATURE_SSL */
1089 /* -C -J and -K fall through to here without SSL */
1090 usage4 (_("Invalid option - SSL is not available"));
1091 break;
1092 case SNI_OPTION: /* --sni is parsed, but ignored, the default is TRUE with libcurl */
1093 use_sni = TRUE;
1094 break;
1095#endif /* LIBCURL_FEATURE_SSL */
1096 case 'f': /* onredirect */
1097 if (!strcmp (optarg, "ok"))
1098 onredirect = STATE_OK;
1099 else if (!strcmp (optarg, "warning"))
1100 onredirect = STATE_WARNING;
1101 else if (!strcmp (optarg, "critical"))
1102 onredirect = STATE_CRITICAL;
1103 else if (!strcmp (optarg, "unknown"))
1104 onredirect = STATE_UNKNOWN;
1105 else if (!strcmp (optarg, "follow"))
1106 onredirect = STATE_DEPENDENT;
1107 else usage2 (_("Invalid onredirect option"), optarg);
1108 if (verbose >= 2)
1109 printf(_("* Following redirects set to %s\n"), state_text(onredirect));
1110 break;
1111 case 'd': /* string or substring */
1112 strncpy (header_expect, optarg, MAX_INPUT_BUFFER - 1);
1113 header_expect[MAX_INPUT_BUFFER - 1] = 0;
1114 break;
1115 case 's': /* string or substring */
1116 strncpy (string_expect, optarg, MAX_INPUT_BUFFER - 1);
1117 string_expect[MAX_INPUT_BUFFER - 1] = 0;
1118 break;
1119 case 'e': /* string or substring */
1120 strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1);
1121 server_expect[MAX_INPUT_BUFFER - 1] = 0;
1122 server_expect_yn = 1;
1123 break;
1124 case 'T': /* Content-type */
1125 http_content_type = strdup (optarg);
1126 break;
1127 case 'l': /* linespan */
1128 cflags &= ~REG_NEWLINE;
1129 break;
1130 case 'R': /* regex */
1131 cflags |= REG_ICASE;
1132 case 'r': /* regex */
1133 strncpy (regexp, optarg, MAX_RE_SIZE - 1);
1134 regexp[MAX_RE_SIZE - 1] = 0;
1135 errcode = regcomp (&preg, regexp, cflags);
1136 if (errcode != 0) {
1137 (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
1138 printf (_("Could Not Compile Regular Expression: %s"), errbuf);
1139 return ERROR;
1140 }
1141 break;
1142 case INVERT_REGEX:
1143 invert_regex = 1;
1144 break;
1145 case '4':
1146 address_family = AF_INET;
1147 break;
1148 case '6':
1149#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6)
1150 address_family = AF_INET6;
1151#else
1152 usage4 (_("IPv6 support not available"));
1153#endif
1154 break;
1155 case 'm': /* min_page_length */
1156 {
1157 char *tmp;
1158 if (strchr(optarg, ':') != (char *)NULL) {
1159 /* range, so get two values, min:max */
1160 tmp = strtok(optarg, ":");
1161 if (tmp == NULL) {
1162 printf("Bad format: try \"-m min:max\"\n");
1163 exit (STATE_WARNING);
1164 } else
1165 min_page_len = atoi(tmp);
1166
1167 tmp = strtok(NULL, ":");
1168 if (tmp == NULL) {
1169 printf("Bad format: try \"-m min:max\"\n");
1170 exit (STATE_WARNING);
1171 } else
1172 max_page_len = atoi(tmp);
1173 } else
1174 min_page_len = atoi (optarg);
1175 break;
1176 }
1177 case 'N': /* no-body */
1178 no_body = TRUE;
1179 break;
1180 case 'M': /* max-age */
1181 {
1182 int L = strlen(optarg);
1183 if (L && optarg[L-1] == 'm')
1184 maximum_age = atoi (optarg) * 60;
1185 else if (L && optarg[L-1] == 'h')
1186 maximum_age = atoi (optarg) * 60 * 60;
1187 else if (L && optarg[L-1] == 'd')
1188 maximum_age = atoi (optarg) * 60 * 60 * 24;
1189 else if (L && (optarg[L-1] == 's' ||
1190 isdigit (optarg[L-1])))
1191 maximum_age = atoi (optarg);
1192 else {
1193 fprintf (stderr, "unparsable max-age: %s\n", optarg);
1194 exit (STATE_WARNING);
1195 }
1196 if (verbose >= 2)
1197 printf ("* Maximal age of document set to %d seconds\n", maximum_age);
1198 }
1199 break;
1200 case 'E': /* show extended perfdata */
1201 show_extended_perfdata = TRUE;
1202 break;
1203 case '?':
1204 /* print short usage statement if args not parsable */
1205 usage5 ();
1206 break;
1207 }
1208 }
1209
1210 c = optind;
1211
1212 if (server_address == NULL && c < argc)
1213 server_address = strdup (argv[c++]);
1214
1215 if (host_name == NULL && c < argc)
1216 host_name = strdup (argv[c++]);
1217
1218 if (server_address == NULL) {
1219 if (host_name == NULL)
1220 usage4 (_("You must specify a server address or host name"));
1221 else
1222 server_address = strdup (host_name);
1223 }
1224
1225 set_thresholds(&thlds, warning_thresholds, critical_thresholds);
1226
1227 if (critical_thresholds && thlds->critical->end>(double)socket_timeout)
1228 socket_timeout = (int)thlds->critical->end + 1;
1229 if (verbose >= 2)
1230 printf ("* Socket timeout set to %d seconds\n", socket_timeout);
1231
1232 if (http_method == NULL)
1233 http_method = strdup ("GET");
1234
1235 if (client_cert && !client_privkey)
1236 usage4 (_("If you use a client certificate you must also specify a private key file"));
1237
1238 if (virtual_port == 0)
1239 virtual_port = server_port;
1240
1241 return TRUE;
1242}
1243
1244void
1245print_help (void)
1246{
1247 print_revision (progname, NP_VERSION);
1248
1249 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
1250 printf ("Copyright (c) 2017 Andreas Baumann <mail@andreasbaumann.cc>\n");
1251 printf (COPYRIGHT, copyright, email);
1252
1253 printf ("%s\n", _("This plugin tests the HTTP service on the specified host. It can test"));
1254 printf ("%s\n", _("normal (http) and secure (https) servers, follow redirects, search for"));
1255 printf ("%s\n", _("strings and regular expressions, check connection times, and report on"));
1256 printf ("%s\n", _("certificate expiration times."));
1257 printf ("\n");
1258 printf ("%s\n", _("It makes use of libcurl to do so. It tries to be as compatible to check_http"));
1259 printf ("%s\n", _("as possible."));
1260
1261 printf ("\n\n");
1262
1263 print_usage ();
1264
1265 printf (_("NOTE: One or both of -H and -I must be specified"));
1266
1267 printf ("\n");
1268
1269 printf (UT_HELP_VRSN);
1270 printf (UT_EXTRA_OPTS);
1271
1272 printf (" %s\n", "-H, --hostname=ADDRESS");
1273 printf (" %s\n", _("Host name argument for servers using host headers (virtual host)"));
1274 printf (" %s\n", _("Append a port to include it in the header (eg: example.com:5000)"));
1275 printf (" %s\n", "-I, --IP-address=ADDRESS");
1276 printf (" %s\n", _("IP address or name (use numeric address if possible to bypass DNS lookup)."));
1277 printf (" %s\n", "-p, --port=INTEGER");
1278 printf (" %s", _("Port number (default: "));
1279 printf ("%d)\n", HTTP_PORT);
1280
1281 printf (UT_IPv46);
1282
1283#ifdef LIBCURL_FEATURE_SSL
1284 printf (" %s\n", "-S, --ssl=VERSION[+]");
1285 printf (" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is optional, and prevents"));
1286 printf (" %s\n", _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,"));
1287 printf (" %s\n", _("1.2 = TLSv1.2). With a '+' suffix, newer versions are also accepted."));
1288 printf (" %s\n", _("Note: SSLv2 and SSLv3 are deprecated and are usually disabled in libcurl"));
1289 printf (" %s\n", "--sni");
1290 printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)"));
1291#if LIBCURL_VERSION_NUM >= 0x071801
1292 printf (" %s\n", _("Note: --sni is the default in libcurl as SSLv2 and SSLV3 are deprecated and"));
1293 printf (" %s\n", _(" SNI only really works since TLSv1.0"));
1294#else
1295 printf (" %s\n", _("Note: SNI is not supported in libcurl before 7.18.1"));
1296#endif
1297 printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]");
1298 printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443"));
1299 printf (" %s\n", _("(when this option is used the URL is not checked.)"));
1300 printf (" %s\n", "-J, --client-cert=FILE");
1301 printf (" %s\n", _("Name of file that contains the client certificate (PEM format)"));
1302 printf (" %s\n", _("to be used in establishing the SSL session"));
1303 printf (" %s\n", "-K, --private-key=FILE");
1304 printf (" %s\n", _("Name of file containing the private key (PEM format)"));
1305 printf (" %s\n", _("matching the client certificate"));
1306 printf (" %s\n", "--ca-cert=FILE");
1307 printf (" %s\n", _("CA certificate file to verify peer against"));
1308#endif
1309
1310 printf (" %s\n", "-e, --expect=STRING");
1311 printf (" %s\n", _("Comma-delimited list of strings, at least one of them is expected in"));
1312 printf (" %s", _("the first (status) line of the server response (default: "));
1313 printf ("%s)\n", HTTP_EXPECT);
1314 printf (" %s\n", _("If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)"));
1315 printf (" %s\n", "-d, --header-string=STRING");
1316 printf (" %s\n", _("String to expect in the response headers"));
1317 printf (" %s\n", "-s, --string=STRING");
1318 printf (" %s\n", _("String to expect in the content"));
1319 printf (" %s\n", "-u, --url=PATH");
1320 printf (" %s\n", _("URL to GET or POST (default: /)"));
1321 printf (" %s\n", "-P, --post=STRING");
1322 printf (" %s\n", _("URL encoded http POST data"));
1323 printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)");
1324 printf (" %s\n", _("Set HTTP method."));
1325 printf (" %s\n", "-N, --no-body");
1326 printf (" %s\n", _("Don't wait for document body: stop reading after headers."));
1327 printf (" %s\n", _("(Note that this still does an HTTP GET or POST, not a HEAD.)"));
1328 printf (" %s\n", "-M, --max-age=SECONDS");
1329 printf (" %s\n", _("Warn if document is more than SECONDS old. the number can also be of"));
1330 printf (" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or \"10d\" for days."));
1331 printf (" %s\n", "-T, --content-type=STRING");
1332 printf (" %s\n", _("specify Content-Type header media type when POSTing\n"));
1333 printf (" %s\n", "-l, --linespan");
1334 printf (" %s\n", _("Allow regex to span newlines (must precede -r or -R)"));
1335 printf (" %s\n", "-r, --regex, --ereg=STRING");
1336 printf (" %s\n", _("Search page for regex STRING"));
1337 printf (" %s\n", "-R, --eregi=STRING");
1338 printf (" %s\n", _("Search page for case-insensitive regex STRING"));
1339 printf (" %s\n", "--invert-regex");
1340 printf (" %s\n", _("Return CRITICAL if found, OK if not\n"));
1341 printf (" %s\n", "-a, --authorization=AUTH_PAIR");
1342 printf (" %s\n", _("Username:password on sites with basic authentication"));
1343 printf (" %s\n", "-A, --useragent=STRING");
1344 printf (" %s\n", _("String to be sent in http header as \"User Agent\""));
1345 printf (" %s\n", "-k, --header=STRING");
1346 printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers"));
1347 printf (" %s\n", "-E, --extended-perfdata");
1348 printf (" %s\n", _("Print additional performance data"));
1349 printf (" %s\n", "-L, --link");
1350 printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)"));
1351 printf (" %s\n", "-f, --onredirect=<ok|warning|critical|follow>");
1352 printf (" %s\n", _("How to handle redirected pages."));
1353 printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>");
1354 printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)"));
1355
1356 printf (UT_WARN_CRIT);
1357
1358 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
1359
1360 printf (UT_VERBOSE);
1361
1362 printf ("\n");
1363 printf ("%s\n", _("Notes:"));
1364 printf (" %s\n", _("This plugin will attempt to open an HTTP connection with the host."));
1365 printf (" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL"));
1366 printf (" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect response"));
1367 printf (" %s\n", _("messages from the host result in STATE_WARNING return values. If you are"));
1368 printf (" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN"));
1369 printf (" %s\n", _("(fully qualified domain name) as the [host_name] argument."));
1370
1371#ifdef LIBCURL_FEATURE_SSL
1372 printf ("\n");
1373 printf (" %s\n", _("This plugin can also check whether an SSL enabled web server is able to"));
1374 printf (" %s\n", _("serve content (optionally within a specified time) or whether the X509 "));
1375 printf (" %s\n", _("certificate is still valid for the specified number of days."));
1376 printf ("\n");
1377 printf (" %s\n", _("Please note that this plugin does not check if the presented server"));
1378 printf (" %s\n", _("certificate matches the hostname of the server, or if the certificate"));
1379 printf (" %s\n", _("has a valid chain of trust to one of the locally installed CAs."));
1380 printf ("\n");
1381 printf ("%s\n", _("Examples:"));
1382 printf (" %s\n\n", "CHECK CONTENT: check_curl -w 5 -c 10 --ssl -H www.verisign.com");
1383 printf (" %s\n", _("When the 'www.verisign.com' server returns its content within 5 seconds,"));
1384 printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds"));
1385 printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,"));
1386 printf (" %s\n", _("a STATE_CRITICAL will be returned."));
1387 printf ("\n");
1388 printf (" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 14");
1389 printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,"));
1390 printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
1391 printf (" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when"));
1392 printf (" %s\n\n", _("the certificate is expired."));
1393 printf ("\n");
1394 printf (" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 30,14");
1395 printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 30 days,"));
1396 printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
1397 printf (" %s\n", _("30 days, but more than 14 days, a STATE_WARNING is returned."));
1398 printf (" %s\n", _("A STATE_CRITICAL will be returned when certificate expires in less than 14 days"));
1399
1400 printf (" %s\n\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: ");
1401 printf (" %s\n", _("check_curl -I 192.168.100.35 -p 80 -u https://www.verisign.com/ -S -j CONNECT -H www.verisign.com "));
1402 printf (" %s\n", _("all these options are needed: -I <proxy> -p <proxy-port> -u <check-url> -S(sl) -j CONNECT -H <webserver>"));
1403 printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds"));
1404 printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,"));
1405 printf (" %s\n", _("a STATE_CRITICAL will be returned."));
1406
1407#endif
1408
1409 printf (UT_SUPPORT);
1410
1411}
1412
1413
1414
1415void
1416print_usage (void)
1417{
1418 printf ("%s\n", _("Usage:"));
1419 printf (" %s -H <vhost> | -I <IP-address> [-u <uri>] [-p <port>]\n",progname);
1420 printf (" [-J <client certificate file>] [-K <private key>] [--ca-cert <CA certificate file>]\n");
1421 printf (" [-w <warn time>] [-c <critical time>] [-t <timeout>] [-L] [-E] [-a auth]\n");
1422 printf (" [-f <ok|warning|critcal|follow>]\n");
1423 printf (" [-e <expect>] [-d string] [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n");
1424 printf (" [-P string] [-m <min_pg_size>:<max_pg_size>] [-4|-6] [-N] [-M <age>]\n");
1425 printf (" [-A string] [-k string] [-S <version>] [--sni] [-C <warn_age>[,<crit_age>]]\n");
1426 printf (" [-T <content-type>] [-j method]\n", progname);
1427 printf ("\n");
1428 printf ("%s\n", _("WARNING: check_curl is experimental. Please use"));
1429 printf ("%s\n\n", _("check_http if you need a stable version."));
1430}
1431
1432void
1433print_curl_version (void)
1434{
1435 printf( "%s\n", curl_version());
1436}
1437
1438int
1439curlhelp_initwritebuffer (curlhelp_write_curlbuf *buf)
1440{
1441 buf->bufsize = DEFAULT_BUFFER_SIZE;
1442 buf->buflen = 0;
1443 buf->buf = (char *)malloc ((size_t)buf->bufsize);
1444 if (buf->buf == NULL) return -1;
1445 return 0;
1446}
1447
1448int
1449curlhelp_buffer_write_callback (void *buffer, size_t size, size_t nmemb, void *stream)
1450{
1451 curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream;
1452
1453 while (buf->bufsize < buf->buflen + size * nmemb + 1) {
1454 buf->bufsize *= buf->bufsize * 2;
1455 buf->buf = (char *)realloc (buf->buf, buf->bufsize);
1456 if (buf->buf == NULL) return -1;
1457 }
1458
1459 memcpy (buf->buf + buf->buflen, buffer, size * nmemb);
1460 buf->buflen += size * nmemb;
1461 buf->buf[buf->buflen] = '\0';
1462
1463 return (int)(size * nmemb);
1464}
1465
1466int
1467curlhelp_buffer_read_callback (void *buffer, size_t size, size_t nmemb, void *stream)
1468{
1469 curlhelp_read_curlbuf *buf = (curlhelp_read_curlbuf *)stream;
1470
1471 size_t n = min (nmemb * size, buf->buflen - buf->pos);
1472
1473 memcpy (buffer, buf->buf + buf->pos, n);
1474 buf->pos += n;
1475
1476 return (int)n;
1477}
1478
1479void
1480curlhelp_freewritebuffer (curlhelp_write_curlbuf *buf)
1481{
1482 free (buf->buf);
1483 buf->buf = NULL;
1484}
1485
1486int
1487curlhelp_initreadbuffer (curlhelp_read_curlbuf *buf, const char *data, size_t datalen)
1488{
1489 buf->buflen = datalen;
1490 buf->buf = (char *)malloc ((size_t)buf->buflen);
1491 if (buf->buf == NULL) return -1;
1492 memcpy (buf->buf, data, datalen);
1493 buf->pos = 0;
1494 return 0;
1495}
1496
1497void
1498curlhelp_freereadbuffer (curlhelp_read_curlbuf *buf)
1499{
1500 free (buf->buf);
1501 buf->buf = NULL;
1502}
1503
1504/* TODO: where to put this, it's actually part of sstrings2 (logically)?
1505 */
1506const char*
1507strrstr2(const char *haystack, const char *needle)
1508{
1509 int counter;
1510 size_t len;
1511 const char *prev_pos;
1512 const char *pos;
1513
1514 if (haystack == NULL || needle == NULL)
1515 return NULL;
1516
1517 if (haystack[0] == '\0' || needle[0] == '\0')
1518 return NULL;
1519
1520 counter = 0;
1521 prev_pos = NULL;
1522 pos = haystack;
1523 len = strlen (needle);
1524 for (;;) {
1525 pos = strstr (pos, needle);
1526 if (pos == NULL) {
1527 if (counter == 0)
1528 return NULL;
1529 else
1530 return prev_pos;
1531 }
1532 counter++;
1533 prev_pos = pos;
1534 pos += len;
1535 if (*pos == '\0') return prev_pos;
1536 }
1537}
1538
1539int
1540curlhelp_parse_statusline (const char *buf, curlhelp_statusline *status_line)
1541{
1542 char *first_line_end;
1543 char *p;
1544 size_t first_line_len;
1545 char *pp;
1546 const char *start;
1547 char *first_line_buf;
1548
1549 /* find last start of a new header */
1550 start = strrstr2 (buf, "\r\nHTTP");
1551 if (start != NULL) {
1552 start += 2;
1553 buf = start;
1554 }
1555
1556 first_line_end = strstr(buf, "\r\n");
1557 if (first_line_end == NULL) return -1;
1558
1559 first_line_len = (size_t)(first_line_end - buf);
1560 status_line->first_line = (char *)malloc (first_line_len + 1);
1561 if (status_line->first_line == NULL) return -1;
1562 memcpy (status_line->first_line, buf, first_line_len);
1563 status_line->first_line[first_line_len] = '\0';
1564 first_line_buf = strdup( status_line->first_line );
1565
1566 /* protocol and version: "HTTP/x.x" SP */
1567
1568 p = strtok(first_line_buf, "/");
1569 if( p == NULL ) { free( first_line_buf ); return -1; }
1570 if( strcmp( p, "HTTP" ) != 0 ) { free( first_line_buf ); return -1; }
1571
1572 p = strtok( NULL, "." );
1573 if( p == NULL ) { free( first_line_buf ); return -1; }
1574 status_line->http_major = (int)strtol( p, &pp, 10 );
1575 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
1576
1577 p = strtok( NULL, " " );
1578 if( p == NULL ) { free( first_line_buf ); return -1; }
1579 status_line->http_minor = (int)strtol( p, &pp, 10 );
1580 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
1581
1582 /* status code: "404" or "404.1", then SP */
1583
1584 p = strtok( NULL, " ." );
1585 if( p == NULL ) { free( first_line_buf ); return -1; }
1586 if( strchr( p, '.' ) != NULL ) {
1587 char *ppp;
1588 ppp = strtok( p, "." );
1589 status_line->http_code = (int)strtol( ppp, &pp, 10 );
1590 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
1591
1592 ppp = strtok( NULL, "" );
1593 status_line->http_subcode = (int)strtol( ppp, &pp, 10 );
1594 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
1595 } else {
1596 status_line->http_code = (int)strtol( p, &pp, 10 );
1597 status_line->http_subcode = -1;
1598 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
1599 }
1600
1601 /* Human readable message: "Not Found" CRLF */
1602
1603 free( first_line_buf );
1604 p = strtok( NULL, "" );
1605 if( p == NULL ) { free( status_line->first_line ); return -1; }
1606 status_line->msg = status_line->first_line + ( p - first_line_buf );
1607
1608 return 0;
1609}
1610
1611void
1612curlhelp_free_statusline (curlhelp_statusline *status_line)
1613{
1614 free (status_line->first_line);
1615}
1616
1617void
1618remove_newlines (char *s)
1619{
1620 char *p;
1621
1622 for (p = s; *p != '\0'; p++)
1623 if (*p == '\r' || *p == '\n')
1624 *p = ' ';
1625}
1626
1627char *
1628perfd_time_ssl (double elapsed_time_ssl)
1629{
1630 return fperfdata ("time_ssl", elapsed_time_ssl, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0);
1631}
1632
1633char *
1634get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header)
1635{
1636 int i;
1637 for( i = 0; i < nof_headers; i++ ) {
1638 if( strncasecmp( header, headers[i].name, max( headers[i].name_len, 4 ) ) == 0 ) {
1639 return strndup( headers[i].value, headers[i].value_len );
1640 }
1641 }
1642 return NULL;
1643}
1644
1645int
1646check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFAULT_BUFFER_SIZE])
1647{
1648 char *server_date = NULL;
1649 char *document_date = NULL;
1650 int date_result = STATE_OK;
1651 curlhelp_statusline status_line;
1652 struct phr_header headers[255];
1653 size_t nof_headers = 255;
1654 size_t msglen;
1655
1656 int res = phr_parse_response (header_buf->buf, header_buf->buflen,
1657 &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen,
1658 headers, &nof_headers, 0);
1659
1660 server_date = get_header_value (headers, nof_headers, "date");
1661 document_date = get_header_value (headers, nof_headers, "last-modified");
1662
1663 if (!server_date || !*server_date) {
1664 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sServer date unknown, "), *msg);
1665 date_result = max_state_alt(STATE_UNKNOWN, date_result);
1666 } else if (!document_date || !*document_date) {
1667 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument modification date unknown, "), *msg);
1668 date_result = max_state_alt(STATE_CRITICAL, date_result);
1669 } else {
1670 time_t srv_data = curl_getdate (server_date, NULL);
1671 time_t doc_data = curl_getdate (document_date, NULL);
1672 if (verbose >= 2)
1673 printf ("* server date: '%s' (%d), doc_date: '%s' (%d)\n", server_date, srv_data, document_date, doc_data);
1674 if (srv_data <= 0) {
1675 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sServer date \"%100s\" unparsable, "), *msg, server_date);
1676 date_result = max_state_alt(STATE_CRITICAL, date_result);
1677 } else if (doc_data <= 0) {
1678 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date);
1679 date_result = max_state_alt(STATE_CRITICAL, date_result);
1680 } else if (doc_data > srv_data + 30) {
1681 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data);
1682 date_result = max_state_alt(STATE_CRITICAL, date_result);
1683 } else if (doc_data < srv_data - maximum_age) {
1684 int n = (srv_data - doc_data);
1685 if (n > (60 * 60 * 24 * 2)) {
1686 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24));
1687 date_result = max_state_alt(STATE_CRITICAL, date_result);
1688 } else {
1689 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60);
1690 date_result = max_state_alt(STATE_CRITICAL, date_result);
1691 }
1692 }
1693 }
1694
1695 if (server_date) free (server_date);
1696 if (document_date) free (document_date);
1697
1698 return date_result;
1699}
1700
1701/* TODO: is there a better way in libcurl to check for the SSL library? */
1702curlhelp_ssl_library
1703curlhelp_get_ssl_library (CURL* curl)
1704{
1705 curl_version_info_data* version_data;
1706 char *ssl_version;
1707 char *library;
1708 curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN;
1709
1710 version_data = curl_version_info (CURLVERSION_NOW);
1711 if (version_data == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN;
1712
1713 ssl_version = strdup (version_data->ssl_version);
1714 if (ssl_version == NULL ) return CURLHELP_SSL_LIBRARY_UNKNOWN;
1715
1716 library = strtok (ssl_version, "/");
1717 if (library == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN;
1718
1719 if (strcmp (library, "OpenSSL") == 0)
1720 ssl_library = CURLHELP_SSL_LIBRARY_OPENSSL;
1721 else if (strcmp (library, "LibreSSL") == 0)
1722 ssl_library = CURLHELP_SSL_LIBRARY_LIBRESSL;
1723 else if (strcmp (library, "GnuTLS") == 0)
1724 ssl_library = CURLHELP_SSL_LIBRARY_GNUTLS;
1725 else if (strcmp (library, "NSS") == 0)
1726 ssl_library = CURLHELP_SSL_LIBRARY_NSS;
1727
1728 if (verbose >= 2)
1729 printf ("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library, ssl_library);
1730
1731 free (ssl_version);
1732
1733 return ssl_library;
1734}
1735
1736const char*
1737curlhelp_get_ssl_library_string (curlhelp_ssl_library ssl_library)
1738{
1739 switch (ssl_library) {
1740 case CURLHELP_SSL_LIBRARY_OPENSSL:
1741 return "OpenSSL";
1742 case CURLHELP_SSL_LIBRARY_LIBRESSL:
1743 return "LibreSSL";
1744 case CURLHELP_SSL_LIBRARY_GNUTLS:
1745 return "GnuTLS";
1746 case CURLHELP_SSL_LIBRARY_NSS:
1747 return "NSS";
1748 case CURLHELP_SSL_LIBRARY_UNKNOWN:
1749 default:
1750 return "unknown";
1751 }
1752}
1753
1754#ifdef LIBCURL_FEATURE_SSL
1755#ifndef USE_OPENSSL
1756time_t
1757parse_cert_date (const char *s)
1758{
1759 struct tm tm;
1760 time_t date;
1761
1762 if (!s) return -1;
1763
1764 strptime (s, "%Y-%m-%d %H:%M:%S GMT", &tm);
1765 date = mktime (&tm);
1766
1767 return date;
1768}
1769
1770/* TODO: this needs cleanup in the sslutils.c, maybe we the #else case to
1771 * OpenSSL could be this function
1772 */
1773int
1774net_noopenssl_check_certificate (cert_ptr_union* cert_ptr, int days_till_exp_warn, int days_till_exp_crit)
1775{
1776 int i;
1777 struct curl_slist* slist;
1778 int cname_found = 0;
1779 char* start_date_str = NULL;
1780 char* end_date_str = NULL;
1781 time_t start_date;
1782 time_t end_date;
1783 char *tz;
1784 float time_left;
1785 int days_left;
1786 int time_remaining;
1787 char timestamp[50] = "";
1788 int status = STATE_UNKNOWN;
1789
1790 if (verbose >= 2)
1791 printf ("**** REQUEST CERTIFICATES ****\n");
1792
1793 for (i = 0; i < cert_ptr->to_certinfo->num_of_certs; i++) {
1794 for (slist = cert_ptr->to_certinfo->certinfo[i]; slist; slist = slist->next) {
1795 /* find first common name in subject, TODO: check alternative subjects for
1796 * multi-host certificate, check wildcards
1797 */
1798 if (strncmp (slist->data, "Subject:", 8) == 0) {
1799 char* p = strstr (slist->data, "CN=");
1800 if (p != NULL) {
1801 if (strncmp (host_name, p+3, strlen (host_name)) == 0) {
1802 cname_found = 1;
1803 }
1804 }
1805 } else if (strncmp (slist->data, "Start Date:", 11) == 0) {
1806 start_date_str = &slist->data[11];
1807 } else if (strncmp (slist->data, "Expire Date:", 12) == 0) {
1808 end_date_str = &slist->data[12];
1809 } else if (strncmp (slist->data, "Cert:", 5) == 0) {
1810 goto HAVE_FIRST_CERT;
1811 }
1812 if (verbose >= 2)
1813 printf ("%d ** %s\n", i, slist->data);
1814 }
1815 }
1816HAVE_FIRST_CERT:
1817
1818 if (verbose >= 2)
1819 printf ("**** REQUEST CERTIFICATES ****\n");
1820
1821 if (!cname_found) {
1822 printf("%s\n",_("CRITICAL - Cannot retrieve certificate subject."));
1823 return STATE_CRITICAL;
1824 }
1825
1826 start_date = parse_cert_date (start_date_str);
1827 if (start_date <= 0) {
1828 snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Start Date' in certificate: '%s'"),
1829 start_date_str);
1830 puts (msg);
1831 return STATE_WARNING;
1832 }
1833
1834 end_date = parse_cert_date (end_date_str);
1835 if (end_date <= 0) {
1836 snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Expire Date' in certificate: '%s'"),
1837 start_date_str);
1838 puts (msg);
1839 return STATE_WARNING;
1840 }
1841
1842 time_left = difftime (end_date, time(NULL));
1843 days_left = time_left / 86400;
1844 tz = getenv("TZ");
1845 setenv("TZ", "GMT", 1);
1846 tzset();
1847 strftime(timestamp, 50, "%c %z", localtime(&end_date));
1848 if (tz)
1849 setenv("TZ", tz, 1);
1850 else
1851 unsetenv("TZ");
1852 tzset();
1853
1854 if (days_left > 0 && days_left <= days_till_exp_warn) {
1855 printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, days_left, timestamp);
1856 if (days_left > days_till_exp_crit)
1857 status = STATE_WARNING;
1858 else
1859 status = STATE_CRITICAL;
1860 } else if (days_left == 0 && time_left > 0) {
1861 if (time_left >= 3600)
1862 time_remaining = (int) time_left / 3600;
1863 else
1864 time_remaining = (int) time_left / 60;
1865
1866 printf (_("%s - Certificate '%s' expires in %u %s (%s)\n"),
1867 (days_left>days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name, time_remaining,
1868 time_left >= 3600 ? "hours" : "minutes", timestamp);
1869
1870 if ( days_left > days_till_exp_crit)
1871 status = STATE_WARNING;
1872 else
1873 status = STATE_CRITICAL;
1874 } else if (time_left < 0) {
1875 printf(_("CRITICAL - Certificate '%s' expired on %s.\n"), host_name, timestamp);
1876 status=STATE_CRITICAL;
1877 } else if (days_left == 0) {
1878 printf (_("%s - Certificate '%s' just expired (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, timestamp);
1879 if (days_left > days_till_exp_crit)
1880 status = STATE_WARNING;
1881 else
1882 status = STATE_CRITICAL;
1883 } else {
1884 printf(_("OK - Certificate '%s' will expire on %s.\n"), host_name, timestamp);
1885 status = STATE_OK;
1886 }
1887 return status;
1888}
1889#endif /* USE_OPENSSL */
1890#endif /* LIBCURL_FEATURE_SSL */