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.c2358
1 files changed, 2358 insertions, 0 deletions
diff --git a/plugins/check_curl.c b/plugins/check_curl.c
new file mode 100644
index 0000000..ee9c8b1
--- /dev/null
+++ b/plugins/check_curl.c
@@ -0,0 +1,2358 @@
1/*****************************************************************************
2*
3* Monitoring check_curl plugin
4*
5* License: GPL
6* Copyright (c) 1999-2019 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-2019";
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#include "uriparser/Uri.h"
55
56#include <arpa/inet.h>
57
58#define MAKE_LIBCURL_VERSION(major, minor, patch) ((major)*0x10000 + (minor)*0x100 + (patch))
59
60#define DEFAULT_BUFFER_SIZE 2048
61#define DEFAULT_SERVER_URL "/"
62#define HTTP_EXPECT "HTTP/"
63#define DEFAULT_MAX_REDIRS 15
64#define INET_ADDR_MAX_SIZE INET6_ADDRSTRLEN
65enum {
66 MAX_IPV4_HOSTLENGTH = 255,
67 HTTP_PORT = 80,
68 HTTPS_PORT = 443,
69 MAX_PORT = 65535
70};
71
72enum {
73 STICKY_NONE = 0,
74 STICKY_HOST = 1,
75 STICKY_PORT = 2
76};
77
78enum {
79 FOLLOW_HTTP_CURL = 0,
80 FOLLOW_LIBCURL = 1
81};
82
83/* for buffers for header and body */
84typedef struct {
85 char *buf;
86 size_t buflen;
87 size_t bufsize;
88} curlhelp_write_curlbuf;
89
90/* for buffering the data sent in PUT */
91typedef struct {
92 char *buf;
93 size_t buflen;
94 off_t pos;
95} curlhelp_read_curlbuf;
96
97/* for parsing the HTTP status line */
98typedef struct {
99 int http_major; /* major version of the protocol, always 1 (HTTP/0.9
100 * never reached the big internet most likely) */
101 int http_minor; /* minor version of the protocol, usually 0 or 1 */
102 int http_code; /* HTTP return code as in RFC 2145 */
103 int http_subcode; /* Microsoft IIS extension, HTTP subcodes, see
104 * http://support.microsoft.com/kb/318380/en-us */
105 const char *msg; /* the human readable message */
106 char *first_line; /* a copy of the first line */
107} curlhelp_statusline;
108
109/* to know the underlying SSL library used by libcurl */
110typedef enum curlhelp_ssl_library {
111 CURLHELP_SSL_LIBRARY_UNKNOWN,
112 CURLHELP_SSL_LIBRARY_OPENSSL,
113 CURLHELP_SSL_LIBRARY_LIBRESSL,
114 CURLHELP_SSL_LIBRARY_GNUTLS,
115 CURLHELP_SSL_LIBRARY_NSS
116} curlhelp_ssl_library;
117
118enum {
119 REGS = 2,
120 MAX_RE_SIZE = 256
121};
122#include "regex.h"
123regex_t preg;
124regmatch_t pmatch[REGS];
125char regexp[MAX_RE_SIZE];
126int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE;
127int errcode;
128int invert_regex = 0;
129
130char *server_address = NULL;
131char *host_name = NULL;
132char *server_url = 0;
133char server_ip[DEFAULT_BUFFER_SIZE];
134struct curl_slist *server_ips = NULL;
135int specify_port = FALSE;
136unsigned short server_port = HTTP_PORT;
137unsigned short virtual_port = 0;
138int host_name_length;
139char output_header_search[30] = "";
140char output_string_search[30] = "";
141char *warning_thresholds = NULL;
142char *critical_thresholds = NULL;
143int days_till_exp_warn, days_till_exp_crit;
144thresholds *thlds;
145char user_agent[DEFAULT_BUFFER_SIZE];
146int verbose = 0;
147int show_extended_perfdata = FALSE;
148int min_page_len = 0;
149int max_page_len = 0;
150int redir_depth = 0;
151int max_depth = DEFAULT_MAX_REDIRS;
152char *http_method = NULL;
153char *http_post_data = NULL;
154char *http_content_type = NULL;
155CURL *curl;
156struct curl_slist *header_list = NULL;
157curlhelp_write_curlbuf body_buf;
158curlhelp_write_curlbuf header_buf;
159curlhelp_statusline status_line;
160curlhelp_read_curlbuf put_buf;
161char http_header[DEFAULT_BUFFER_SIZE];
162long code;
163long socket_timeout = DEFAULT_SOCKET_TIMEOUT;
164double total_time;
165double time_connect;
166double time_appconnect;
167double time_headers;
168double time_firstbyte;
169char errbuf[CURL_ERROR_SIZE+1];
170CURLcode res;
171char url[DEFAULT_BUFFER_SIZE];
172char msg[DEFAULT_BUFFER_SIZE];
173char perfstring[DEFAULT_BUFFER_SIZE];
174char header_expect[MAX_INPUT_BUFFER] = "";
175char string_expect[MAX_INPUT_BUFFER] = "";
176char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT;
177int server_expect_yn = 0;
178char user_auth[MAX_INPUT_BUFFER] = "";
179char proxy_auth[MAX_INPUT_BUFFER] = "";
180char **http_opt_headers;
181int http_opt_headers_count = 0;
182int display_html = FALSE;
183int onredirect = STATE_OK;
184int followmethod = FOLLOW_HTTP_CURL;
185int followsticky = STICKY_NONE;
186int use_ssl = FALSE;
187int use_sni = TRUE;
188int check_cert = FALSE;
189typedef union {
190 struct curl_slist* to_info;
191 struct curl_certinfo* to_certinfo;
192} cert_ptr_union;
193cert_ptr_union cert_ptr;
194int ssl_version = CURL_SSLVERSION_DEFAULT;
195char *client_cert = NULL;
196char *client_privkey = NULL;
197char *ca_cert = NULL;
198int is_openssl_callback = FALSE;
199#if defined(HAVE_SSL) && defined(USE_OPENSSL)
200X509 *cert = NULL;
201#endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */
202int no_body = FALSE;
203int maximum_age = -1;
204int address_family = AF_UNSPEC;
205curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN;
206int curl_http_version = CURL_HTTP_VERSION_NONE;
207
208int process_arguments (int, char**);
209void handle_curl_option_return_code (CURLcode res, const char* option);
210int check_http (void);
211void redir (curlhelp_write_curlbuf*);
212char *perfd_time (double microsec);
213char *perfd_time_connect (double microsec);
214char *perfd_time_ssl (double microsec);
215char *perfd_time_firstbyte (double microsec);
216char *perfd_time_headers (double microsec);
217char *perfd_time_transfer (double microsec);
218char *perfd_size (int page_len);
219void print_help (void);
220void print_usage (void);
221void print_curl_version (void);
222int curlhelp_initwritebuffer (curlhelp_write_curlbuf*);
223int curlhelp_buffer_write_callback (void*, size_t , size_t , void*);
224void curlhelp_freewritebuffer (curlhelp_write_curlbuf*);
225int curlhelp_initreadbuffer (curlhelp_read_curlbuf *, const char *, size_t);
226int curlhelp_buffer_read_callback (void *, size_t , size_t , void *);
227void curlhelp_freereadbuffer (curlhelp_read_curlbuf *);
228curlhelp_ssl_library curlhelp_get_ssl_library (CURL*);
229const char* curlhelp_get_ssl_library_string (curlhelp_ssl_library);
230int net_noopenssl_check_certificate (cert_ptr_union*, int, int);
231
232int curlhelp_parse_statusline (const char*, curlhelp_statusline *);
233void curlhelp_free_statusline (curlhelp_statusline *);
234char *get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header);
235int check_document_dates (const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]);
236int get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_write_curlbuf* body_buf);
237
238#if defined(HAVE_SSL) && defined(USE_OPENSSL)
239int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit);
240#endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */
241
242void remove_newlines (char *);
243void test_file (char *);
244
245int
246main (int argc, char **argv)
247{
248 int result = STATE_UNKNOWN;
249
250 setlocale (LC_ALL, "");
251 bindtextdomain (PACKAGE, LOCALEDIR);
252 textdomain (PACKAGE);
253
254 /* Parse extra opts if any */
255 argv = np_extra_opts (&argc, argv, progname);
256
257 /* set defaults */
258 snprintf( user_agent, DEFAULT_BUFFER_SIZE, "%s/v%s (monitoring-plugins %s, %s)",
259 progname, NP_VERSION, VERSION, curl_version());
260
261 /* parse arguments */
262 if (process_arguments (argc, argv) == ERROR)
263 usage4 (_("Could not parse arguments"));
264
265 if (display_html == TRUE)
266 printf ("<A HREF=\"%s://%s:%d%s\" target=\"_blank\">",
267 use_ssl ? "https" : "http",
268 host_name ? host_name : server_address,
269 virtual_port ? virtual_port : server_port,
270 server_url);
271
272 result = check_http ();
273 return result;
274}
275
276#ifdef HAVE_SSL
277#ifdef USE_OPENSSL
278
279int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
280{
281 /* TODO: we get all certificates of the chain, so which ones
282 * should we test?
283 * TODO: is the last certificate always the server certificate?
284 */
285 cert = X509_STORE_CTX_get_current_cert(x509_ctx);
286 return 1;
287}
288
289CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm)
290{
291 SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback);
292
293 return CURLE_OK;
294}
295
296#endif /* USE_OPENSSL */
297#endif /* HAVE_SSL */
298
299/* returns a string "HTTP/1.x" or "HTTP/2" */
300static char *string_statuscode (int major, int minor)
301{
302 static char buf[10];
303
304 switch (major) {
305 case 1:
306 snprintf (buf, sizeof (buf), "HTTP/%d.%d", major, minor);
307 break;
308 case 2:
309 case 3:
310 snprintf (buf, sizeof (buf), "HTTP/%d", major);
311 break;
312 default:
313 /* assuming here HTTP/N with N>=4 */
314 snprintf (buf, sizeof (buf), "HTTP/%d", major);
315 break;
316 }
317
318 return buf;
319}
320
321/* Checks if the server 'reply' is one of the expected 'statuscodes' */
322static int
323expected_statuscode (const char *reply, const char *statuscodes)
324{
325 char *expected, *code;
326 int result = 0;
327
328 if ((expected = strdup (statuscodes)) == NULL)
329 die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n"));
330
331 for (code = strtok (expected, ","); code != NULL; code = strtok (NULL, ","))
332 if (strstr (reply, code) != NULL) {
333 result = 1;
334 break;
335 }
336
337 free (expected);
338 return result;
339}
340
341void
342handle_curl_option_return_code (CURLcode res, const char* option)
343{
344 if (res != CURLE_OK) {
345 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Error while setting cURL option '%s': cURL returned %d - %s"),
346 option, res, curl_easy_strerror(res));
347 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
348 }
349}
350
351int
352check_http (void)
353{
354 int result = STATE_OK;
355 int page_len = 0;
356 int i;
357 char *force_host_header = NULL;
358
359 /* initialize curl */
360 if (curl_global_init (CURL_GLOBAL_DEFAULT) != CURLE_OK)
361 die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n");
362
363 if ((curl = curl_easy_init()) == NULL)
364 die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n");
365
366 if (verbose >= 1)
367 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_VERBOSE, TRUE), "CURLOPT_VERBOSE");
368
369 /* print everything on stdout like check_http would do */
370 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_STDERR, stdout), "CURLOPT_STDERR");
371
372 /* initialize buffer for body of the answer */
373 if (curlhelp_initwritebuffer(&body_buf) < 0)
374 die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n");
375 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_WRITEFUNCTION");
376 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEDATA, (void *)&body_buf), "CURLOPT_WRITEDATA");
377
378 /* initialize buffer for header of the answer */
379 if (curlhelp_initwritebuffer( &header_buf ) < 0)
380 die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for header\n" );
381 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HEADERFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_HEADERFUNCTION");
382 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEHEADER, (void *)&header_buf), "CURLOPT_WRITEHEADER");
383
384 /* set the error buffer */
385 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, errbuf), "CURLOPT_ERRORBUFFER");
386
387 /* set timeouts */
388 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, socket_timeout), "CURLOPT_CONNECTTIMEOUT");
389 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_TIMEOUT, socket_timeout), "CURLOPT_TIMEOUT");
390
391 // fill dns resolve cache to make curl connect to the given server_address instead of the host_name, only required for ssl, because we use the host_name later on to make SNI happy
392 if(use_ssl && host_name != NULL) {
393 struct curl_slist *host = NULL;
394 char dnscache[DEFAULT_BUFFER_SIZE];
395 snprintf (dnscache, DEFAULT_BUFFER_SIZE, "%s:%d:%s", host_name, server_port, server_address);
396 host = curl_slist_append(NULL, dnscache);
397 curl_easy_setopt(curl, CURLOPT_RESOLVE, host);
398 if (verbose>=1)
399 printf ("* curl CURLOPT_RESOLVE: %s\n", dnscache);
400 }
401
402 /* compose URL: use the address we want to connect to, set Host: header later */
403 snprintf (url, DEFAULT_BUFFER_SIZE, "%s://%s:%d%s",
404 use_ssl ? "https" : "http",
405 use_ssl & host_name != NULL ? host_name : server_address,
406 server_port,
407 server_url
408 );
409
410 if (verbose>=1)
411 printf ("* curl CURLOPT_URL: %s\n", url);
412 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, url), "CURLOPT_URL");
413
414 /* extract proxy information for legacy proxy https requests */
415 if (!strcmp(http_method, "CONNECT") || strstr(server_url, "http") == server_url) {
416 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXY, server_address), "CURLOPT_PROXY");
417 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXYPORT, (long)server_port), "CURLOPT_PROXYPORT");
418 if (verbose>=2)
419 printf ("* curl CURLOPT_PROXY: %s:%d\n", server_address, server_port);
420 http_method = "GET";
421 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, server_url), "CURLOPT_URL");
422 }
423
424 /* disable body for HEAD request */
425 if (http_method && !strcmp (http_method, "HEAD" )) {
426 no_body = TRUE;
427 }
428
429 /* set HTTP protocol version */
430 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HTTP_VERSION, curl_http_version), "CURLOPT_HTTP_VERSION");
431
432 /* set HTTP method */
433 if (http_method) {
434 if (!strcmp(http_method, "POST"))
435 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POST, 1), "CURLOPT_POST");
436 else if (!strcmp(http_method, "PUT"))
437 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_UPLOAD, 1), "CURLOPT_UPLOAD");
438 else
439 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CUSTOMREQUEST, http_method), "CURLOPT_CUSTOMREQUEST");
440 }
441
442 /* check if Host header is explicitly set in options */
443 if (http_opt_headers_count) {
444 for (i = 0; i < http_opt_headers_count ; i++) {
445 if (strncmp(http_opt_headers[i], "Host:", 5) == 0) {
446 force_host_header = http_opt_headers[i];
447 }
448 }
449 }
450
451 /* set hostname (virtual hosts), not needed if CURLOPT_CONNECT_TO is used, but left in anyway */
452 if(host_name != NULL && force_host_header == NULL) {
453 if((virtual_port != HTTP_PORT && !use_ssl) || (virtual_port != HTTPS_PORT && use_ssl)) {
454 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s:%d", host_name, virtual_port);
455 } else {
456 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s", host_name);
457 }
458 header_list = curl_slist_append (header_list, http_header);
459 }
460
461 /* always close connection, be nice to servers */
462 snprintf (http_header, DEFAULT_BUFFER_SIZE, "Connection: close");
463 header_list = curl_slist_append (header_list, http_header);
464
465 /* attach additional headers supplied by the user */
466 /* optionally send any other header tag */
467 if (http_opt_headers_count) {
468 for (i = 0; i < http_opt_headers_count ; i++) {
469 header_list = curl_slist_append (header_list, http_opt_headers[i]);
470 }
471 /* This cannot be free'd here because a redirection will then try to access this and segfault */
472 /* Covered in a testcase in tests/check_http.t */
473 /* free(http_opt_headers); */
474 }
475
476 /* set HTTP headers */
477 handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPHEADER, header_list ), "CURLOPT_HTTPHEADER");
478
479#ifdef LIBCURL_FEATURE_SSL
480
481 /* set SSL version, warn about unsecure or unsupported versions */
482 if (use_ssl) {
483 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLVERSION, ssl_version), "CURLOPT_SSLVERSION");
484 }
485
486 /* client certificate and key to present to server (SSL) */
487 if (client_cert)
488 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLCERT, client_cert), "CURLOPT_SSLCERT");
489 if (client_privkey)
490 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLKEY, client_privkey), "CURLOPT_SSLKEY");
491 if (ca_cert) {
492 /* per default if we have a CA verify both the peer and the
493 * hostname in the certificate, can be switched off later */
494 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO");
495 handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER");
496 handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST");
497 } else {
498 /* backward-compatible behaviour, be tolerant in checks
499 * TODO: depending on more options have aspects we want
500 * to be less tolerant about ssl verfications
501 */
502 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0), "CURLOPT_SSL_VERIFYPEER");
503 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0), "CURLOPT_SSL_VERIFYHOST");
504 }
505
506 /* detect SSL library used by libcurl */
507 ssl_library = curlhelp_get_ssl_library (curl);
508
509 /* try hard to get a stack of certificates to verify against */
510 if (check_cert) {
511#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1)
512 /* inform curl to report back certificates */
513 switch (ssl_library) {
514 case CURLHELP_SSL_LIBRARY_OPENSSL:
515 case CURLHELP_SSL_LIBRARY_LIBRESSL:
516 /* set callback to extract certificate with OpenSSL context function (works with
517 * OpenSSL-style libraries only!) */
518#ifdef USE_OPENSSL
519 /* libcurl and monitoring plugins built with OpenSSL, good */
520 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION");
521 is_openssl_callback = TRUE;
522#else /* USE_OPENSSL */
523#endif /* USE_OPENSSL */
524 /* libcurl is built with OpenSSL, monitoring plugins, so falling
525 * back to manually extracting certificate information */
526 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
527 break;
528
529 case CURLHELP_SSL_LIBRARY_NSS:
530#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
531 /* NSS: support for CERTINFO is implemented since 7.34.0 */
532 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
533#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
534 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));
535#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
536 break;
537
538 case CURLHELP_SSL_LIBRARY_GNUTLS:
539#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0)
540 /* GnuTLS: support for CERTINFO is implemented since 7.42.0 */
541 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
542#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */
543 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));
544#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */
545 break;
546
547 case CURLHELP_SSL_LIBRARY_UNKNOWN:
548 default:
549 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (unknown SSL library '%s', must implement first)\n", curlhelp_get_ssl_library_string (ssl_library));
550 break;
551 }
552#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */
553 /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */
554 if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL || ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL)
555 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION");
556 else
557 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");
558#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */
559 }
560
561#endif /* LIBCURL_FEATURE_SSL */
562
563 /* set default or user-given user agent identification */
564 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERAGENT, user_agent), "CURLOPT_USERAGENT");
565
566 /* proxy-authentication */
567 if (strcmp(proxy_auth, ""))
568 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXYUSERPWD, proxy_auth), "CURLOPT_PROXYUSERPWD");
569
570 /* authentication */
571 if (strcmp(user_auth, ""))
572 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERPWD, user_auth), "CURLOPT_USERPWD");
573
574 /* TODO: parameter auth method, bitfield of following methods:
575 * CURLAUTH_BASIC (default)
576 * CURLAUTH_DIGEST
577 * CURLAUTH_DIGEST_IE
578 * CURLAUTH_NEGOTIATE
579 * CURLAUTH_NTLM
580 * CURLAUTH_NTLM_WB
581 *
582 * convenience tokens for typical sets of methods:
583 * CURLAUTH_ANYSAFE: most secure, without BASIC
584 * or CURLAUTH_ANY: most secure, even BASIC if necessary
585 *
586 * handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST ), "CURLOPT_HTTPAUTH");
587 */
588
589 /* handle redirections */
590 if (onredirect == STATE_DEPENDENT) {
591 if( followmethod == FOLLOW_LIBCURL ) {
592 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1), "CURLOPT_FOLLOWLOCATION");
593
594 /* default -1 is infinite, not good, could lead to zombie plugins!
595 Setting it to one bigger than maximal limit to handle errors nicely below
596 */
597 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_MAXREDIRS, max_depth+1), "CURLOPT_MAXREDIRS");
598
599 /* for now allow only http and https (we are a http(s) check plugin in the end) */
600#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4)
601 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS), "CURLOPT_REDIRECT_PROTOCOLS");
602#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4) */
603
604 /* TODO: handle the following aspects of redirection, make them
605 * command line options too later:
606 CURLOPT_POSTREDIR: method switch
607 CURLINFO_REDIRECT_URL: custom redirect option
608 CURLOPT_REDIRECT_PROTOCOLS: allow people to step outside safe protocols
609 CURLINFO_REDIRECT_COUNT: get the number of redirects, print it, maybe a range option here is nice like for expected page size?
610 */
611 } else {
612 /* old style redirection is handled below */
613 }
614 }
615
616 /* no-body */
617 if (no_body)
618 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_NOBODY, 1), "CURLOPT_NOBODY");
619
620 /* IPv4 or IPv6 forced DNS resolution */
621 if (address_family == AF_UNSPEC)
622 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_WHATEVER)");
623 else if (address_family == AF_INET)
624 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V4)");
625#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6)
626 else if (address_family == AF_INET6)
627 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V6)");
628#endif
629
630 /* either send http POST data (any data, not only POST)*/
631 if (!strcmp(http_method, "POST") ||!strcmp(http_method, "PUT")) {
632 /* set content of payload for POST and PUT */
633 if (http_content_type) {
634 snprintf (http_header, DEFAULT_BUFFER_SIZE, "Content-Type: %s", http_content_type);
635 header_list = curl_slist_append (header_list, http_header);
636 }
637 /* NULL indicates "HTTP Continue" in libcurl, provide an empty string
638 * in case of no POST/PUT data */
639 if (!http_post_data)
640 http_post_data = "";
641 if (!strcmp(http_method, "POST")) {
642 /* POST method, set payload with CURLOPT_POSTFIELDS */
643 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POSTFIELDS, http_post_data), "CURLOPT_POSTFIELDS");
644 } else if (!strcmp(http_method, "PUT")) {
645 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READFUNCTION, (curl_read_callback)curlhelp_buffer_read_callback), "CURLOPT_READFUNCTION");
646 curlhelp_initreadbuffer (&put_buf, http_post_data, strlen (http_post_data));
647 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READDATA, (void *)&put_buf), "CURLOPT_READDATA");
648 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_INFILESIZE, (curl_off_t)strlen (http_post_data)), "CURLOPT_INFILESIZE");
649 }
650 }
651
652 /* do the request */
653 res = curl_easy_perform(curl);
654
655 if (verbose>=2 && http_post_data)
656 printf ("**** REQUEST CONTENT ****\n%s\n", http_post_data);
657
658 /* free header and server IP resolve lists, we don't need it anymore */
659 curl_slist_free_all (header_list); header_list = NULL;
660 curl_slist_free_all (server_ips); server_ips = NULL;
661
662 /* Curl errors, result in critical Nagios state */
663 if (res != CURLE_OK) {
664 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: cURL returned %d - %s"),
665 server_port, res, errbuf[0] ? errbuf : curl_easy_strerror(res));
666 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
667 }
668
669 /* certificate checks */
670#ifdef LIBCURL_FEATURE_SSL
671 if (use_ssl == TRUE) {
672 if (check_cert == TRUE) {
673 if (is_openssl_callback) {
674#ifdef USE_OPENSSL
675 /* check certificate with OpenSSL functions, curl has been built against OpenSSL
676 * and we actually have OpenSSL in the monitoring tools
677 */
678 result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit);
679 return result;
680#else /* USE_OPENSSL */
681 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL callback used and not linked against OpenSSL\n");
682#endif /* USE_OPENSSL */
683 } else {
684 int i;
685 struct curl_slist *slist;
686
687 cert_ptr.to_info = NULL;
688 res = curl_easy_getinfo (curl, CURLINFO_CERTINFO, &cert_ptr.to_info);
689 if (!res && cert_ptr.to_info) {
690#ifdef USE_OPENSSL
691 /* We have no OpenSSL in libcurl, but we can use OpenSSL for X509 cert parsing
692 * We only check the first certificate and assume it's the one of the server
693 */
694 const char* raw_cert = NULL;
695 for (i = 0; i < cert_ptr.to_certinfo->num_of_certs; i++) {
696 for (slist = cert_ptr.to_certinfo->certinfo[i]; slist; slist = slist->next) {
697 if (verbose >= 2)
698 printf ("%d ** %s\n", i, slist->data);
699 if (strncmp (slist->data, "Cert:", 5) == 0) {
700 raw_cert = &slist->data[5];
701 goto GOT_FIRST_CERT;
702 }
703 }
704 }
705GOT_FIRST_CERT:
706 if (!raw_cert) {
707 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates from CERTINFO information - certificate data was empty"));
708 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
709 }
710 BIO* cert_BIO = BIO_new (BIO_s_mem());
711 BIO_write (cert_BIO, raw_cert, strlen(raw_cert));
712 cert = PEM_read_bio_X509 (cert_BIO, NULL, NULL, NULL);
713 if (!cert) {
714 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot read certificate from CERTINFO information - BIO error"));
715 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
716 }
717 BIO_free (cert_BIO);
718 result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit);
719 return result;
720#else /* USE_OPENSSL */
721 /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our disposal,
722 * so we use the libcurl CURLINFO data
723 */
724 result = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit);
725 return result;
726#endif /* USE_OPENSSL */
727 } else {
728 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates - cURL returned %d - %s"),
729 res, curl_easy_strerror(res));
730 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
731 }
732 }
733 }
734 }
735#endif /* LIBCURL_FEATURE_SSL */
736
737 /* we got the data and we executed the request in a given time, so we can append
738 * performance data to the answer always
739 */
740 handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_TOTAL_TIME, &total_time), "CURLINFO_TOTAL_TIME");
741 page_len = get_content_length(&header_buf, &body_buf);
742 if(show_extended_perfdata) {
743 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &time_connect), "CURLINFO_CONNECT_TIME");
744 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &time_appconnect), "CURLINFO_APPCONNECT_TIME");
745 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &time_headers), "CURLINFO_PRETRANSFER_TIME");
746 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &time_firstbyte), "CURLINFO_STARTTRANSFER_TIME");
747 snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s %s %s %s %s %s",
748 perfd_time(total_time),
749 perfd_size(page_len),
750 perfd_time_connect(time_connect),
751 use_ssl == TRUE ? perfd_time_ssl (time_appconnect-time_connect) : "",
752 perfd_time_headers(time_headers - time_appconnect),
753 perfd_time_firstbyte(time_firstbyte - time_headers),
754 perfd_time_transfer(total_time-time_firstbyte)
755 );
756 } else {
757 snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s",
758 perfd_time(total_time),
759 perfd_size(page_len)
760 );
761 }
762
763 /* return a CRITICAL status if we couldn't read any data */
764 if (strlen(header_buf.buf) == 0 && strlen(body_buf.buf) == 0)
765 die (STATE_CRITICAL, _("HTTP CRITICAL - No header received from host\n"));
766
767 /* get status line of answer, check sanity of HTTP code */
768 if (curlhelp_parse_statusline (header_buf.buf, &status_line) < 0) {
769 snprintf (msg, DEFAULT_BUFFER_SIZE, "Unparsable status line in %.3g seconds response time|%s\n",
770 total_time, perfstring);
771 /* we cannot know the major/minor version here for sure as we cannot parse the first line */
772 die (STATE_CRITICAL, "HTTP CRITICAL HTTP/x.x %ld unknown - %s", code, msg);
773 }
774
775 /* get result code from cURL */
776 handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE");
777 if (verbose>=2)
778 printf ("* curl CURLINFO_RESPONSE_CODE is %ld\n", code);
779
780 /* print status line, header, body if verbose */
781 if (verbose >= 2) {
782 printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header_buf.buf,
783 (no_body ? " [[ skipped ]]" : body_buf.buf));
784 }
785
786 /* make sure the status line matches the response we are looking for */
787 if (!expected_statuscode(status_line.first_line, server_expect)) {
788 if (server_port == HTTP_PORT)
789 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host: %s\n"), status_line.first_line);
790 else
791 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: %s\n"), server_port, status_line.first_line);
792 die (STATE_CRITICAL, "HTTP CRITICAL - %s", msg);
793 }
794
795 if( server_expect_yn ) {
796 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Status line output matched \"%s\" - "), server_expect);
797 if (verbose)
798 printf ("%s\n",msg);
799 result = STATE_OK;
800 }
801 else {
802 /* illegal return codes result in a critical state */
803 if (code >= 600 || code < 100) {
804 die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%d, %.40s)\n"), status_line.http_code, status_line.msg);
805 /* server errors result in a critical state */
806 } else if (code >= 500) {
807 result = STATE_CRITICAL;
808 /* client errors result in a warning state */
809 } else if (code >= 400) {
810 result = STATE_WARNING;
811 /* check redirected page if specified */
812 } else if (code >= 300) {
813 if (onredirect == STATE_DEPENDENT) {
814 if( followmethod == FOLLOW_LIBCURL ) {
815 code = status_line.http_code;
816 } else {
817 /* old check_http style redirection, if we come
818 * back here, we are in the same status as with
819 * the libcurl method
820 */
821 redir (&header_buf);
822 }
823 } else {
824 /* this is a specific code in the command line to
825 * be returned when a redirection is encoutered
826 */
827 }
828 result = max_state_alt (onredirect, result);
829 /* all other codes are considered ok */
830 } else {
831 result = STATE_OK;
832 }
833 }
834
835 /* libcurl redirection internally, handle error states here */
836 if( followmethod == FOLLOW_LIBCURL ) {
837 handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_REDIRECT_COUNT, &redir_depth), "CURLINFO_REDIRECT_COUNT");
838 if (verbose >= 2)
839 printf(_("* curl LIBINFO_REDIRECT_COUNT is %d\n"), redir_depth);
840 if (redir_depth > max_depth) {
841 snprintf (msg, DEFAULT_BUFFER_SIZE, "maximum redirection depth %d exceeded in libcurl",
842 max_depth);
843 die (STATE_WARNING, "HTTP WARNING - %s", msg);
844 }
845 }
846
847 /* check status codes, set exit status accordingly */
848 if( status_line.http_code != code ) {
849 die (STATE_CRITICAL, _("HTTP CRITICAL %s %d %s - different HTTP codes (cUrl has %ld)\n"),
850 string_statuscode (status_line.http_major, status_line.http_minor),
851 status_line.http_code, status_line.msg, code);
852 }
853
854 if (maximum_age >= 0) {
855 result = max_state_alt(check_document_dates(&header_buf, &msg), result);
856 }
857
858 /* Page and Header content checks go here */
859
860 if (strlen (header_expect)) {
861 if (!strstr (header_buf.buf, header_expect)) {
862 strncpy(&output_header_search[0],header_expect,sizeof(output_header_search));
863 if(output_header_search[sizeof(output_header_search)-1]!='\0') {
864 bcopy("...",&output_header_search[sizeof(output_header_search)-4],4);
865 }
866 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);
867 result = STATE_CRITICAL;
868 }
869 }
870
871 if (strlen (string_expect)) {
872 if (!strstr (body_buf.buf, string_expect)) {
873 strncpy(&output_string_search[0],string_expect,sizeof(output_string_search));
874 if(output_string_search[sizeof(output_string_search)-1]!='\0') {
875 bcopy("...",&output_string_search[sizeof(output_string_search)-4],4);
876 }
877 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);
878 result = STATE_CRITICAL;
879 }
880 }
881
882 if (strlen (regexp)) {
883 errcode = regexec (&preg, body_buf.buf, REGS, pmatch, 0);
884 if ((errcode == 0 && invert_regex == 0) || (errcode == REG_NOMATCH && invert_regex == 1)) {
885 /* OK - No-op to avoid changing the logic around it */
886 result = max_state_alt(STATE_OK, result);
887 }
888 else if ((errcode == REG_NOMATCH && invert_regex == 0) || (errcode == 0 && invert_regex == 1)) {
889 if (invert_regex == 0)
890 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spattern not found, "), msg);
891 else
892 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spattern found, "), msg);
893 result = STATE_CRITICAL;
894 }
895 else {
896 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
897 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%sExecute Error: %s, "), msg, errbuf);
898 result = STATE_UNKNOWN;
899 }
900 }
901
902 /* make sure the page is of an appropriate size */
903 if ((max_page_len > 0) && (page_len > max_page_len)) {
904 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spage size %d too large, "), msg, page_len);
905 result = max_state_alt(STATE_WARNING, result);
906 } else if ((min_page_len > 0) && (page_len < min_page_len)) {
907 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spage size %d too small, "), msg, page_len);
908 result = max_state_alt(STATE_WARNING, result);
909 }
910
911 /* -w, -c: check warning and critical level */
912 result = max_state_alt(get_status(total_time, thlds), result);
913
914 /* Cut-off trailing characters */
915 if(msg[strlen(msg)-2] == ',')
916 msg[strlen(msg)-2] = '\0';
917 else
918 msg[strlen(msg)-3] = '\0';
919
920 /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */
921 die (result, "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n",
922 state_text(result), string_statuscode (status_line.http_major, status_line.http_minor),
923 status_line.http_code, status_line.msg,
924 strlen(msg) > 0 ? " - " : "",
925 msg, page_len, total_time,
926 (display_html ? "</A>" : ""),
927 perfstring);
928
929 /* proper cleanup after die? */
930 curlhelp_free_statusline(&status_line);
931 curl_easy_cleanup (curl);
932 curl_global_cleanup ();
933 curlhelp_freewritebuffer (&body_buf);
934 curlhelp_freewritebuffer (&header_buf);
935 if (!strcmp (http_method, "PUT")) {
936 curlhelp_freereadbuffer (&put_buf);
937 }
938
939 return result;
940}
941
942int
943uri_strcmp (const UriTextRangeA range, const char* s)
944{
945 if (!range.first) return -1;
946 if (range.afterLast - range.first < strlen (s)) return -1;
947 return strncmp (s, range.first, min( range.afterLast - range.first, strlen (s)));
948}
949
950char*
951uri_string (const UriTextRangeA range, char* buf, size_t buflen)
952{
953 if (!range.first) return "(null)";
954 strncpy (buf, range.first, max (buflen, range.afterLast - range.first));
955 buf[max (buflen, range.afterLast - range.first)] = '\0';
956 buf[range.afterLast - range.first] = '\0';
957 return buf;
958}
959
960void
961redir (curlhelp_write_curlbuf* header_buf)
962{
963 char *location = NULL;
964 curlhelp_statusline status_line;
965 struct phr_header headers[255];
966 size_t nof_headers = 255;
967 size_t msglen;
968 char buf[DEFAULT_BUFFER_SIZE];
969 char ipstr[INET_ADDR_MAX_SIZE];
970 int new_port;
971 char *new_host;
972 char *new_url;
973
974 int res = phr_parse_response (header_buf->buf, header_buf->buflen,
975 &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen,
976 headers, &nof_headers, 0);
977
978 location = get_header_value (headers, nof_headers, "location");
979
980 if (verbose >= 2)
981 printf(_("* Seen redirect location %s\n"), location);
982
983 if (++redir_depth > max_depth)
984 die (STATE_WARNING,
985 _("HTTP WARNING - maximum redirection depth %d exceeded - %s%s\n"),
986 max_depth, location, (display_html ? "</A>" : ""));
987
988 UriParserStateA state;
989 UriUriA uri;
990 state.uri = &uri;
991 if (uriParseUriA (&state, location) != URI_SUCCESS) {
992 if (state.errorCode == URI_ERROR_SYNTAX) {
993 die (STATE_UNKNOWN,
994 _("HTTP UNKNOWN - Could not parse redirect location '%s'%s\n"),
995 location, (display_html ? "</A>" : ""));
996 } else if (state.errorCode == URI_ERROR_MALLOC) {
997 die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n"));
998 }
999 }
1000
1001 if (verbose >= 2) {
1002 printf (_("** scheme: %s\n"),
1003 uri_string (uri.scheme, buf, DEFAULT_BUFFER_SIZE));
1004 printf (_("** host: %s\n"),
1005 uri_string (uri.hostText, buf, DEFAULT_BUFFER_SIZE));
1006 printf (_("** port: %s\n"),
1007 uri_string (uri.portText, buf, DEFAULT_BUFFER_SIZE));
1008 if (uri.hostData.ip4) {
1009 inet_ntop (AF_INET, uri.hostData.ip4->data, ipstr, sizeof (ipstr));
1010 printf (_("** IPv4: %s\n"), ipstr);
1011 }
1012 if (uri.hostData.ip6) {
1013 inet_ntop (AF_INET, uri.hostData.ip6->data, ipstr, sizeof (ipstr));
1014 printf (_("** IPv6: %s\n"), ipstr);
1015 }
1016 if (uri.pathHead) {
1017 printf (_("** path: "));
1018 const UriPathSegmentA* p = uri.pathHead;
1019 for (; p; p = p->next) {
1020 printf ("/%s", uri_string (p->text, buf, DEFAULT_BUFFER_SIZE));
1021 }
1022 puts ("");
1023 }
1024 if (uri.query.first) {
1025 printf (_("** query: %s\n"),
1026 uri_string (uri.query, buf, DEFAULT_BUFFER_SIZE));
1027 }
1028 if (uri.fragment.first) {
1029 printf (_("** fragment: %s\n"),
1030 uri_string (uri.fragment, buf, DEFAULT_BUFFER_SIZE));
1031 }
1032 }
1033
1034 use_ssl = !uri_strcmp (uri.scheme, "https");
1035
1036 /* we do a sloppy test here only, because uriparser would have failed
1037 * above, if the port would be invalid, we just check for MAX_PORT
1038 */
1039 if (uri.portText.first) {
1040 new_port = atoi (uri_string (uri.portText, buf, DEFAULT_BUFFER_SIZE));
1041 } else {
1042 new_port = HTTP_PORT;
1043 if (use_ssl)
1044 new_port = HTTPS_PORT;
1045 }
1046 if (new_port > MAX_PORT)
1047 die (STATE_UNKNOWN,
1048 _("HTTP UNKNOWN - Redirection to port above %d - %s%s\n"),
1049 MAX_PORT, location, display_html ? "</A>" : "");
1050
1051 /* by RFC 7231 relative URLs in Location should be taken relative to
1052 * the original URL, so wy try to form a new absolute URL here
1053 */
1054 if (!uri.scheme.first && !uri.hostText.first) {
1055 new_host = strdup (host_name ? host_name : server_address);
1056 } else {
1057 new_host = strdup (uri_string (uri.hostText, buf, DEFAULT_BUFFER_SIZE));
1058 }
1059
1060 /* compose new path */
1061 /* TODO: handle fragments and query part of URL */
1062 new_url = (char *)calloc( 1, DEFAULT_BUFFER_SIZE);
1063 if (uri.pathHead) {
1064 const UriPathSegmentA* p = uri.pathHead;
1065 for (; p; p = p->next) {
1066 strncat (new_url, "/", DEFAULT_BUFFER_SIZE);
1067 strncat (new_url, uri_string (p->text, buf, DEFAULT_BUFFER_SIZE), DEFAULT_BUFFER_SIZE-1);
1068 }
1069 }
1070
1071 if (server_port==new_port &&
1072 !strncmp(server_address, new_host, MAX_IPV4_HOSTLENGTH) &&
1073 (host_name && !strncmp(host_name, new_host, MAX_IPV4_HOSTLENGTH)) &&
1074 !strcmp(server_url, new_url))
1075 die (STATE_WARNING,
1076 _("HTTP WARNING - redirection creates an infinite loop - %s://%s:%d%s%s\n"),
1077 use_ssl ? "https" : "http", new_host, new_port, new_url, (display_html ? "</A>" : ""));
1078
1079 /* set new values for redirected request */
1080
1081 if (!(followsticky & STICKY_HOST)) {
1082 free (server_address);
1083 server_address = strndup (new_host, MAX_IPV4_HOSTLENGTH);
1084 }
1085 if (!(followsticky & STICKY_PORT)) {
1086 server_port = (unsigned short)new_port;
1087 }
1088
1089 free (host_name);
1090 host_name = strndup (new_host, MAX_IPV4_HOSTLENGTH);
1091
1092 /* reset virtual port */
1093 virtual_port = server_port;
1094
1095 free(new_host);
1096 free (server_url);
1097 server_url = new_url;
1098
1099 uriFreeUriMembersA (&uri);
1100
1101 if (verbose)
1102 printf (_("Redirection to %s://%s:%d%s\n"), use_ssl ? "https" : "http",
1103 host_name ? host_name : server_address, server_port, server_url);
1104
1105 /* TODO: the hash component MUST be taken from the original URL and
1106 * attached to the URL in Location
1107 */
1108
1109 check_http ();
1110}
1111
1112/* check whether a file exists */
1113void
1114test_file (char *path)
1115{
1116 if (access(path, R_OK) == 0)
1117 return;
1118 usage2 (_("file does not exist or is not readable"), path);
1119}
1120
1121int
1122process_arguments (int argc, char **argv)
1123{
1124 char *p;
1125 int c = 1;
1126 char *temp;
1127
1128 enum {
1129 INVERT_REGEX = CHAR_MAX + 1,
1130 SNI_OPTION,
1131 CA_CERT_OPTION,
1132 HTTP_VERSION_OPTION
1133 };
1134
1135 int option = 0;
1136 int got_plus = 0;
1137 static struct option longopts[] = {
1138 STD_LONG_OPTS,
1139 {"link", no_argument, 0, 'L'},
1140 {"nohtml", no_argument, 0, 'n'},
1141 {"ssl", optional_argument, 0, 'S'},
1142 {"sni", no_argument, 0, SNI_OPTION},
1143 {"post", required_argument, 0, 'P'},
1144 {"method", required_argument, 0, 'j'},
1145 {"IP-address", required_argument, 0, 'I'},
1146 {"url", required_argument, 0, 'u'},
1147 {"port", required_argument, 0, 'p'},
1148 {"authorization", required_argument, 0, 'a'},
1149 {"proxy-authorization", required_argument, 0, 'b'},
1150 {"header-string", required_argument, 0, 'd'},
1151 {"string", required_argument, 0, 's'},
1152 {"expect", required_argument, 0, 'e'},
1153 {"regex", required_argument, 0, 'r'},
1154 {"ereg", required_argument, 0, 'r'},
1155 {"eregi", required_argument, 0, 'R'},
1156 {"linespan", no_argument, 0, 'l'},
1157 {"onredirect", required_argument, 0, 'f'},
1158 {"certificate", required_argument, 0, 'C'},
1159 {"client-cert", required_argument, 0, 'J'},
1160 {"private-key", required_argument, 0, 'K'},
1161 {"ca-cert", required_argument, 0, CA_CERT_OPTION},
1162 {"useragent", required_argument, 0, 'A'},
1163 {"header", required_argument, 0, 'k'},
1164 {"no-body", no_argument, 0, 'N'},
1165 {"max-age", required_argument, 0, 'M'},
1166 {"content-type", required_argument, 0, 'T'},
1167 {"pagesize", required_argument, 0, 'm'},
1168 {"invert-regex", no_argument, NULL, INVERT_REGEX},
1169 {"use-ipv4", no_argument, 0, '4'},
1170 {"use-ipv6", no_argument, 0, '6'},
1171 {"extended-perfdata", no_argument, 0, 'E'},
1172 {"http-version", required_argument, 0, HTTP_VERSION_OPTION},
1173 {0, 0, 0, 0}
1174 };
1175
1176 if (argc < 2)
1177 return ERROR;
1178
1179 /* support check_http compatible arguments */
1180 for (c = 1; c < argc; c++) {
1181 if (strcmp ("-to", argv[c]) == 0)
1182 strcpy (argv[c], "-t");
1183 if (strcmp ("-hn", argv[c]) == 0)
1184 strcpy (argv[c], "-H");
1185 if (strcmp ("-wt", argv[c]) == 0)
1186 strcpy (argv[c], "-w");
1187 if (strcmp ("-ct", argv[c]) == 0)
1188 strcpy (argv[c], "-c");
1189 if (strcmp ("-nohtml", argv[c]) == 0)
1190 strcpy (argv[c], "-n");
1191 }
1192
1193 server_url = strdup(DEFAULT_SERVER_URL);
1194
1195 while (1) {
1196 c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:nlLS::m:M:NE", longopts, &option);
1197 if (c == -1 || c == EOF || c == 1)
1198 break;
1199
1200 switch (c) {
1201 case 'h':
1202 print_help();
1203 exit(STATE_UNKNOWN);
1204 break;
1205 case 'V':
1206 print_revision(progname, NP_VERSION);
1207 print_curl_version();
1208 exit(STATE_UNKNOWN);
1209 break;
1210 case 'v':
1211 verbose++;
1212 break;
1213 case 't': /* timeout period */
1214 if (!is_intnonneg (optarg))
1215 usage2 (_("Timeout interval must be a positive integer"), optarg);
1216 else
1217 socket_timeout = (int)strtol (optarg, NULL, 10);
1218 break;
1219 case 'c': /* critical time threshold */
1220 critical_thresholds = optarg;
1221 break;
1222 case 'w': /* warning time threshold */
1223 warning_thresholds = optarg;
1224 break;
1225 case 'H': /* virtual host */
1226 host_name = strdup (optarg);
1227 if (host_name[0] == '[') {
1228 if ((p = strstr (host_name, "]:")) != NULL) { /* [IPv6]:port */
1229 virtual_port = atoi (p + 2);
1230 /* cut off the port */
1231 host_name_length = strlen (host_name) - strlen (p) - 1;
1232 free (host_name);
1233 host_name = strndup (optarg, host_name_length);
1234 }
1235 } else if ((p = strchr (host_name, ':')) != NULL
1236 && strchr (++p, ':') == NULL) { /* IPv4:port or host:port */
1237 virtual_port = atoi (p);
1238 /* cut off the port */
1239 host_name_length = strlen (host_name) - strlen (p) - 1;
1240 free (host_name);
1241 host_name = strndup (optarg, host_name_length);
1242 }
1243 break;
1244 case 'I': /* internet address */
1245 server_address = strdup (optarg);
1246 break;
1247 case 'u': /* URL path */
1248 server_url = strdup (optarg);
1249 break;
1250 case 'p': /* Server port */
1251 if (!is_intnonneg (optarg))
1252 usage2 (_("Invalid port number, expecting a non-negative number"), optarg);
1253 else {
1254 if( strtol(optarg, NULL, 10) > MAX_PORT)
1255 usage2 (_("Invalid port number, supplied port number is too big"), optarg);
1256 server_port = (unsigned short)strtol(optarg, NULL, 10);
1257 specify_port = TRUE;
1258 }
1259 break;
1260 case 'a': /* authorization info */
1261 strncpy (user_auth, optarg, MAX_INPUT_BUFFER - 1);
1262 user_auth[MAX_INPUT_BUFFER - 1] = 0;
1263 break;
1264 case 'b': /* proxy-authorization info */
1265 strncpy (proxy_auth, optarg, MAX_INPUT_BUFFER - 1);
1266 proxy_auth[MAX_INPUT_BUFFER - 1] = 0;
1267 break;
1268 case 'P': /* HTTP POST data in URL encoded format; ignored if settings already */
1269 if (! http_post_data)
1270 http_post_data = strdup (optarg);
1271 if (! http_method)
1272 http_method = strdup("POST");
1273 break;
1274 case 'j': /* Set HTTP method */
1275 if (http_method)
1276 free(http_method);
1277 http_method = strdup (optarg);
1278 break;
1279 case 'A': /* useragent */
1280 strncpy (user_agent, optarg, DEFAULT_BUFFER_SIZE);
1281 user_agent[DEFAULT_BUFFER_SIZE-1] = '\0';
1282 break;
1283 case 'k': /* Additional headers */
1284 if (http_opt_headers_count == 0)
1285 http_opt_headers = malloc (sizeof (char *) * (++http_opt_headers_count));
1286 else
1287 http_opt_headers = realloc (http_opt_headers, sizeof (char *) * (++http_opt_headers_count));
1288 http_opt_headers[http_opt_headers_count - 1] = optarg;
1289 break;
1290 case 'L': /* show html link */
1291 display_html = TRUE;
1292 break;
1293 case 'n': /* do not show html link */
1294 display_html = FALSE;
1295 break;
1296 case 'C': /* Check SSL cert validity */
1297#ifdef LIBCURL_FEATURE_SSL
1298 if ((temp=strchr(optarg,','))!=NULL) {
1299 *temp='\0';
1300 if (!is_intnonneg (optarg))
1301 usage2 (_("Invalid certificate expiration period"), optarg);
1302 days_till_exp_warn = atoi(optarg);
1303 *temp=',';
1304 temp++;
1305 if (!is_intnonneg (temp))
1306 usage2 (_("Invalid certificate expiration period"), temp);
1307 days_till_exp_crit = atoi (temp);
1308 }
1309 else {
1310 days_till_exp_crit=0;
1311 if (!is_intnonneg (optarg))
1312 usage2 (_("Invalid certificate expiration period"), optarg);
1313 days_till_exp_warn = atoi (optarg);
1314 }
1315 check_cert = TRUE;
1316 goto enable_ssl;
1317#endif
1318 case 'J': /* use client certificate */
1319#ifdef LIBCURL_FEATURE_SSL
1320 test_file(optarg);
1321 client_cert = optarg;
1322 goto enable_ssl;
1323#endif
1324 case 'K': /* use client private key */
1325#ifdef LIBCURL_FEATURE_SSL
1326 test_file(optarg);
1327 client_privkey = optarg;
1328 goto enable_ssl;
1329#endif
1330#ifdef LIBCURL_FEATURE_SSL
1331 case CA_CERT_OPTION: /* use CA chain file */
1332 test_file(optarg);
1333 ca_cert = optarg;
1334 goto enable_ssl;
1335#endif
1336 case 'S': /* use SSL */
1337#ifdef LIBCURL_FEATURE_SSL
1338 enable_ssl:
1339 use_ssl = TRUE;
1340 /* ssl_version initialized to CURL_SSLVERSION_DEFAULT as a default.
1341 * Only set if it's non-zero. This helps when we include multiple
1342 * parameters, like -S and -C combinations */
1343 ssl_version = CURL_SSLVERSION_DEFAULT;
1344 if (c=='S' && optarg != NULL) {
1345 char *plus_ptr = strchr(optarg, '+');
1346 if (plus_ptr) {
1347 got_plus = 1;
1348 *plus_ptr = '\0';
1349 }
1350
1351 if (optarg[0] == '2')
1352 ssl_version = CURL_SSLVERSION_SSLv2;
1353 else if (optarg[0] == '3')
1354 ssl_version = CURL_SSLVERSION_SSLv3;
1355 else if (!strcmp (optarg, "1") || !strcmp (optarg, "1.0"))
1356#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1357 ssl_version = CURL_SSLVERSION_TLSv1_0;
1358#else
1359 ssl_version = CURL_SSLVERSION_DEFAULT;
1360#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1361 else if (!strcmp (optarg, "1.1"))
1362#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1363 ssl_version = CURL_SSLVERSION_TLSv1_1;
1364#else
1365 ssl_version = CURL_SSLVERSION_DEFAULT;
1366#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1367 else if (!strcmp (optarg, "1.2"))
1368#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1369 ssl_version = CURL_SSLVERSION_TLSv1_2;
1370#else
1371 ssl_version = CURL_SSLVERSION_DEFAULT;
1372#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1373 else if (!strcmp (optarg, "1.3"))
1374#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0)
1375 ssl_version = CURL_SSLVERSION_TLSv1_3;
1376#else
1377 ssl_version = CURL_SSLVERSION_DEFAULT;
1378#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) */
1379 else
1380 usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2, 1.3 (with optional '+' suffix)"));
1381 }
1382#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0)
1383 if (got_plus) {
1384 switch (ssl_version) {
1385 case CURL_SSLVERSION_TLSv1_3:
1386 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3;
1387 break;
1388 case CURL_SSLVERSION_TLSv1_2:
1389 case CURL_SSLVERSION_TLSv1_1:
1390 case CURL_SSLVERSION_TLSv1_0:
1391 ssl_version |= CURL_SSLVERSION_MAX_DEFAULT;
1392 break;
1393 }
1394 } else {
1395 switch (ssl_version) {
1396 case CURL_SSLVERSION_TLSv1_3:
1397 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3;
1398 break;
1399 case CURL_SSLVERSION_TLSv1_2:
1400 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_2;
1401 break;
1402 case CURL_SSLVERSION_TLSv1_1:
1403 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_1;
1404 break;
1405 case CURL_SSLVERSION_TLSv1_0:
1406 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_0;
1407 break;
1408 }
1409 }
1410#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) */
1411 if (verbose >= 2)
1412 printf(_("* Set SSL/TLS version to %d\n"), ssl_version);
1413 if (specify_port == FALSE)
1414 server_port = HTTPS_PORT;
1415 break;
1416#else /* LIBCURL_FEATURE_SSL */
1417 /* -C -J and -K fall through to here without SSL */
1418 usage4 (_("Invalid option - SSL is not available"));
1419 break;
1420 case SNI_OPTION: /* --sni is parsed, but ignored, the default is TRUE with libcurl */
1421 use_sni = TRUE;
1422 break;
1423#endif /* LIBCURL_FEATURE_SSL */
1424 case 'f': /* onredirect */
1425 if (!strcmp (optarg, "ok"))
1426 onredirect = STATE_OK;
1427 else if (!strcmp (optarg, "warning"))
1428 onredirect = STATE_WARNING;
1429 else if (!strcmp (optarg, "critical"))
1430 onredirect = STATE_CRITICAL;
1431 else if (!strcmp (optarg, "unknown"))
1432 onredirect = STATE_UNKNOWN;
1433 else if (!strcmp (optarg, "follow"))
1434 onredirect = STATE_DEPENDENT;
1435 else if (!strcmp (optarg, "stickyport"))
1436 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST|STICKY_PORT;
1437 else if (!strcmp (optarg, "sticky"))
1438 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST;
1439 else if (!strcmp (optarg, "follow"))
1440 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_NONE;
1441 else if (!strcmp (optarg, "curl"))
1442 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_LIBCURL;
1443 else usage2 (_("Invalid onredirect option"), optarg);
1444 if (verbose >= 2)
1445 printf(_("* Following redirects set to %s\n"), state_text(onredirect));
1446 break;
1447 case 'd': /* string or substring */
1448 strncpy (header_expect, optarg, MAX_INPUT_BUFFER - 1);
1449 header_expect[MAX_INPUT_BUFFER - 1] = 0;
1450 break;
1451 case 's': /* string or substring */
1452 strncpy (string_expect, optarg, MAX_INPUT_BUFFER - 1);
1453 string_expect[MAX_INPUT_BUFFER - 1] = 0;
1454 break;
1455 case 'e': /* string or substring */
1456 strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1);
1457 server_expect[MAX_INPUT_BUFFER - 1] = 0;
1458 server_expect_yn = 1;
1459 break;
1460 case 'T': /* Content-type */
1461 http_content_type = strdup (optarg);
1462 break;
1463 case 'l': /* linespan */
1464 cflags &= ~REG_NEWLINE;
1465 break;
1466 case 'R': /* regex */
1467 cflags |= REG_ICASE;
1468 case 'r': /* regex */
1469 strncpy (regexp, optarg, MAX_RE_SIZE - 1);
1470 regexp[MAX_RE_SIZE - 1] = 0;
1471 errcode = regcomp (&preg, regexp, cflags);
1472 if (errcode != 0) {
1473 (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
1474 printf (_("Could Not Compile Regular Expression: %s"), errbuf);
1475 return ERROR;
1476 }
1477 break;
1478 case INVERT_REGEX:
1479 invert_regex = 1;
1480 break;
1481 case '4':
1482 address_family = AF_INET;
1483 break;
1484 case '6':
1485#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6)
1486 address_family = AF_INET6;
1487#else
1488 usage4 (_("IPv6 support not available"));
1489#endif
1490 break;
1491 case 'm': /* min_page_length */
1492 {
1493 char *tmp;
1494 if (strchr(optarg, ':') != (char *)NULL) {
1495 /* range, so get two values, min:max */
1496 tmp = strtok(optarg, ":");
1497 if (tmp == NULL) {
1498 printf("Bad format: try \"-m min:max\"\n");
1499 exit (STATE_WARNING);
1500 } else
1501 min_page_len = atoi(tmp);
1502
1503 tmp = strtok(NULL, ":");
1504 if (tmp == NULL) {
1505 printf("Bad format: try \"-m min:max\"\n");
1506 exit (STATE_WARNING);
1507 } else
1508 max_page_len = atoi(tmp);
1509 } else
1510 min_page_len = atoi (optarg);
1511 break;
1512 }
1513 case 'N': /* no-body */
1514 no_body = TRUE;
1515 break;
1516 case 'M': /* max-age */
1517 {
1518 int L = strlen(optarg);
1519 if (L && optarg[L-1] == 'm')
1520 maximum_age = atoi (optarg) * 60;
1521 else if (L && optarg[L-1] == 'h')
1522 maximum_age = atoi (optarg) * 60 * 60;
1523 else if (L && optarg[L-1] == 'd')
1524 maximum_age = atoi (optarg) * 60 * 60 * 24;
1525 else if (L && (optarg[L-1] == 's' ||
1526 isdigit (optarg[L-1])))
1527 maximum_age = atoi (optarg);
1528 else {
1529 fprintf (stderr, "unparsable max-age: %s\n", optarg);
1530 exit (STATE_WARNING);
1531 }
1532 if (verbose >= 2)
1533 printf ("* Maximal age of document set to %d seconds\n", maximum_age);
1534 }
1535 break;
1536 case 'E': /* show extended perfdata */
1537 show_extended_perfdata = TRUE;
1538 break;
1539 case HTTP_VERSION_OPTION:
1540 curl_http_version = CURL_HTTP_VERSION_NONE;
1541 if (strcmp (optarg, "1.0") == 0) {
1542 curl_http_version = CURL_HTTP_VERSION_1_0;
1543 } else if (strcmp (optarg, "1.1") == 0) {
1544 curl_http_version = CURL_HTTP_VERSION_1_1;
1545 } else if ((strcmp (optarg, "2.0") == 0) || (strcmp (optarg, "2") == 0)) {
1546#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0)
1547 curl_http_version = CURL_HTTP_VERSION_2_0;
1548#else
1549 curl_http_version = CURL_HTTP_VERSION_NONE;
1550#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0) */
1551 } else {
1552 fprintf (stderr, "unkown http-version parameter: %s\n", optarg);
1553 exit (STATE_WARNING);
1554 }
1555 break;
1556 case '?':
1557 /* print short usage statement if args not parsable */
1558 usage5 ();
1559 break;
1560 }
1561 }
1562
1563 c = optind;
1564
1565 if (server_address == NULL && c < argc)
1566 server_address = strdup (argv[c++]);
1567
1568 if (host_name == NULL && c < argc)
1569 host_name = strdup (argv[c++]);
1570
1571 if (server_address == NULL) {
1572 if (host_name == NULL)
1573 usage4 (_("You must specify a server address or host name"));
1574 else
1575 server_address = strdup (host_name);
1576 }
1577
1578 set_thresholds(&thlds, warning_thresholds, critical_thresholds);
1579
1580 if (critical_thresholds && thlds->critical->end>(double)socket_timeout)
1581 socket_timeout = (int)thlds->critical->end + 1;
1582 if (verbose >= 2)
1583 printf ("* Socket timeout set to %ld seconds\n", socket_timeout);
1584
1585 if (http_method == NULL)
1586 http_method = strdup ("GET");
1587
1588 if (client_cert && !client_privkey)
1589 usage4 (_("If you use a client certificate you must also specify a private key file"));
1590
1591 if (virtual_port == 0)
1592 virtual_port = server_port;
1593 else {
1594 if ((use_ssl && server_port == HTTPS_PORT) || (!use_ssl && server_port == HTTP_PORT))
1595 if(specify_port == FALSE)
1596 server_port = virtual_port;
1597 }
1598
1599 return TRUE;
1600}
1601
1602char *perfd_time (double elapsed_time)
1603{
1604 return fperfdata ("time", elapsed_time, "s",
1605 thlds->warning?TRUE:FALSE, thlds->warning?thlds->warning->end:0,
1606 thlds->critical?TRUE:FALSE, thlds->critical?thlds->critical->end:0,
1607 TRUE, 0, TRUE, socket_timeout);
1608}
1609
1610char *perfd_time_connect (double elapsed_time_connect)
1611{
1612 return fperfdata ("time_connect", elapsed_time_connect, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1613}
1614
1615char *perfd_time_ssl (double elapsed_time_ssl)
1616{
1617 return fperfdata ("time_ssl", elapsed_time_ssl, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1618}
1619
1620char *perfd_time_headers (double elapsed_time_headers)
1621{
1622 return fperfdata ("time_headers", elapsed_time_headers, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1623}
1624
1625char *perfd_time_firstbyte (double elapsed_time_firstbyte)
1626{
1627 return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1628}
1629
1630char *perfd_time_transfer (double elapsed_time_transfer)
1631{
1632 return fperfdata ("time_transfer", elapsed_time_transfer, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1633}
1634
1635char *perfd_size (int page_len)
1636{
1637 return perfdata ("size", page_len, "B",
1638 (min_page_len>0?TRUE:FALSE), min_page_len,
1639 (min_page_len>0?TRUE:FALSE), 0,
1640 TRUE, 0, FALSE, 0);
1641}
1642
1643void
1644print_help (void)
1645{
1646 print_revision (progname, NP_VERSION);
1647
1648 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
1649 printf (COPYRIGHT, copyright, email);
1650
1651 printf ("%s\n", _("This plugin tests the HTTP service on the specified host. It can test"));
1652 printf ("%s\n", _("normal (http) and secure (https) servers, follow redirects, search for"));
1653 printf ("%s\n", _("strings and regular expressions, check connection times, and report on"));
1654 printf ("%s\n", _("certificate expiration times."));
1655 printf ("\n");
1656 printf ("%s\n", _("It makes use of libcurl to do so. It tries to be as compatible to check_http"));
1657 printf ("%s\n", _("as possible."));
1658
1659 printf ("\n\n");
1660
1661 print_usage ();
1662
1663 printf (_("NOTE: One or both of -H and -I must be specified"));
1664
1665 printf ("\n");
1666
1667 printf (UT_HELP_VRSN);
1668 printf (UT_EXTRA_OPTS);
1669
1670 printf (" %s\n", "-H, --hostname=ADDRESS");
1671 printf (" %s\n", _("Host name argument for servers using host headers (virtual host)"));
1672 printf (" %s\n", _("Append a port to include it in the header (eg: example.com:5000)"));
1673 printf (" %s\n", "-I, --IP-address=ADDRESS");
1674 printf (" %s\n", _("IP address or name (use numeric address if possible to bypass DNS lookup)."));
1675 printf (" %s\n", "-p, --port=INTEGER");
1676 printf (" %s", _("Port number (default: "));
1677 printf ("%d)\n", HTTP_PORT);
1678
1679 printf (UT_IPv46);
1680
1681#ifdef LIBCURL_FEATURE_SSL
1682 printf (" %s\n", "-S, --ssl=VERSION[+]");
1683 printf (" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is optional, and prevents"));
1684 printf (" %s\n", _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,"));
1685 printf (" %s\n", _("1.2 = TLSv1.2, 1.3 = TLSv1.3). With a '+' suffix, newer versions are also accepted."));
1686 printf (" %s\n", _("Note: SSLv2 and SSLv3 are deprecated and are usually disabled in libcurl"));
1687 printf (" %s\n", "--sni");
1688 printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)"));
1689#if LIBCURL_VERSION_NUM >= 0x071801
1690 printf (" %s\n", _("Note: --sni is the default in libcurl as SSLv2 and SSLV3 are deprecated and"));
1691 printf (" %s\n", _(" SNI only really works since TLSv1.0"));
1692#else
1693 printf (" %s\n", _("Note: SNI is not supported in libcurl before 7.18.1"));
1694#endif
1695 printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]");
1696 printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443"));
1697 printf (" %s\n", _("(when this option is used the URL is not checked.)"));
1698 printf (" %s\n", "-J, --client-cert=FILE");
1699 printf (" %s\n", _("Name of file that contains the client certificate (PEM format)"));
1700 printf (" %s\n", _("to be used in establishing the SSL session"));
1701 printf (" %s\n", "-K, --private-key=FILE");
1702 printf (" %s\n", _("Name of file containing the private key (PEM format)"));
1703 printf (" %s\n", _("matching the client certificate"));
1704 printf (" %s\n", "--ca-cert=FILE");
1705 printf (" %s\n", _("CA certificate file to verify peer against"));
1706#endif
1707
1708 printf (" %s\n", "-e, --expect=STRING");
1709 printf (" %s\n", _("Comma-delimited list of strings, at least one of them is expected in"));
1710 printf (" %s", _("the first (status) line of the server response (default: "));
1711 printf ("%s)\n", HTTP_EXPECT);
1712 printf (" %s\n", _("If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)"));
1713 printf (" %s\n", "-d, --header-string=STRING");
1714 printf (" %s\n", _("String to expect in the response headers"));
1715 printf (" %s\n", "-s, --string=STRING");
1716 printf (" %s\n", _("String to expect in the content"));
1717 printf (" %s\n", "-u, --url=PATH");
1718 printf (" %s\n", _("URL to GET or POST (default: /)"));
1719 printf (" %s\n", "-P, --post=STRING");
1720 printf (" %s\n", _("URL encoded http POST data"));
1721 printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)");
1722 printf (" %s\n", _("Set HTTP method."));
1723 printf (" %s\n", "-N, --no-body");
1724 printf (" %s\n", _("Don't wait for document body: stop reading after headers."));
1725 printf (" %s\n", _("(Note that this still does an HTTP GET or POST, not a HEAD.)"));
1726 printf (" %s\n", "-M, --max-age=SECONDS");
1727 printf (" %s\n", _("Warn if document is more than SECONDS old. the number can also be of"));
1728 printf (" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or \"10d\" for days."));
1729 printf (" %s\n", "-T, --content-type=STRING");
1730 printf (" %s\n", _("specify Content-Type header media type when POSTing\n"));
1731 printf (" %s\n", "-l, --linespan");
1732 printf (" %s\n", _("Allow regex to span newlines (must precede -r or -R)"));
1733 printf (" %s\n", "-r, --regex, --ereg=STRING");
1734 printf (" %s\n", _("Search page for regex STRING"));
1735 printf (" %s\n", "-R, --eregi=STRING");
1736 printf (" %s\n", _("Search page for case-insensitive regex STRING"));
1737 printf (" %s\n", "--invert-regex");
1738 printf (" %s\n", _("Return CRITICAL if found, OK if not\n"));
1739 printf (" %s\n", "-a, --authorization=AUTH_PAIR");
1740 printf (" %s\n", _("Username:password on sites with basic authentication"));
1741 printf (" %s\n", "-b, --proxy-authorization=AUTH_PAIR");
1742 printf (" %s\n", _("Username:password on proxy-servers with basic authentication"));
1743 printf (" %s\n", "-A, --useragent=STRING");
1744 printf (" %s\n", _("String to be sent in http header as \"User Agent\""));
1745 printf (" %s\n", "-k, --header=STRING");
1746 printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers"));
1747 printf (" %s\n", "-E, --extended-perfdata");
1748 printf (" %s\n", _("Print additional performance data"));
1749 printf (" %s\n", "-L, --link");
1750 printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)"));
1751 printf (" %s\n", "-f, --onredirect=<ok|warning|critical|follow|sticky|stickyport|curl>");
1752 printf (" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the"));
1753 printf (" %s\n", _("specified IP address. stickyport also ensures port stays the same."));
1754 printf (" %s\n", _("follow uses the old redirection algorithm of check_http."));
1755 printf (" %s\n", _("curl uses CURL_FOLLOWLOCATION built into libcurl."));
1756 printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>");
1757 printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)"));
1758 printf ("\n");
1759 printf (" %s\n", "--http-version=VERSION");
1760 printf (" %s\n", _("Connect via specific HTTP protocol."));
1761 printf (" %s\n", _("1.0 = HTTP/1.0, 1.1 = HTTP/1.1, 2.0 = HTTP/2 (HTTP/2 will fail without -S)"));
1762 printf ("\n");
1763
1764 printf (UT_WARN_CRIT);
1765
1766 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
1767
1768 printf (UT_VERBOSE);
1769
1770 printf ("\n");
1771 printf ("%s\n", _("Notes:"));
1772 printf (" %s\n", _("This plugin will attempt to open an HTTP connection with the host."));
1773 printf (" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL"));
1774 printf (" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect response"));
1775 printf (" %s\n", _("messages from the host result in STATE_WARNING return values. If you are"));
1776 printf (" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN"));
1777 printf (" %s\n", _("(fully qualified domain name) as the [host_name] argument."));
1778
1779#ifdef LIBCURL_FEATURE_SSL
1780 printf ("\n");
1781 printf (" %s\n", _("This plugin can also check whether an SSL enabled web server is able to"));
1782 printf (" %s\n", _("serve content (optionally within a specified time) or whether the X509 "));
1783 printf (" %s\n", _("certificate is still valid for the specified number of days."));
1784 printf ("\n");
1785 printf (" %s\n", _("Please note that this plugin does not check if the presented server"));
1786 printf (" %s\n", _("certificate matches the hostname of the server, or if the certificate"));
1787 printf (" %s\n", _("has a valid chain of trust to one of the locally installed CAs."));
1788 printf ("\n");
1789 printf ("%s\n", _("Examples:"));
1790 printf (" %s\n\n", "CHECK CONTENT: check_curl -w 5 -c 10 --ssl -H www.verisign.com");
1791 printf (" %s\n", _("When the 'www.verisign.com' server returns its content within 5 seconds,"));
1792 printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds"));
1793 printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,"));
1794 printf (" %s\n", _("a STATE_CRITICAL will be returned."));
1795 printf ("\n");
1796 printf (" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 14");
1797 printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,"));
1798 printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
1799 printf (" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when"));
1800 printf (" %s\n\n", _("the certificate is expired."));
1801 printf ("\n");
1802 printf (" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 30,14");
1803 printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 30 days,"));
1804 printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
1805 printf (" %s\n", _("30 days, but more than 14 days, a STATE_WARNING is returned."));
1806 printf (" %s\n", _("A STATE_CRITICAL will be returned when certificate expires in less than 14 days"));
1807#endif
1808
1809 printf ("\n %s\n", "CHECK WEBSERVER CONTENT VIA PROXY:");
1810 printf (" %s\n", _("It is recommended to use an environment proxy like:"));
1811 printf (" %s\n", _("http_proxy=http://192.168.100.35:3128 ./check_curl -H www.monitoring-plugins.org"));
1812 printf (" %s\n", _("legacy proxy requests in check_http style still work:"));
1813 printf (" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u http://www.monitoring-plugins.org/ -H www.monitoring-plugins.org"));
1814
1815#ifdef LIBCURL_FEATURE_SSL
1816 printf ("\n %s\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: ");
1817 printf (" %s\n", _("It is recommended to use an environment proxy like:"));
1818 printf (" %s\n", _("https_proxy=http://192.168.100.35:3128 ./check_curl -H www.verisign.com -S"));
1819 printf (" %s\n", _("legacy proxy requests in check_http style still work:"));
1820 printf (" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u https://www.verisign.com/ -S -j CONNECT -H www.verisign.com "));
1821 printf (" %s\n", _("all these options are needed: -I <proxy> -p <proxy-port> -u <check-url> -S(sl) -j CONNECT -H <webserver>"));
1822 printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds"));
1823 printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,"));
1824 printf (" %s\n", _("a STATE_CRITICAL will be returned."));
1825
1826#endif
1827
1828 printf (UT_SUPPORT);
1829
1830}
1831
1832
1833
1834void
1835print_usage (void)
1836{
1837 printf ("%s\n", _("Usage:"));
1838 printf (" %s -H <vhost> | -I <IP-address> [-u <uri>] [-p <port>]\n",progname);
1839 printf (" [-J <client certificate file>] [-K <private key>] [--ca-cert <CA certificate file>]\n");
1840 printf (" [-w <warn time>] [-c <critical time>] [-t <timeout>] [-L] [-E] [-a auth]\n");
1841 printf (" [-b proxy_auth] [-f <ok|warning|critcal|follow|sticky|stickyport|curl>]\n");
1842 printf (" [-e <expect>] [-d string] [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n");
1843 printf (" [-P string] [-m <min_pg_size>:<max_pg_size>] [-4|-6] [-N] [-M <age>]\n");
1844 printf (" [-A string] [-k string] [-S <version>] [--sni] [-C <warn_age>[,<crit_age>]]\n");
1845 printf (" [-T <content-type>] [-j method]\n");
1846 printf (" [--http-version=<version>]\n");
1847 printf ("\n");
1848 printf ("%s\n", _("WARNING: check_curl is experimental. Please use"));
1849 printf ("%s\n\n", _("check_http if you need a stable version."));
1850}
1851
1852void
1853print_curl_version (void)
1854{
1855 printf( "%s\n", curl_version());
1856}
1857
1858int
1859curlhelp_initwritebuffer (curlhelp_write_curlbuf *buf)
1860{
1861 buf->bufsize = DEFAULT_BUFFER_SIZE;
1862 buf->buflen = 0;
1863 buf->buf = (char *)malloc ((size_t)buf->bufsize);
1864 if (buf->buf == NULL) return -1;
1865 return 0;
1866}
1867
1868int
1869curlhelp_buffer_write_callback (void *buffer, size_t size, size_t nmemb, void *stream)
1870{
1871 curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream;
1872
1873 while (buf->bufsize < buf->buflen + size * nmemb + 1) {
1874 buf->bufsize *= buf->bufsize * 2;
1875 buf->buf = (char *)realloc (buf->buf, buf->bufsize);
1876 if (buf->buf == NULL) return -1;
1877 }
1878
1879 memcpy (buf->buf + buf->buflen, buffer, size * nmemb);
1880 buf->buflen += size * nmemb;
1881 buf->buf[buf->buflen] = '\0';
1882
1883 return (int)(size * nmemb);
1884}
1885
1886int
1887curlhelp_buffer_read_callback (void *buffer, size_t size, size_t nmemb, void *stream)
1888{
1889 curlhelp_read_curlbuf *buf = (curlhelp_read_curlbuf *)stream;
1890
1891 size_t n = min (nmemb * size, buf->buflen - buf->pos);
1892
1893 memcpy (buffer, buf->buf + buf->pos, n);
1894 buf->pos += n;
1895
1896 return (int)n;
1897}
1898
1899void
1900curlhelp_freewritebuffer (curlhelp_write_curlbuf *buf)
1901{
1902 free (buf->buf);
1903 buf->buf = NULL;
1904}
1905
1906int
1907curlhelp_initreadbuffer (curlhelp_read_curlbuf *buf, const char *data, size_t datalen)
1908{
1909 buf->buflen = datalen;
1910 buf->buf = (char *)malloc ((size_t)buf->buflen);
1911 if (buf->buf == NULL) return -1;
1912 memcpy (buf->buf, data, datalen);
1913 buf->pos = 0;
1914 return 0;
1915}
1916
1917void
1918curlhelp_freereadbuffer (curlhelp_read_curlbuf *buf)
1919{
1920 free (buf->buf);
1921 buf->buf = NULL;
1922}
1923
1924/* TODO: where to put this, it's actually part of sstrings2 (logically)?
1925 */
1926const char*
1927strrstr2(const char *haystack, const char *needle)
1928{
1929 int counter;
1930 size_t len;
1931 const char *prev_pos;
1932 const char *pos;
1933
1934 if (haystack == NULL || needle == NULL)
1935 return NULL;
1936
1937 if (haystack[0] == '\0' || needle[0] == '\0')
1938 return NULL;
1939
1940 counter = 0;
1941 prev_pos = NULL;
1942 pos = haystack;
1943 len = strlen (needle);
1944 for (;;) {
1945 pos = strstr (pos, needle);
1946 if (pos == NULL) {
1947 if (counter == 0)
1948 return NULL;
1949 else
1950 return prev_pos;
1951 }
1952 counter++;
1953 prev_pos = pos;
1954 pos += len;
1955 if (*pos == '\0') return prev_pos;
1956 }
1957}
1958
1959int
1960curlhelp_parse_statusline (const char *buf, curlhelp_statusline *status_line)
1961{
1962 char *first_line_end;
1963 char *p;
1964 size_t first_line_len;
1965 char *pp;
1966 const char *start;
1967 char *first_line_buf;
1968
1969 /* find last start of a new header */
1970 start = strrstr2 (buf, "\r\nHTTP");
1971 if (start != NULL) {
1972 start += 2;
1973 buf = start;
1974 }
1975
1976 first_line_end = strstr(buf, "\r\n");
1977 if (first_line_end == NULL) return -1;
1978
1979 first_line_len = (size_t)(first_line_end - buf);
1980 status_line->first_line = (char *)malloc (first_line_len + 1);
1981 if (status_line->first_line == NULL) return -1;
1982 memcpy (status_line->first_line, buf, first_line_len);
1983 status_line->first_line[first_line_len] = '\0';
1984 first_line_buf = strdup( status_line->first_line );
1985
1986 /* protocol and version: "HTTP/x.x" SP or "HTTP/2" SP */
1987
1988 p = strtok(first_line_buf, "/");
1989 if( p == NULL ) { free( first_line_buf ); return -1; }
1990 if( strcmp( p, "HTTP" ) != 0 ) { free( first_line_buf ); return -1; }
1991
1992 p = strtok( NULL, " " );
1993 if( p == NULL ) { free( first_line_buf ); return -1; }
1994 if( strchr( p, '.' ) != NULL ) {
1995
1996 /* HTTP 1.x case */
1997 char *ppp;
1998 ppp = strtok( p, "." );
1999 status_line->http_major = (int)strtol( p, &pp, 10 );
2000 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
2001 ppp = strtok( NULL, " " );
2002 status_line->http_minor = (int)strtol( p, &pp, 10 );
2003 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
2004 p += 4; /* 1.x SP */
2005 } else {
2006 /* HTTP 2 case */
2007 status_line->http_major = (int)strtol( p, &pp, 10 );
2008 status_line->http_minor = 0;
2009 p += 2; /* 2 SP */
2010 }
2011
2012 /* status code: "404" or "404.1", then SP */
2013
2014 p = strtok( p, " " );
2015 if( p == NULL ) { free( first_line_buf ); return -1; }
2016 if( strchr( p, '.' ) != NULL ) {
2017 char *ppp;
2018 ppp = strtok( p, "." );
2019 status_line->http_code = (int)strtol( ppp, &pp, 10 );
2020 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
2021 ppp = strtok( NULL, "" );
2022 status_line->http_subcode = (int)strtol( ppp, &pp, 10 );
2023 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
2024 p += 6; /* 400.1 SP */
2025 } else {
2026 status_line->http_code = (int)strtol( p, &pp, 10 );
2027 status_line->http_subcode = -1;
2028 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
2029 p += 4; /* 400 SP */
2030 }
2031
2032 /* Human readable message: "Not Found" CRLF */
2033
2034 p = strtok( p, "" );
2035 if( p == NULL ) { status_line->msg = ""; return 0; }
2036 status_line->msg = status_line->first_line + ( p - first_line_buf );
2037 free( first_line_buf );
2038
2039 return 0;
2040}
2041
2042void
2043curlhelp_free_statusline (curlhelp_statusline *status_line)
2044{
2045 free (status_line->first_line);
2046}
2047
2048void
2049remove_newlines (char *s)
2050{
2051 char *p;
2052
2053 for (p = s; *p != '\0'; p++)
2054 if (*p == '\r' || *p == '\n')
2055 *p = ' ';
2056}
2057
2058char *
2059get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header)
2060{
2061 int i;
2062 for( i = 0; i < nof_headers; i++ ) {
2063 if(headers[i].name != NULL && strncasecmp( header, headers[i].name, max( headers[i].name_len, 4 ) ) == 0 ) {
2064 return strndup( headers[i].value, headers[i].value_len );
2065 }
2066 }
2067 return NULL;
2068}
2069
2070int
2071check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFAULT_BUFFER_SIZE])
2072{
2073 char *server_date = NULL;
2074 char *document_date = NULL;
2075 int date_result = STATE_OK;
2076 curlhelp_statusline status_line;
2077 struct phr_header headers[255];
2078 size_t nof_headers = 255;
2079 size_t msglen;
2080
2081 int res = phr_parse_response (header_buf->buf, header_buf->buflen,
2082 &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen,
2083 headers, &nof_headers, 0);
2084
2085 server_date = get_header_value (headers, nof_headers, "date");
2086 document_date = get_header_value (headers, nof_headers, "last-modified");
2087
2088 if (!server_date || !*server_date) {
2089 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sServer date unknown, "), *msg);
2090 date_result = max_state_alt(STATE_UNKNOWN, date_result);
2091 } else if (!document_date || !*document_date) {
2092 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument modification date unknown, "), *msg);
2093 date_result = max_state_alt(STATE_CRITICAL, date_result);
2094 } else {
2095 time_t srv_data = curl_getdate (server_date, NULL);
2096 time_t doc_data = curl_getdate (document_date, NULL);
2097 if (verbose >= 2)
2098 printf ("* server date: '%s' (%d), doc_date: '%s' (%d)\n", server_date, (int)srv_data, document_date, (int)doc_data);
2099 if (srv_data <= 0) {
2100 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sServer date \"%100s\" unparsable, "), *msg, server_date);
2101 date_result = max_state_alt(STATE_CRITICAL, date_result);
2102 } else if (doc_data <= 0) {
2103 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date);
2104 date_result = max_state_alt(STATE_CRITICAL, date_result);
2105 } else if (doc_data > srv_data + 30) {
2106 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data);
2107 date_result = max_state_alt(STATE_CRITICAL, date_result);
2108 } else if (doc_data < srv_data - maximum_age) {
2109 int n = (srv_data - doc_data);
2110 if (n > (60 * 60 * 24 * 2)) {
2111 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24));
2112 date_result = max_state_alt(STATE_CRITICAL, date_result);
2113 } else {
2114 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60);
2115 date_result = max_state_alt(STATE_CRITICAL, date_result);
2116 }
2117 }
2118 }
2119
2120 if (server_date) free (server_date);
2121 if (document_date) free (document_date);
2122
2123 return date_result;
2124}
2125
2126
2127int
2128get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_write_curlbuf* body_buf)
2129{
2130 const char *s;
2131 int content_length = 0;
2132 char *copy;
2133 struct phr_header headers[255];
2134 size_t nof_headers = 255;
2135 size_t msglen;
2136 char *content_length_s = NULL;
2137 curlhelp_statusline status_line;
2138
2139 int res = phr_parse_response (header_buf->buf, header_buf->buflen,
2140 &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen,
2141 headers, &nof_headers, 0);
2142
2143 content_length_s = get_header_value (headers, nof_headers, "content-length");
2144 if (!content_length_s) {
2145 return header_buf->buflen + body_buf->buflen;
2146 }
2147 content_length_s += strspn (content_length_s, " \t");
2148 content_length = atoi (content_length_s);
2149 if (content_length != body_buf->buflen) {
2150 /* TODO: should we warn if the actual and the reported body length don't match? */
2151 }
2152
2153 if (content_length_s) free (content_length_s);
2154
2155 return header_buf->buflen + body_buf->buflen;
2156}
2157
2158/* TODO: is there a better way in libcurl to check for the SSL library? */
2159curlhelp_ssl_library
2160curlhelp_get_ssl_library (CURL* curl)
2161{
2162 curl_version_info_data* version_data;
2163 char *ssl_version;
2164 char *library;
2165 curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN;
2166
2167 version_data = curl_version_info (CURLVERSION_NOW);
2168 if (version_data == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN;
2169
2170 ssl_version = strdup (version_data->ssl_version);
2171 if (ssl_version == NULL ) return CURLHELP_SSL_LIBRARY_UNKNOWN;
2172
2173 library = strtok (ssl_version, "/");
2174 if (library == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN;
2175
2176 if (strcmp (library, "OpenSSL") == 0)
2177 ssl_library = CURLHELP_SSL_LIBRARY_OPENSSL;
2178 else if (strcmp (library, "LibreSSL") == 0)
2179 ssl_library = CURLHELP_SSL_LIBRARY_LIBRESSL;
2180 else if (strcmp (library, "GnuTLS") == 0)
2181 ssl_library = CURLHELP_SSL_LIBRARY_GNUTLS;
2182 else if (strcmp (library, "NSS") == 0)
2183 ssl_library = CURLHELP_SSL_LIBRARY_NSS;
2184
2185 if (verbose >= 2)
2186 printf ("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library, ssl_library);
2187
2188 free (ssl_version);
2189
2190 return ssl_library;
2191}
2192
2193const char*
2194curlhelp_get_ssl_library_string (curlhelp_ssl_library ssl_library)
2195{
2196 switch (ssl_library) {
2197 case CURLHELP_SSL_LIBRARY_OPENSSL:
2198 return "OpenSSL";
2199 case CURLHELP_SSL_LIBRARY_LIBRESSL:
2200 return "LibreSSL";
2201 case CURLHELP_SSL_LIBRARY_GNUTLS:
2202 return "GnuTLS";
2203 case CURLHELP_SSL_LIBRARY_NSS:
2204 return "NSS";
2205 case CURLHELP_SSL_LIBRARY_UNKNOWN:
2206 default:
2207 return "unknown";
2208 }
2209}
2210
2211#ifdef LIBCURL_FEATURE_SSL
2212#ifndef USE_OPENSSL
2213time_t
2214parse_cert_date (const char *s)
2215{
2216 struct tm tm;
2217 time_t date;
2218 char *res;
2219
2220 if (!s) return -1;
2221
2222 /* Jan 17 14:25:12 2020 GMT */
2223 res = strptime (s, "%Y-%m-%d %H:%M:%S GMT", &tm);
2224 /* Sep 11 12:00:00 2020 GMT */
2225 if (res == NULL) strptime (s, "%Y %m %d %H:%M:%S GMT", &tm);
2226 date = mktime (&tm);
2227
2228 return date;
2229}
2230
2231/* TODO: this needs cleanup in the sslutils.c, maybe we the #else case to
2232 * OpenSSL could be this function
2233 */
2234int
2235net_noopenssl_check_certificate (cert_ptr_union* cert_ptr, int days_till_exp_warn, int days_till_exp_crit)
2236{
2237 int i;
2238 struct curl_slist* slist;
2239 int cname_found = 0;
2240 char* start_date_str = NULL;
2241 char* end_date_str = NULL;
2242 time_t start_date;
2243 time_t end_date;
2244 char *tz;
2245 float time_left;
2246 int days_left;
2247 int time_remaining;
2248 char timestamp[50] = "";
2249 int status = STATE_UNKNOWN;
2250
2251 if (verbose >= 2)
2252 printf ("**** REQUEST CERTIFICATES ****\n");
2253
2254 for (i = 0; i < cert_ptr->to_certinfo->num_of_certs; i++) {
2255 for (slist = cert_ptr->to_certinfo->certinfo[i]; slist; slist = slist->next) {
2256 /* find first common name in subject,
2257 * TODO: check alternative subjects for
2258 * TODO: have a decent parser here and not a hack
2259 * multi-host certificate, check wildcards
2260 */
2261 if (strncasecmp (slist->data, "Subject:", 8) == 0) {
2262 int d = 3;
2263 char* p = strstr (slist->data, "CN=");
2264 if (p == NULL) {
2265 d = 5;
2266 p = strstr (slist->data, "CN = ");
2267 }
2268 if (p != NULL) {
2269 if (strncmp (host_name, p+d, strlen (host_name)) == 0) {
2270 cname_found = 1;
2271 }
2272 }
2273 } else if (strncasecmp (slist->data, "Start Date:", 11) == 0) {
2274 start_date_str = &slist->data[11];
2275 } else if (strncasecmp (slist->data, "Expire Date:", 12) == 0) {
2276 end_date_str = &slist->data[12];
2277 } else if (strncasecmp (slist->data, "Cert:", 5) == 0) {
2278 goto HAVE_FIRST_CERT;
2279 }
2280 if (verbose >= 2)
2281 printf ("%d ** %s\n", i, slist->data);
2282 }
2283 }
2284HAVE_FIRST_CERT:
2285
2286 if (verbose >= 2)
2287 printf ("**** REQUEST CERTIFICATES ****\n");
2288
2289 if (!cname_found) {
2290 printf("%s\n",_("CRITICAL - Cannot retrieve certificate subject."));
2291 return STATE_CRITICAL;
2292 }
2293
2294 start_date = parse_cert_date (start_date_str);
2295 if (start_date <= 0) {
2296 snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Start Date' in certificate: '%s'"),
2297 start_date_str);
2298 puts (msg);
2299 return STATE_WARNING;
2300 }
2301
2302 end_date = parse_cert_date (end_date_str);
2303 if (end_date <= 0) {
2304 snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Expire Date' in certificate: '%s'"),
2305 start_date_str);
2306 puts (msg);
2307 return STATE_WARNING;
2308 }
2309
2310 time_left = difftime (end_date, time(NULL));
2311 days_left = time_left / 86400;
2312 tz = getenv("TZ");
2313 setenv("TZ", "GMT", 1);
2314 tzset();
2315 strftime(timestamp, 50, "%c %z", localtime(&end_date));
2316 if (tz)
2317 setenv("TZ", tz, 1);
2318 else
2319 unsetenv("TZ");
2320 tzset();
2321
2322 if (days_left > 0 && days_left <= days_till_exp_warn) {
2323 printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, days_left, timestamp);
2324 if (days_left > days_till_exp_crit)
2325 status = STATE_WARNING;
2326 else
2327 status = STATE_CRITICAL;
2328 } else if (days_left == 0 && time_left > 0) {
2329 if (time_left >= 3600)
2330 time_remaining = (int) time_left / 3600;
2331 else
2332 time_remaining = (int) time_left / 60;
2333
2334 printf (_("%s - Certificate '%s' expires in %u %s (%s)\n"),
2335 (days_left>days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name, time_remaining,
2336 time_left >= 3600 ? "hours" : "minutes", timestamp);
2337
2338 if ( days_left > days_till_exp_crit)
2339 status = STATE_WARNING;
2340 else
2341 status = STATE_CRITICAL;
2342 } else if (time_left < 0) {
2343 printf(_("CRITICAL - Certificate '%s' expired on %s.\n"), host_name, timestamp);
2344 status=STATE_CRITICAL;
2345 } else if (days_left == 0) {
2346 printf (_("%s - Certificate '%s' just expired (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, timestamp);
2347 if (days_left > days_till_exp_crit)
2348 status = STATE_WARNING;
2349 else
2350 status = STATE_CRITICAL;
2351 } else {
2352 printf(_("OK - Certificate '%s' will expire on %s.\n"), host_name, timestamp);
2353 status = STATE_OK;
2354 }
2355 return status;
2356}
2357#endif /* USE_OPENSSL */
2358#endif /* LIBCURL_FEATURE_SSL */