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