Merge pull request #2045 from RincewindsHat/fix/calloc_argument_order
[monitoring-plugins.git] / plugins / check_curl.c
blob1d27da28243fcba28ea07b3dabc78d6303962ad4
1 /*****************************************************************************
3 * Monitoring check_curl plugin
5 * License: GPL
6 * Copyright (c) 1999-2024 Monitoring Plugins Development Team
8 * Description:
10 * This file contains the check_curl plugin
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.
17 * This plugin uses functions from the curl library, see
18 * http://curl.haxx.se
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.
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.
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/>.
34 *****************************************************************************/
35 const char *progname = "check_curl";
37 const char *copyright = "2006-2024";
38 const char *email = "devel@monitoring-plugins.org";
40 #include <stdbool.h>
41 #include <ctype.h>
43 #include "common.h"
44 #include "utils.h"
46 #ifndef LIBCURL_PROTOCOL_HTTP
47 # error libcurl compiled without HTTP support, compiling check_curl plugin does not makes a lot of sense
48 #endif
50 #include "curl/curl.h"
51 #include "curl/easy.h"
53 #include "picohttpparser.h"
55 #include "uriparser/Uri.h"
57 #include <arpa/inet.h>
58 #include <netinet/in.h>
60 #if defined(HAVE_SSL) && defined(USE_OPENSSL)
61 # include <openssl/opensslv.h>
62 #endif
64 #include <netdb.h>
66 #define MAKE_LIBCURL_VERSION(major, minor, patch) ((major)*0x10000 + (minor)*0x100 + (patch))
68 #define DEFAULT_BUFFER_SIZE 2048
69 #define DEFAULT_SERVER_URL "/"
70 #define HTTP_EXPECT "HTTP/"
71 #define INET_ADDR_MAX_SIZE INET6_ADDRSTRLEN
72 enum {
73 MAX_IPV4_HOSTLENGTH = 255,
74 HTTP_PORT = 80,
75 HTTPS_PORT = 443,
76 MAX_PORT = 65535,
77 DEFAULT_MAX_REDIRS = 15
80 enum {
81 STICKY_NONE = 0,
82 STICKY_HOST = 1,
83 STICKY_PORT = 2
86 enum {
87 FOLLOW_HTTP_CURL = 0,
88 FOLLOW_LIBCURL = 1
91 /* for buffers for header and body */
92 typedef struct {
93 char *buf;
94 size_t buflen;
95 size_t bufsize;
96 } curlhelp_write_curlbuf;
98 /* for buffering the data sent in PUT */
99 typedef struct {
100 char *buf;
101 size_t buflen;
102 off_t pos;
103 } curlhelp_read_curlbuf;
105 /* for parsing the HTTP status line */
106 typedef struct {
107 int http_major; /* major version of the protocol, always 1 (HTTP/0.9
108 * never reached the big internet most likely) */
109 int http_minor; /* minor version of the protocol, usually 0 or 1 */
110 int http_code; /* HTTP return code as in RFC 2145 */
111 int http_subcode; /* Microsoft IIS extension, HTTP subcodes, see
112 * http://support.microsoft.com/kb/318380/en-us */
113 const char *msg; /* the human readable message */
114 char *first_line; /* a copy of the first line */
115 } curlhelp_statusline;
117 /* to know the underlying SSL library used by libcurl */
118 typedef enum curlhelp_ssl_library {
119 CURLHELP_SSL_LIBRARY_UNKNOWN,
120 CURLHELP_SSL_LIBRARY_OPENSSL,
121 CURLHELP_SSL_LIBRARY_LIBRESSL,
122 CURLHELP_SSL_LIBRARY_GNUTLS,
123 CURLHELP_SSL_LIBRARY_NSS
124 } curlhelp_ssl_library;
126 enum {
127 REGS = 2,
128 MAX_RE_SIZE = 1024
130 #include "regex.h"
131 static regex_t preg;
132 static regmatch_t pmatch[REGS];
133 static char regexp[MAX_RE_SIZE];
134 static int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE;
135 static int errcode;
136 static bool invert_regex = false;
137 static int state_regex = STATE_CRITICAL;
139 static char *server_address = NULL;
140 static char *host_name = NULL;
141 static char *server_url = 0;
142 static struct curl_slist *server_ips = NULL;
143 static bool specify_port = false;
144 static unsigned short server_port = HTTP_PORT;
145 static unsigned short virtual_port = 0;
146 static int host_name_length;
147 static char output_header_search[30] = "";
148 static char output_string_search[30] = "";
149 static char *warning_thresholds = NULL;
150 static char *critical_thresholds = NULL;
151 static int days_till_exp_warn, days_till_exp_crit;
152 static thresholds *thlds;
153 static char user_agent[DEFAULT_BUFFER_SIZE];
154 static int verbose = 0;
155 static bool show_extended_perfdata = false;
156 static bool show_body = false;
157 static int min_page_len = 0;
158 static int max_page_len = 0;
159 static int redir_depth = 0;
160 static int max_depth = DEFAULT_MAX_REDIRS;
161 static char *http_method = NULL;
162 static char *http_post_data = NULL;
163 static char *http_content_type = NULL;
164 static CURL *curl;
165 static bool curl_global_initialized = false;
166 static bool curl_easy_initialized = false;
167 static struct curl_slist *header_list = NULL;
168 static bool body_buf_initialized = false;
169 static curlhelp_write_curlbuf body_buf;
170 static bool header_buf_initialized = false;
171 static curlhelp_write_curlbuf header_buf;
172 static bool status_line_initialized = false;
173 static curlhelp_statusline status_line;
174 static bool put_buf_initialized = false;
175 static curlhelp_read_curlbuf put_buf;
176 static char http_header[DEFAULT_BUFFER_SIZE];
177 static long code;
178 static long socket_timeout = DEFAULT_SOCKET_TIMEOUT;
179 static double total_time;
180 static double time_connect;
181 static double time_appconnect;
182 static double time_headers;
183 static double time_firstbyte;
184 static char errbuf[MAX_INPUT_BUFFER];
185 static CURLcode res;
186 static char url[DEFAULT_BUFFER_SIZE];
187 static char msg[DEFAULT_BUFFER_SIZE];
188 static char perfstring[DEFAULT_BUFFER_SIZE];
189 static char header_expect[MAX_INPUT_BUFFER] = "";
190 static char string_expect[MAX_INPUT_BUFFER] = "";
191 static char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT;
192 static int server_expect_yn = 0;
193 static char user_auth[MAX_INPUT_BUFFER] = "";
194 static char proxy_auth[MAX_INPUT_BUFFER] = "";
195 static char **http_opt_headers;
196 static int http_opt_headers_count = 0;
197 static bool display_html = false;
198 static int onredirect = STATE_OK;
199 static int followmethod = FOLLOW_HTTP_CURL;
200 static int followsticky = STICKY_NONE;
201 static bool use_ssl = false;
202 static bool check_cert = false;
203 static bool continue_after_check_cert = false;
204 typedef union {
205 struct curl_slist *to_info;
206 struct curl_certinfo *to_certinfo;
207 } cert_ptr_union;
208 static cert_ptr_union cert_ptr;
209 static int ssl_version = CURL_SSLVERSION_DEFAULT;
210 static char *client_cert = NULL;
211 static char *client_privkey = NULL;
212 static char *ca_cert = NULL;
213 static bool verify_peer_and_host = false;
214 static bool is_openssl_callback = false;
215 static bool add_sslctx_verify_fun = false;
216 #if defined(HAVE_SSL) && defined(USE_OPENSSL)
217 static X509 *cert = NULL;
218 #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */
219 static bool no_body = false;
220 static int maximum_age = -1;
221 static int address_family = AF_UNSPEC;
222 static curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN;
223 static int curl_http_version = CURL_HTTP_VERSION_NONE;
224 static bool automatic_decompression = false;
225 static char *cookie_jar_file = NULL;
226 static bool haproxy_protocol = false;
228 static bool process_arguments(int /*argc*/, char ** /*argv*/);
229 static void handle_curl_option_return_code(CURLcode res, const char *option);
230 static int check_http(void);
231 static void redir(curlhelp_write_curlbuf * /*header_buf*/);
232 static char *perfd_time(double elapsed_time);
233 static char *perfd_time_connect(double elapsed_time_connect);
234 static char *perfd_time_ssl(double elapsed_time_ssl);
235 static char *perfd_time_firstbyte(double elapsed_time_firstbyte);
236 static char *perfd_time_headers(double elapsed_time_headers);
237 static char *perfd_time_transfer(double elapsed_time_transfer);
238 static char *perfd_size(int page_len);
239 static void print_help(void);
240 void print_usage(void);
241 static void print_curl_version(void);
242 static int curlhelp_initwritebuffer(curlhelp_write_curlbuf * /*buf*/);
243 static size_t curlhelp_buffer_write_callback(void * /*buffer*/, size_t /*size*/, size_t /*nmemb*/, void * /*stream*/);
244 static void curlhelp_freewritebuffer(curlhelp_write_curlbuf * /*buf*/);
245 static int curlhelp_initreadbuffer(curlhelp_read_curlbuf * /*buf*/, const char * /*data*/, size_t /*datalen*/);
246 static size_t curlhelp_buffer_read_callback(void * /*buffer*/, size_t /*size*/, size_t /*nmemb*/, void * /*stream*/);
247 static void curlhelp_freereadbuffer(curlhelp_read_curlbuf * /*buf*/);
248 static curlhelp_ssl_library curlhelp_get_ssl_library(void);
249 static const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library /*ssl_library*/);
250 int net_noopenssl_check_certificate(cert_ptr_union *, int, int);
252 static int curlhelp_parse_statusline(const char * /*buf*/, curlhelp_statusline * /*status_line*/);
253 static void curlhelp_free_statusline(curlhelp_statusline * /*status_line*/);
254 static char *get_header_value(const struct phr_header *headers, size_t nof_headers, const char *header);
255 static int check_document_dates(const curlhelp_write_curlbuf * /*header_buf*/, char (*msg)[DEFAULT_BUFFER_SIZE]);
256 static int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf);
258 #if defined(HAVE_SSL) && defined(USE_OPENSSL)
259 int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit);
260 #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */
262 static void test_file(char * /*path*/);
264 int main(int argc, char **argv) {
265 int result = STATE_UNKNOWN;
267 setlocale(LC_ALL, "");
268 bindtextdomain(PACKAGE, LOCALEDIR);
269 textdomain(PACKAGE);
271 /* Parse extra opts if any */
272 argv = np_extra_opts(&argc, argv, progname);
274 /* set defaults */
275 snprintf(user_agent, DEFAULT_BUFFER_SIZE, "%s/v%s (monitoring-plugins %s, %s)", progname, NP_VERSION, VERSION, curl_version());
277 /* parse arguments */
278 if (process_arguments(argc, argv) == false)
279 usage4(_("Could not parse arguments"));
281 if (display_html)
282 printf("<A HREF=\"%s://%s:%d%s\" target=\"_blank\">", use_ssl ? "https" : "http", host_name ? host_name : server_address,
283 virtual_port ? virtual_port : server_port, server_url);
285 result = check_http();
286 return result;
289 #ifdef HAVE_SSL
290 # ifdef USE_OPENSSL
292 int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) {
293 (void)preverify_ok;
294 /* TODO: we get all certificates of the chain, so which ones
295 * should we test?
296 * TODO: is the last certificate always the server certificate?
298 cert = X509_STORE_CTX_get_current_cert(x509_ctx);
299 # if OPENSSL_VERSION_NUMBER >= 0x10100000L
300 X509_up_ref(cert);
301 # endif
302 if (verbose >= 2) {
303 puts("* SSL verify callback with certificate:");
304 X509_NAME *subject;
305 X509_NAME *issuer;
306 printf("* issuer:\n");
307 issuer = X509_get_issuer_name(cert);
308 X509_NAME_print_ex_fp(stdout, issuer, 5, XN_FLAG_MULTILINE);
309 printf("* curl verify_callback:\n* subject:\n");
310 subject = X509_get_subject_name(cert);
311 X509_NAME_print_ex_fp(stdout, subject, 5, XN_FLAG_MULTILINE);
312 puts("");
314 return 1;
317 CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm) {
318 (void)curl; // ignore unused parameter
319 (void)parm; // ignore unused parameter
320 if (add_sslctx_verify_fun) {
321 SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback);
324 // workaround for issue:
325 // OpenSSL SSL_read: error:0A000126:SSL routines::unexpected eof while reading, errno 0
326 // see discussion https://github.com/openssl/openssl/discussions/22690
327 # ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
328 SSL_CTX_set_options(sslctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
329 # endif
331 return CURLE_OK;
334 # endif /* USE_OPENSSL */
335 #endif /* HAVE_SSL */
337 /* returns a string "HTTP/1.x" or "HTTP/2" */
338 static char *string_statuscode(int major, int minor) {
339 static char buf[10];
341 switch (major) {
342 case 1:
343 snprintf(buf, sizeof(buf), "HTTP/%d.%d", major, minor);
344 break;
345 case 2:
346 case 3:
347 snprintf(buf, sizeof(buf), "HTTP/%d", major);
348 break;
349 default:
350 /* assuming here HTTP/N with N>=4 */
351 snprintf(buf, sizeof(buf), "HTTP/%d", major);
352 break;
355 return buf;
358 /* Checks if the server 'reply' is one of the expected 'statuscodes' */
359 static int expected_statuscode(const char *reply, const char *statuscodes) {
360 char *expected;
361 char *code;
362 int result = 0;
364 if ((expected = strdup(statuscodes)) == NULL)
365 die(STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n"));
367 for (code = strtok(expected, ","); code != NULL; code = strtok(NULL, ","))
368 if (strstr(reply, code) != NULL) {
369 result = 1;
370 break;
373 free(expected);
374 return result;
377 void handle_curl_option_return_code(CURLcode res, const char *option) {
378 if (res != CURLE_OK) {
379 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Error while setting cURL option '%s': cURL returned %d - %s"), option, res,
380 curl_easy_strerror(res));
381 die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
385 int lookup_host(const char *host, char *buf, size_t buflen) {
386 struct addrinfo hints, *res, *result;
387 char addrstr[100];
388 size_t addrstr_len;
389 int errcode;
390 void *ptr = {0};
391 size_t buflen_remaining = buflen - 1;
393 memset(&hints, 0, sizeof(hints));
394 hints.ai_family = address_family;
395 hints.ai_socktype = SOCK_STREAM;
396 hints.ai_flags |= AI_CANONNAME;
398 errcode = getaddrinfo(host, NULL, &hints, &result);
399 if (errcode != 0)
400 return errcode;
402 strcpy(buf, "");
403 res = result;
405 while (res) {
406 switch (res->ai_family) {
407 case AF_INET:
408 ptr = &((struct sockaddr_in *)res->ai_addr)->sin_addr;
409 break;
410 case AF_INET6:
411 ptr = &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
412 break;
415 inet_ntop(res->ai_family, ptr, addrstr, 100);
416 if (verbose >= 1) {
417 printf("* getaddrinfo IPv%d address: %s\n", res->ai_family == PF_INET6 ? 6 : 4, addrstr);
420 // Append all IPs to buf as a comma-separated string
421 addrstr_len = strlen(addrstr);
422 if (buflen_remaining > addrstr_len + 1) {
423 if (buf[0] != '\0') {
424 strncat(buf, ",", buflen_remaining);
425 buflen_remaining -= 1;
427 strncat(buf, addrstr, buflen_remaining);
428 buflen_remaining -= addrstr_len;
431 res = res->ai_next;
434 freeaddrinfo(result);
436 return 0;
439 static void cleanup(void) {
440 if (status_line_initialized)
441 curlhelp_free_statusline(&status_line);
442 status_line_initialized = false;
443 if (curl_easy_initialized)
444 curl_easy_cleanup(curl);
445 curl_easy_initialized = false;
446 if (curl_global_initialized)
447 curl_global_cleanup();
448 curl_global_initialized = false;
449 if (body_buf_initialized)
450 curlhelp_freewritebuffer(&body_buf);
451 body_buf_initialized = false;
452 if (header_buf_initialized)
453 curlhelp_freewritebuffer(&header_buf);
454 header_buf_initialized = false;
455 if (put_buf_initialized)
456 curlhelp_freereadbuffer(&put_buf);
457 put_buf_initialized = false;
460 int check_http(void) {
461 int result = STATE_OK;
462 int result_ssl = STATE_OK;
463 int page_len = 0;
464 int i;
465 char *force_host_header = NULL;
466 struct curl_slist *host = NULL;
467 char addrstr[DEFAULT_BUFFER_SIZE / 2];
468 char dnscache[DEFAULT_BUFFER_SIZE];
470 /* initialize curl */
471 if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK)
472 die(STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n");
473 curl_global_initialized = true;
475 if ((curl = curl_easy_init()) == NULL) {
476 die(STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n");
478 curl_easy_initialized = true;
480 /* register cleanup function to shut down libcurl properly */
481 atexit(cleanup);
483 if (verbose >= 1)
484 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_VERBOSE, 1), "CURLOPT_VERBOSE");
486 /* print everything on stdout like check_http would do */
487 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_STDERR, stdout), "CURLOPT_STDERR");
489 if (automatic_decompression)
490 #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6)
491 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""), "CURLOPT_ACCEPT_ENCODING");
492 #else
493 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_ENCODING, ""), "CURLOPT_ENCODING");
494 #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6) */
496 /* initialize buffer for body of the answer */
497 if (curlhelp_initwritebuffer(&body_buf) < 0)
498 die(STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n");
499 body_buf_initialized = true;
500 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback),
501 "CURLOPT_WRITEFUNCTION");
502 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&body_buf), "CURLOPT_WRITEDATA");
504 /* initialize buffer for header of the answer */
505 if (curlhelp_initwritebuffer(&header_buf) < 0)
506 die(STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for header\n");
507 header_buf_initialized = true;
508 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback),
509 "CURLOPT_HEADERFUNCTION");
510 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_WRITEHEADER, (void *)&header_buf), "CURLOPT_WRITEHEADER");
512 /* set the error buffer */
513 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf), "CURLOPT_ERRORBUFFER");
515 /* set timeouts */
516 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, socket_timeout), "CURLOPT_CONNECTTIMEOUT");
517 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_TIMEOUT, socket_timeout), "CURLOPT_TIMEOUT");
519 /* enable haproxy protocol */
520 if (haproxy_protocol) {
521 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HAPROXYPROTOCOL, 1L), "CURLOPT_HAPROXYPROTOCOL");
524 // fill dns resolve cache to make curl connect to the given server_address instead of the host_name, only required for ssl, because we
525 // use the host_name later on to make SNI happy
526 if (use_ssl && host_name != NULL) {
527 if ((res = lookup_host(server_address, addrstr, DEFAULT_BUFFER_SIZE / 2)) != 0) {
528 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Unable to lookup IP address for '%s': getaddrinfo returned %d - %d"), server_address, res,
529 gai_strerror(res));
530 die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
532 snprintf(dnscache, DEFAULT_BUFFER_SIZE, "%s:%d:%s", host_name, server_port, addrstr);
533 host = curl_slist_append(NULL, dnscache);
534 curl_easy_setopt(curl, CURLOPT_RESOLVE, host);
535 if (verbose >= 1)
536 printf("* curl CURLOPT_RESOLVE: %s\n", dnscache);
539 // If server_address is an IPv6 address it must be surround by square brackets
540 struct in6_addr tmp_in_addr;
541 if (inet_pton(AF_INET6, server_address, &tmp_in_addr) == 1) {
542 char *new_server_address = malloc(strlen(server_address) + 3);
543 if (new_server_address == NULL) {
544 die(STATE_UNKNOWN, "HTTP UNKNOWN - Unable to allocate memory\n");
546 snprintf(new_server_address, strlen(server_address) + 3, "[%s]", server_address);
547 free(server_address);
548 server_address = new_server_address;
551 /* compose URL: use the address we want to connect to, set Host: header later */
552 snprintf(url, DEFAULT_BUFFER_SIZE, "%s://%s:%d%s", use_ssl ? "https" : "http",
553 (use_ssl & (host_name != NULL)) ? host_name : server_address, server_port, server_url);
555 if (verbose >= 1)
556 printf("* curl CURLOPT_URL: %s\n", url);
557 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_URL, url), "CURLOPT_URL");
559 /* extract proxy information for legacy proxy https requests */
560 if (!strcmp(http_method, "CONNECT") || strstr(server_url, "http") == server_url) {
561 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_PROXY, server_address), "CURLOPT_PROXY");
562 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_PROXYPORT, (long)server_port), "CURLOPT_PROXYPORT");
563 if (verbose >= 2)
564 printf("* curl CURLOPT_PROXY: %s:%d\n", server_address, server_port);
565 http_method = "GET";
566 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_URL, server_url), "CURLOPT_URL");
569 /* disable body for HEAD request */
570 if (http_method && !strcmp(http_method, "HEAD")) {
571 no_body = true;
574 /* set HTTP protocol version */
575 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, curl_http_version), "CURLOPT_HTTP_VERSION");
577 /* set HTTP method */
578 if (http_method) {
579 if (!strcmp(http_method, "POST"))
580 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_POST, 1), "CURLOPT_POST");
581 else if (!strcmp(http_method, "PUT"))
582 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_UPLOAD, 1), "CURLOPT_UPLOAD");
583 else
584 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method), "CURLOPT_CUSTOMREQUEST");
587 /* check if Host header is explicitly set in options */
588 if (http_opt_headers_count) {
589 for (i = 0; i < http_opt_headers_count; i++) {
590 if (strncmp(http_opt_headers[i], "Host:", 5) == 0) {
591 force_host_header = http_opt_headers[i];
596 /* set hostname (virtual hosts), not needed if CURLOPT_CONNECT_TO is used, but left in anyway */
597 if (host_name != NULL && force_host_header == NULL) {
598 if ((virtual_port != HTTP_PORT && !use_ssl) || (virtual_port != HTTPS_PORT && use_ssl)) {
599 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s:%d", host_name, virtual_port);
600 } else {
601 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s", host_name);
603 header_list = curl_slist_append(header_list, http_header);
606 /* always close connection, be nice to servers */
607 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Connection: close");
608 header_list = curl_slist_append(header_list, http_header);
610 /* attach additional headers supplied by the user */
611 /* optionally send any other header tag */
612 if (http_opt_headers_count) {
613 for (i = 0; i < http_opt_headers_count; i++) {
614 header_list = curl_slist_append(header_list, http_opt_headers[i]);
616 /* This cannot be free'd here because a redirection will then try to access this and segfault */
617 /* Covered in a testcase in tests/check_http.t */
618 /* free(http_opt_headers); */
621 /* set HTTP headers */
622 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list), "CURLOPT_HTTPHEADER");
624 #ifdef LIBCURL_FEATURE_SSL
626 /* set SSL version, warn about insecure or unsupported versions */
627 if (use_ssl) {
628 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSLVERSION, ssl_version), "CURLOPT_SSLVERSION");
631 /* client certificate and key to present to server (SSL) */
632 if (client_cert)
633 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSLCERT, client_cert), "CURLOPT_SSLCERT");
634 if (client_privkey)
635 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSLKEY, client_privkey), "CURLOPT_SSLKEY");
636 if (ca_cert) {
637 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO");
639 if (ca_cert || verify_peer_and_host) {
640 /* per default if we have a CA verify both the peer and the
641 * hostname in the certificate, can be switched off later */
642 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER");
643 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST");
644 } else {
645 /* backward-compatible behaviour, be tolerant in checks
646 * TODO: depending on more options have aspects we want
647 * to be less tolerant about ssl verfications
649 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0), "CURLOPT_SSL_VERIFYPEER");
650 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0), "CURLOPT_SSL_VERIFYHOST");
653 /* detect SSL library used by libcurl */
654 ssl_library = curlhelp_get_ssl_library();
656 /* try hard to get a stack of certificates to verify against */
657 if (check_cert) {
658 # if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1)
659 /* inform curl to report back certificates */
660 switch (ssl_library) {
661 case CURLHELP_SSL_LIBRARY_OPENSSL:
662 case CURLHELP_SSL_LIBRARY_LIBRESSL:
663 /* set callback to extract certificate with OpenSSL context function (works with
664 * OpenSSL-style libraries only!) */
665 # ifdef USE_OPENSSL
666 /* libcurl and monitoring plugins built with OpenSSL, good */
667 add_sslctx_verify_fun = true;
668 is_openssl_callback = true;
669 # endif /* USE_OPENSSL */
670 /* libcurl is built with OpenSSL, monitoring plugins, so falling
671 * back to manually extracting certificate information */
672 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
673 break;
675 case CURLHELP_SSL_LIBRARY_NSS:
676 # if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
677 /* NSS: support for CERTINFO is implemented since 7.34.0 */
678 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
679 # else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
680 die(STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n",
681 curlhelp_get_ssl_library_string(ssl_library));
682 # endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
683 break;
685 case CURLHELP_SSL_LIBRARY_GNUTLS:
686 # if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0)
687 /* GnuTLS: support for CERTINFO is implemented since 7.42.0 */
688 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
689 # else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */
690 die(STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n",
691 curlhelp_get_ssl_library_string(ssl_library));
692 # endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */
693 break;
695 case CURLHELP_SSL_LIBRARY_UNKNOWN:
696 default:
697 die(STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (unknown SSL library '%s', must implement first)\n",
698 curlhelp_get_ssl_library_string(ssl_library));
699 break;
701 # else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */
702 /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */
703 if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL || ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL)
704 add_sslctx_verify_fun = true;
705 else
706 die(STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (no CURLOPT_SSL_CTX_FUNCTION, no OpenSSL library or libcurl "
707 "too old and has no CURLOPT_CERTINFO)\n");
708 # endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */
711 # if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 10, 6) /* required for CURLOPT_SSL_CTX_FUNCTION */
712 // ssl ctx function is not available with all ssl backends
713 if (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, NULL) != CURLE_UNKNOWN_OPTION)
714 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION");
715 # endif
717 #endif /* LIBCURL_FEATURE_SSL */
719 /* set default or user-given user agent identification */
720 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent), "CURLOPT_USERAGENT");
722 /* proxy-authentication */
723 if (strcmp(proxy_auth, ""))
724 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, proxy_auth), "CURLOPT_PROXYUSERPWD");
726 /* authentication */
727 if (strcmp(user_auth, ""))
728 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_USERPWD, user_auth), "CURLOPT_USERPWD");
730 /* TODO: parameter auth method, bitfield of following methods:
731 * CURLAUTH_BASIC (default)
732 * CURLAUTH_DIGEST
733 * CURLAUTH_DIGEST_IE
734 * CURLAUTH_NEGOTIATE
735 * CURLAUTH_NTLM
736 * CURLAUTH_NTLM_WB
738 * convenience tokens for typical sets of methods:
739 * CURLAUTH_ANYSAFE: most secure, without BASIC
740 * or CURLAUTH_ANY: most secure, even BASIC if necessary
742 * handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST ), "CURLOPT_HTTPAUTH");
745 /* handle redirections */
746 if (onredirect == STATE_DEPENDENT) {
747 if (followmethod == FOLLOW_LIBCURL) {
748 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1), "CURLOPT_FOLLOWLOCATION");
750 /* default -1 is infinite, not good, could lead to zombie plugins!
751 Setting it to one bigger than maximal limit to handle errors nicely below
753 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_MAXREDIRS, max_depth + 1), "CURLOPT_MAXREDIRS");
755 /* for now allow only http and https (we are a http(s) check plugin in the end) */
756 #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 85, 0)
757 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https"),
758 "CURLOPT_REDIR_PROTOCOLS_STR");
759 #elif LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4)
760 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS),
761 "CURLOPT_REDIRECT_PROTOCOLS");
762 #endif
764 /* TODO: handle the following aspects of redirection, make them
765 * command line options too later:
766 CURLOPT_POSTREDIR: method switch
767 CURLINFO_REDIRECT_URL: custom redirect option
768 CURLOPT_REDIRECT_PROTOCOLS: allow people to step outside safe protocols
769 CURLINFO_REDIRECT_COUNT: get the number of redirects, print it, maybe a range option here is nice like for expected page size?
771 } else {
772 /* old style redirection is handled below */
776 /* no-body */
777 if (no_body)
778 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_NOBODY, 1), "CURLOPT_NOBODY");
780 /* IPv4 or IPv6 forced DNS resolution */
781 if (address_family == AF_UNSPEC)
782 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER),
783 "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_WHATEVER)");
784 else if (address_family == AF_INET)
785 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4),
786 "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V4)");
787 #if defined(USE_IPV6) && defined(LIBCURL_FEATURE_IPV6)
788 else if (address_family == AF_INET6)
789 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6),
790 "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V6)");
791 #endif
793 /* either send http POST data (any data, not only POST)*/
794 if (!strcmp(http_method, "POST") || !strcmp(http_method, "PUT")) {
795 /* set content of payload for POST and PUT */
796 if (http_content_type) {
797 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Content-Type: %s", http_content_type);
798 header_list = curl_slist_append(header_list, http_header);
800 /* NULL indicates "HTTP Continue" in libcurl, provide an empty string
801 * in case of no POST/PUT data */
802 if (!http_post_data)
803 http_post_data = "";
804 if (!strcmp(http_method, "POST")) {
805 /* POST method, set payload with CURLOPT_POSTFIELDS */
806 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_POSTFIELDS, http_post_data), "CURLOPT_POSTFIELDS");
807 } else if (!strcmp(http_method, "PUT")) {
808 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_READFUNCTION, (curl_read_callback)curlhelp_buffer_read_callback),
809 "CURLOPT_READFUNCTION");
810 if (curlhelp_initreadbuffer(&put_buf, http_post_data, strlen(http_post_data)) < 0)
811 die(STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating read buffer for PUT\n");
812 put_buf_initialized = true;
813 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_READDATA, (void *)&put_buf), "CURLOPT_READDATA");
814 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_INFILESIZE, (curl_off_t)strlen(http_post_data)),
815 "CURLOPT_INFILESIZE");
819 /* cookie handling */
820 if (cookie_jar_file != NULL) {
821 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookie_jar_file), "CURLOPT_COOKIEJAR");
822 handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookie_jar_file), "CURLOPT_COOKIEFILE");
825 /* do the request */
826 res = curl_easy_perform(curl);
828 if (verbose >= 2 && http_post_data)
829 printf("**** REQUEST CONTENT ****\n%s\n", http_post_data);
831 /* free header and server IP resolve lists, we don't need it anymore */
832 curl_slist_free_all(header_list);
833 header_list = NULL;
834 curl_slist_free_all(server_ips);
835 server_ips = NULL;
836 if (host) {
837 curl_slist_free_all(host);
838 host = NULL;
841 /* Curl errors, result in critical Nagios state */
842 if (res != CURLE_OK) {
843 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: cURL returned %d - %s"), server_port,
844 res, errbuf[0] ? errbuf : curl_easy_strerror(res));
845 die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
848 /* certificate checks */
849 #ifdef LIBCURL_FEATURE_SSL
850 if (use_ssl) {
851 if (check_cert) {
852 if (is_openssl_callback) {
853 # ifdef USE_OPENSSL
854 /* check certificate with OpenSSL functions, curl has been built against OpenSSL
855 * and we actually have OpenSSL in the monitoring tools
857 result_ssl = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit);
858 if (!continue_after_check_cert) {
859 return result_ssl;
861 # else /* USE_OPENSSL */
862 die(STATE_CRITICAL,
863 "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL callback used and not linked against OpenSSL\n");
864 # endif /* USE_OPENSSL */
865 } else {
866 int i;
867 struct curl_slist *slist;
869 cert_ptr.to_info = NULL;
870 res = curl_easy_getinfo(curl, CURLINFO_CERTINFO, &cert_ptr.to_info);
871 if (!res && cert_ptr.to_info) {
872 # ifdef USE_OPENSSL
873 /* We have no OpenSSL in libcurl, but we can use OpenSSL for X509 cert parsing
874 * We only check the first certificate and assume it's the one of the server
876 const char *raw_cert = NULL;
877 for (i = 0; i < cert_ptr.to_certinfo->num_of_certs; i++) {
878 for (slist = cert_ptr.to_certinfo->certinfo[i]; slist; slist = slist->next) {
879 if (verbose >= 2)
880 printf("%d ** %s\n", i, slist->data);
881 if (strncmp(slist->data, "Cert:", 5) == 0) {
882 raw_cert = &slist->data[5];
883 goto GOT_FIRST_CERT;
887 GOT_FIRST_CERT:
888 if (!raw_cert) {
889 snprintf(msg, DEFAULT_BUFFER_SIZE,
890 _("Cannot retrieve certificates from CERTINFO information - certificate data was empty"));
891 die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
893 BIO *cert_BIO = BIO_new(BIO_s_mem());
894 BIO_write(cert_BIO, raw_cert, strlen(raw_cert));
895 cert = PEM_read_bio_X509(cert_BIO, NULL, NULL, NULL);
896 if (!cert) {
897 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Cannot read certificate from CERTINFO information - BIO error"));
898 die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
900 BIO_free(cert_BIO);
901 result_ssl = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit);
902 if (!continue_after_check_cert) {
903 return result_ssl;
905 # else /* USE_OPENSSL */
906 /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our disposal,
907 * so we use the libcurl CURLINFO data
909 result_ssl = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit);
910 if (!continue_after_check_cert) {
911 return result_ssl;
913 # endif /* USE_OPENSSL */
914 } else {
915 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates - cURL returned %d - %s"), res,
916 curl_easy_strerror(res));
917 die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
922 #endif /* LIBCURL_FEATURE_SSL */
924 /* we got the data and we executed the request in a given time, so we can append
925 * performance data to the answer always
927 handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time), "CURLINFO_TOTAL_TIME");
928 page_len = get_content_length(&header_buf, &body_buf);
929 if (show_extended_perfdata) {
930 handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &time_connect), "CURLINFO_CONNECT_TIME");
931 handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &time_appconnect), "CURLINFO_APPCONNECT_TIME");
932 handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &time_headers), "CURLINFO_PRETRANSFER_TIME");
933 handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &time_firstbyte),
934 "CURLINFO_STARTTRANSFER_TIME");
935 snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s %s %s %s %s %s", perfd_time(total_time), perfd_size(page_len),
936 perfd_time_connect(time_connect), use_ssl ? perfd_time_ssl(time_appconnect - time_connect) : "",
937 perfd_time_headers(time_headers - time_appconnect), perfd_time_firstbyte(time_firstbyte - time_headers),
938 perfd_time_transfer(total_time - time_firstbyte));
939 } else {
940 snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s", perfd_time(total_time), perfd_size(page_len));
943 /* return a CRITICAL status if we couldn't read any data */
944 if (strlen(header_buf.buf) == 0 && strlen(body_buf.buf) == 0)
945 die(STATE_CRITICAL, _("HTTP CRITICAL - No header received from host\n"));
947 /* get status line of answer, check sanity of HTTP code */
948 if (curlhelp_parse_statusline(header_buf.buf, &status_line) < 0) {
949 snprintf(msg, DEFAULT_BUFFER_SIZE, "Unparsable status line in %.3g seconds response time|%s\n", total_time, perfstring);
950 /* we cannot know the major/minor version here for sure as we cannot parse the first line */
951 die(STATE_CRITICAL, "HTTP CRITICAL HTTP/x.x %ld unknown - %s", code, msg);
953 status_line_initialized = true;
955 /* get result code from cURL */
956 handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE");
957 if (verbose >= 2)
958 printf("* curl CURLINFO_RESPONSE_CODE is %ld\n", code);
960 /* print status line, header, body if verbose */
961 if (verbose >= 2) {
962 printf("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header_buf.buf, (no_body ? " [[ skipped ]]" : body_buf.buf));
965 /* make sure the status line matches the response we are looking for */
966 if (!expected_statuscode(status_line.first_line, server_expect)) {
967 if (server_port == HTTP_PORT)
968 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host: %s\n"), status_line.first_line);
969 else
970 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: %s\n"), server_port,
971 status_line.first_line);
972 die(STATE_CRITICAL, "HTTP CRITICAL - %s%s%s", msg, show_body ? "\n" : "", show_body ? body_buf.buf : "");
975 if (server_expect_yn) {
976 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Status line output matched \"%s\" - "), server_expect);
977 if (verbose)
978 printf("%s\n", msg);
979 result = STATE_OK;
980 } else {
981 /* illegal return codes result in a critical state */
982 if (code >= 600 || code < 100) {
983 die(STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%d, %.40s)\n"), status_line.http_code, status_line.msg);
984 /* server errors result in a critical state */
985 } else if (code >= 500) {
986 result = STATE_CRITICAL;
987 /* client errors result in a warning state */
988 } else if (code >= 400) {
989 result = STATE_WARNING;
990 /* check redirected page if specified */
991 } else if (code >= 300) {
992 if (onredirect == STATE_DEPENDENT) {
993 if (followmethod == FOLLOW_LIBCURL) {
994 code = status_line.http_code;
995 } else {
996 /* old check_http style redirection, if we come
997 * back here, we are in the same status as with
998 * the libcurl method
1000 redir(&header_buf);
1002 } else {
1003 /* this is a specific code in the command line to
1004 * be returned when a redirection is encountered
1007 result = max_state_alt(onredirect, result);
1008 /* all other codes are considered ok */
1009 } else {
1010 result = STATE_OK;
1014 /* libcurl redirection internally, handle error states here */
1015 if (followmethod == FOLLOW_LIBCURL) {
1016 handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_REDIRECT_COUNT, &redir_depth), "CURLINFO_REDIRECT_COUNT");
1017 if (verbose >= 2)
1018 printf(_("* curl LIBINFO_REDIRECT_COUNT is %d\n"), redir_depth);
1019 if (redir_depth > max_depth) {
1020 snprintf(msg, DEFAULT_BUFFER_SIZE, "maximum redirection depth %d exceeded in libcurl", max_depth);
1021 die(STATE_WARNING, "HTTP WARNING - %s", msg);
1025 /* check status codes, set exit status accordingly */
1026 if (status_line.http_code != code) {
1027 die(STATE_CRITICAL, _("HTTP CRITICAL %s %d %s - different HTTP codes (cUrl has %ld)\n"),
1028 string_statuscode(status_line.http_major, status_line.http_minor), status_line.http_code, status_line.msg, code);
1031 if (maximum_age >= 0) {
1032 result = max_state_alt(check_document_dates(&header_buf, &msg), result);
1035 /* Page and Header content checks go here */
1037 if (strlen(header_expect)) {
1038 if (!strstr(header_buf.buf, header_expect)) {
1040 strncpy(&output_header_search[0], header_expect, sizeof(output_header_search));
1042 if (output_header_search[sizeof(output_header_search) - 1] != '\0') {
1043 bcopy("...", &output_header_search[sizeof(output_header_search) - 4], 4);
1046 char tmp[DEFAULT_BUFFER_SIZE];
1048 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sheader '%s' not found on '%s://%s:%d%s', "), msg, output_header_search,
1049 use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url);
1051 strcpy(msg, tmp);
1053 result = STATE_CRITICAL;
1057 if (strlen(string_expect)) {
1058 if (!strstr(body_buf.buf, string_expect)) {
1060 strncpy(&output_string_search[0], string_expect, sizeof(output_string_search));
1062 if (output_string_search[sizeof(output_string_search) - 1] != '\0') {
1063 bcopy("...", &output_string_search[sizeof(output_string_search) - 4], 4);
1066 char tmp[DEFAULT_BUFFER_SIZE];
1068 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sstring '%s' not found on '%s://%s:%d%s', "), msg, output_string_search,
1069 use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url);
1071 strcpy(msg, tmp);
1073 result = STATE_CRITICAL;
1077 if (strlen(regexp)) {
1078 errcode = regexec(&preg, body_buf.buf, REGS, pmatch, 0);
1079 if ((errcode == 0 && !invert_regex) || (errcode == REG_NOMATCH && invert_regex)) {
1080 /* OK - No-op to avoid changing the logic around it */
1081 result = max_state_alt(STATE_OK, result);
1082 } else if ((errcode == REG_NOMATCH && !invert_regex) || (errcode == 0 && invert_regex)) {
1083 if (!invert_regex) {
1084 char tmp[DEFAULT_BUFFER_SIZE];
1086 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spattern not found, "), msg);
1087 strcpy(msg, tmp);
1089 } else {
1090 char tmp[DEFAULT_BUFFER_SIZE];
1092 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spattern found, "), msg);
1093 strcpy(msg, tmp);
1095 result = state_regex;
1096 } else {
1097 regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER);
1099 char tmp[DEFAULT_BUFFER_SIZE];
1101 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sExecute Error: %s, "), msg, errbuf);
1102 strcpy(msg, tmp);
1103 result = STATE_UNKNOWN;
1107 /* make sure the page is of an appropriate size */
1108 if ((max_page_len > 0) && (page_len > max_page_len)) {
1109 char tmp[DEFAULT_BUFFER_SIZE];
1111 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spage size %d too large, "), msg, page_len);
1113 strcpy(msg, tmp);
1115 result = max_state_alt(STATE_WARNING, result);
1117 } else if ((min_page_len > 0) && (page_len < min_page_len)) {
1118 char tmp[DEFAULT_BUFFER_SIZE];
1120 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spage size %d too small, "), msg, page_len);
1121 strcpy(msg, tmp);
1122 result = max_state_alt(STATE_WARNING, result);
1125 /* -w, -c: check warning and critical level */
1126 result = max_state_alt(get_status(total_time, thlds), result);
1128 /* Cut-off trailing characters */
1129 if (strlen(msg) >= 2) {
1130 if (msg[strlen(msg) - 2] == ',')
1131 msg[strlen(msg) - 2] = '\0';
1132 else
1133 msg[strlen(msg) - 3] = '\0';
1136 /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */
1137 die(max_state_alt(result, result_ssl), "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n%s%s", state_text(result),
1138 string_statuscode(status_line.http_major, status_line.http_minor), status_line.http_code, status_line.msg,
1139 strlen(msg) > 0 ? " - " : "", msg, page_len, total_time, (display_html ? "</A>" : ""), perfstring, (show_body ? body_buf.buf : ""),
1140 (show_body ? "\n" : ""));
1142 return max_state_alt(result, result_ssl);
1145 int uri_strcmp(const UriTextRangeA range, const char *s) {
1146 if (!range.first)
1147 return -1;
1148 if ((size_t)(range.afterLast - range.first) < strlen(s))
1149 return -1;
1150 return strncmp(s, range.first, min((size_t)(range.afterLast - range.first), strlen(s)));
1153 char *uri_string(const UriTextRangeA range, char *buf, size_t buflen) {
1154 if (!range.first)
1155 return "(null)";
1156 strncpy(buf, range.first, max(buflen - 1, (size_t)(range.afterLast - range.first)));
1157 buf[max(buflen - 1, (size_t)(range.afterLast - range.first))] = '\0';
1158 buf[range.afterLast - range.first] = '\0';
1159 return buf;
1162 void redir(curlhelp_write_curlbuf *header_buf) {
1163 char *location = NULL;
1164 curlhelp_statusline status_line;
1165 struct phr_header headers[255];
1166 size_t nof_headers = 255;
1167 size_t msglen;
1168 char buf[DEFAULT_BUFFER_SIZE];
1169 char ipstr[INET_ADDR_MAX_SIZE];
1170 int new_port;
1171 char *new_host;
1172 char *new_url;
1174 int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major, &status_line.http_minor,
1175 &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0);
1177 if (res == -1) {
1178 die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n"));
1181 location = get_header_value(headers, nof_headers, "location");
1183 if (verbose >= 2)
1184 printf(_("* Seen redirect location %s\n"), location);
1186 if (++redir_depth > max_depth)
1187 die(STATE_WARNING, _("HTTP WARNING - maximum redirection depth %d exceeded - %s%s\n"), max_depth, location,
1188 (display_html ? "</A>" : ""));
1190 UriParserStateA state;
1191 UriUriA uri;
1192 state.uri = &uri;
1193 if (uriParseUriA(&state, location) != URI_SUCCESS) {
1194 if (state.errorCode == URI_ERROR_SYNTAX) {
1195 die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not parse redirect location '%s'%s\n"), location, (display_html ? "</A>" : ""));
1196 } else if (state.errorCode == URI_ERROR_MALLOC) {
1197 die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n"));
1201 if (verbose >= 2) {
1202 printf(_("** scheme: %s\n"), uri_string(uri.scheme, buf, DEFAULT_BUFFER_SIZE));
1203 printf(_("** host: %s\n"), uri_string(uri.hostText, buf, DEFAULT_BUFFER_SIZE));
1204 printf(_("** port: %s\n"), uri_string(uri.portText, buf, DEFAULT_BUFFER_SIZE));
1205 if (uri.hostData.ip4) {
1206 inet_ntop(AF_INET, uri.hostData.ip4->data, ipstr, sizeof(ipstr));
1207 printf(_("** IPv4: %s\n"), ipstr);
1209 if (uri.hostData.ip6) {
1210 inet_ntop(AF_INET, uri.hostData.ip6->data, ipstr, sizeof(ipstr));
1211 printf(_("** IPv6: %s\n"), ipstr);
1213 if (uri.pathHead) {
1214 printf(_("** path: "));
1215 const UriPathSegmentA *p = uri.pathHead;
1216 for (; p; p = p->next) {
1217 printf("/%s", uri_string(p->text, buf, DEFAULT_BUFFER_SIZE));
1219 puts("");
1221 if (uri.query.first) {
1222 printf(_("** query: %s\n"), uri_string(uri.query, buf, DEFAULT_BUFFER_SIZE));
1224 if (uri.fragment.first) {
1225 printf(_("** fragment: %s\n"), uri_string(uri.fragment, buf, DEFAULT_BUFFER_SIZE));
1229 if (uri.scheme.first) {
1230 if (!uri_strcmp(uri.scheme, "https"))
1231 use_ssl = true;
1232 else
1233 use_ssl = false;
1236 /* we do a sloppy test here only, because uriparser would have failed
1237 * above, if the port would be invalid, we just check for MAX_PORT
1239 if (uri.portText.first) {
1240 new_port = atoi(uri_string(uri.portText, buf, DEFAULT_BUFFER_SIZE));
1241 } else {
1242 new_port = HTTP_PORT;
1243 if (use_ssl)
1244 new_port = HTTPS_PORT;
1246 if (new_port > MAX_PORT)
1247 die(STATE_UNKNOWN, _("HTTP UNKNOWN - Redirection to port above %d - %s%s\n"), MAX_PORT, location, display_html ? "</A>" : "");
1249 /* by RFC 7231 relative URLs in Location should be taken relative to
1250 * the original URL, so we try to form a new absolute URL here
1252 if (!uri.scheme.first && !uri.hostText.first) {
1253 new_host = strdup(host_name ? host_name : server_address);
1254 new_port = server_port;
1255 if (use_ssl)
1256 uri_string(uri.scheme, "https", DEFAULT_BUFFER_SIZE);
1257 } else {
1258 new_host = strdup(uri_string(uri.hostText, buf, DEFAULT_BUFFER_SIZE));
1261 /* compose new path */
1262 /* TODO: handle fragments and query part of URL */
1263 new_url = (char *)calloc(1, DEFAULT_BUFFER_SIZE);
1264 if (uri.pathHead) {
1265 const UriPathSegmentA *p = uri.pathHead;
1266 for (; p; p = p->next) {
1267 strncat(new_url, "/", DEFAULT_BUFFER_SIZE);
1268 strncat(new_url, uri_string(p->text, buf, DEFAULT_BUFFER_SIZE), DEFAULT_BUFFER_SIZE - 1);
1272 if (server_port == new_port && !strncmp(server_address, new_host, MAX_IPV4_HOSTLENGTH) &&
1273 (host_name && !strncmp(host_name, new_host, MAX_IPV4_HOSTLENGTH)) && !strcmp(server_url, new_url))
1274 die(STATE_CRITICAL, _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"), use_ssl ? "https" : "http",
1275 new_host, new_port, new_url, (display_html ? "</A>" : ""));
1277 /* set new values for redirected request */
1279 if (!(followsticky & STICKY_HOST)) {
1280 free(server_address);
1281 server_address = strndup(new_host, MAX_IPV4_HOSTLENGTH);
1283 if (!(followsticky & STICKY_PORT)) {
1284 server_port = (unsigned short)new_port;
1287 free(host_name);
1288 host_name = strndup(new_host, MAX_IPV4_HOSTLENGTH);
1290 /* reset virtual port */
1291 virtual_port = server_port;
1293 free(new_host);
1294 free(server_url);
1295 server_url = new_url;
1297 uriFreeUriMembersA(&uri);
1299 if (verbose)
1300 printf(_("Redirection to %s://%s:%d%s\n"), use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port,
1301 server_url);
1303 /* TODO: the hash component MUST be taken from the original URL and
1304 * attached to the URL in Location
1307 cleanup();
1308 check_http();
1311 /* check whether a file exists */
1312 void test_file(char *path) {
1313 if (access(path, R_OK) == 0)
1314 return;
1315 usage2(_("file does not exist or is not readable"), path);
1318 bool process_arguments(int argc, char **argv) {
1319 char *p;
1320 int c = 1;
1321 char *temp;
1323 enum {
1324 INVERT_REGEX = CHAR_MAX + 1,
1325 SNI_OPTION,
1326 MAX_REDIRS_OPTION,
1327 CONTINUE_AFTER_CHECK_CERT,
1328 CA_CERT_OPTION,
1329 HTTP_VERSION_OPTION,
1330 AUTOMATIC_DECOMPRESSION,
1331 COOKIE_JAR,
1332 HAPROXY_PROTOCOL,
1333 STATE_REGEX
1336 int option = 0;
1337 int got_plus = 0;
1338 static struct option longopts[] = {STD_LONG_OPTS,
1339 {"link", no_argument, 0, 'L'},
1340 {"nohtml", no_argument, 0, 'n'},
1341 {"ssl", optional_argument, 0, 'S'},
1342 {"sni", no_argument, 0, SNI_OPTION},
1343 {"post", required_argument, 0, 'P'},
1344 {"method", required_argument, 0, 'j'},
1345 {"IP-address", required_argument, 0, 'I'},
1346 {"url", required_argument, 0, 'u'},
1347 {"port", required_argument, 0, 'p'},
1348 {"authorization", required_argument, 0, 'a'},
1349 {"proxy-authorization", required_argument, 0, 'b'},
1350 {"header-string", required_argument, 0, 'd'},
1351 {"string", required_argument, 0, 's'},
1352 {"expect", required_argument, 0, 'e'},
1353 {"regex", required_argument, 0, 'r'},
1354 {"ereg", required_argument, 0, 'r'},
1355 {"eregi", required_argument, 0, 'R'},
1356 {"linespan", no_argument, 0, 'l'},
1357 {"onredirect", required_argument, 0, 'f'},
1358 {"certificate", required_argument, 0, 'C'},
1359 {"client-cert", required_argument, 0, 'J'},
1360 {"private-key", required_argument, 0, 'K'},
1361 {"ca-cert", required_argument, 0, CA_CERT_OPTION},
1362 {"verify-cert", no_argument, 0, 'D'},
1363 {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT},
1364 {"useragent", required_argument, 0, 'A'},
1365 {"header", required_argument, 0, 'k'},
1366 {"no-body", no_argument, 0, 'N'},
1367 {"max-age", required_argument, 0, 'M'},
1368 {"content-type", required_argument, 0, 'T'},
1369 {"pagesize", required_argument, 0, 'm'},
1370 {"invert-regex", no_argument, NULL, INVERT_REGEX},
1371 {"state-regex", required_argument, 0, STATE_REGEX},
1372 {"use-ipv4", no_argument, 0, '4'},
1373 {"use-ipv6", no_argument, 0, '6'},
1374 {"extended-perfdata", no_argument, 0, 'E'},
1375 {"show-body", no_argument, 0, 'B'},
1376 {"max-redirs", required_argument, 0, MAX_REDIRS_OPTION},
1377 {"http-version", required_argument, 0, HTTP_VERSION_OPTION},
1378 {"enable-automatic-decompression", no_argument, 0, AUTOMATIC_DECOMPRESSION},
1379 {"cookie-jar", required_argument, 0, COOKIE_JAR},
1380 {"haproxy-protocol", no_argument, 0, HAPROXY_PROTOCOL},
1381 {0, 0, 0, 0}};
1383 if (argc < 2)
1384 return false;
1386 /* support check_http compatible arguments */
1387 for (c = 1; c < argc; c++) {
1388 if (strcmp("-to", argv[c]) == 0)
1389 strcpy(argv[c], "-t");
1390 if (strcmp("-hn", argv[c]) == 0)
1391 strcpy(argv[c], "-H");
1392 if (strcmp("-wt", argv[c]) == 0)
1393 strcpy(argv[c], "-w");
1394 if (strcmp("-ct", argv[c]) == 0)
1395 strcpy(argv[c], "-c");
1396 if (strcmp("-nohtml", argv[c]) == 0)
1397 strcpy(argv[c], "-n");
1400 server_url = strdup(DEFAULT_SERVER_URL);
1402 while (1) {
1403 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:DnlLS::m:M:NEB", longopts, &option);
1404 if (c == -1 || c == EOF || c == 1)
1405 break;
1407 switch (c) {
1408 case 'h':
1409 print_help();
1410 exit(STATE_UNKNOWN);
1411 break;
1412 case 'V':
1413 print_revision(progname, NP_VERSION);
1414 print_curl_version();
1415 exit(STATE_UNKNOWN);
1416 break;
1417 case 'v':
1418 verbose++;
1419 break;
1420 case 't': /* timeout period */
1421 if (!is_intnonneg(optarg))
1422 usage2(_("Timeout interval must be a positive integer"), optarg);
1423 else
1424 socket_timeout = (int)strtol(optarg, NULL, 10);
1425 break;
1426 case 'c': /* critical time threshold */
1427 critical_thresholds = optarg;
1428 break;
1429 case 'w': /* warning time threshold */
1430 warning_thresholds = optarg;
1431 break;
1432 case 'H': /* virtual host */
1433 host_name = strdup(optarg);
1434 if (host_name[0] == '[') {
1435 if ((p = strstr(host_name, "]:")) != NULL) { /* [IPv6]:port */
1436 virtual_port = atoi(p + 2);
1437 /* cut off the port */
1438 host_name_length = strlen(host_name) - strlen(p) - 1;
1439 free(host_name);
1440 host_name = strndup(optarg, host_name_length);
1442 } else if ((p = strchr(host_name, ':')) != NULL && strchr(++p, ':') == NULL) { /* IPv4:port or host:port */
1443 virtual_port = atoi(p);
1444 /* cut off the port */
1445 host_name_length = strlen(host_name) - strlen(p) - 1;
1446 free(host_name);
1447 host_name = strndup(optarg, host_name_length);
1449 break;
1450 case 'I': /* internet address */
1451 server_address = strdup(optarg);
1452 break;
1453 case 'u': /* URL path */
1454 server_url = strdup(optarg);
1455 break;
1456 case 'p': /* Server port */
1457 if (!is_intnonneg(optarg))
1458 usage2(_("Invalid port number, expecting a non-negative number"), optarg);
1459 else {
1460 if (strtol(optarg, NULL, 10) > MAX_PORT)
1461 usage2(_("Invalid port number, supplied port number is too big"), optarg);
1462 server_port = (unsigned short)strtol(optarg, NULL, 10);
1463 specify_port = true;
1465 break;
1466 case 'a': /* authorization info */
1467 strncpy(user_auth, optarg, MAX_INPUT_BUFFER - 1);
1468 user_auth[MAX_INPUT_BUFFER - 1] = 0;
1469 break;
1470 case 'b': /* proxy-authorization info */
1471 strncpy(proxy_auth, optarg, MAX_INPUT_BUFFER - 1);
1472 proxy_auth[MAX_INPUT_BUFFER - 1] = 0;
1473 break;
1474 case 'P': /* HTTP POST data in URL encoded format; ignored if settings already */
1475 if (!http_post_data)
1476 http_post_data = strdup(optarg);
1477 if (!http_method)
1478 http_method = strdup("POST");
1479 break;
1480 case 'j': /* Set HTTP method */
1481 if (http_method)
1482 free(http_method);
1483 http_method = strdup(optarg);
1484 break;
1485 case 'A': /* useragent */
1486 strncpy(user_agent, optarg, DEFAULT_BUFFER_SIZE);
1487 user_agent[DEFAULT_BUFFER_SIZE - 1] = '\0';
1488 break;
1489 case 'k': /* Additional headers */
1490 if (http_opt_headers_count == 0)
1491 http_opt_headers = malloc(sizeof(char *) * (++http_opt_headers_count));
1492 else
1493 http_opt_headers = realloc(http_opt_headers, sizeof(char *) * (++http_opt_headers_count));
1494 http_opt_headers[http_opt_headers_count - 1] = optarg;
1495 break;
1496 case 'L': /* show html link */
1497 display_html = true;
1498 break;
1499 case 'n': /* do not show html link */
1500 display_html = false;
1501 break;
1502 case 'C': /* Check SSL cert validity */
1503 #ifdef LIBCURL_FEATURE_SSL
1504 if ((temp = strchr(optarg, ',')) != NULL) {
1505 *temp = '\0';
1506 if (!is_intnonneg(optarg))
1507 usage2(_("Invalid certificate expiration period"), optarg);
1508 days_till_exp_warn = atoi(optarg);
1509 *temp = ',';
1510 temp++;
1511 if (!is_intnonneg(temp))
1512 usage2(_("Invalid certificate expiration period"), temp);
1513 days_till_exp_crit = atoi(temp);
1514 } else {
1515 days_till_exp_crit = 0;
1516 if (!is_intnonneg(optarg))
1517 usage2(_("Invalid certificate expiration period"), optarg);
1518 days_till_exp_warn = atoi(optarg);
1520 check_cert = true;
1521 goto enable_ssl;
1522 #endif
1523 case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is checked */
1524 #ifdef HAVE_SSL
1525 continue_after_check_cert = true;
1526 break;
1527 #endif
1528 case 'J': /* use client certificate */
1529 #ifdef LIBCURL_FEATURE_SSL
1530 test_file(optarg);
1531 client_cert = optarg;
1532 goto enable_ssl;
1533 #endif
1534 case 'K': /* use client private key */
1535 #ifdef LIBCURL_FEATURE_SSL
1536 test_file(optarg);
1537 client_privkey = optarg;
1538 goto enable_ssl;
1539 #endif
1540 #ifdef LIBCURL_FEATURE_SSL
1541 case CA_CERT_OPTION: /* use CA chain file */
1542 test_file(optarg);
1543 ca_cert = optarg;
1544 goto enable_ssl;
1545 #endif
1546 #ifdef LIBCURL_FEATURE_SSL
1547 case 'D': /* verify peer certificate & host */
1548 verify_peer_and_host = true;
1549 break;
1550 #endif
1551 case 'S': /* use SSL */
1552 #ifdef LIBCURL_FEATURE_SSL
1553 enable_ssl:
1554 use_ssl = true;
1555 /* ssl_version initialized to CURL_SSLVERSION_DEFAULT as a default.
1556 * Only set if it's non-zero. This helps when we include multiple
1557 * parameters, like -S and -C combinations */
1558 ssl_version = CURL_SSLVERSION_DEFAULT;
1559 if (c == 'S' && optarg != NULL) {
1560 char *plus_ptr = strchr(optarg, '+');
1561 if (plus_ptr) {
1562 got_plus = 1;
1563 *plus_ptr = '\0';
1566 if (optarg[0] == '2')
1567 ssl_version = CURL_SSLVERSION_SSLv2;
1568 else if (optarg[0] == '3')
1569 ssl_version = CURL_SSLVERSION_SSLv3;
1570 else if (!strcmp(optarg, "1") || !strcmp(optarg, "1.0"))
1571 # if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1572 ssl_version = CURL_SSLVERSION_TLSv1_0;
1573 # else
1574 ssl_version = CURL_SSLVERSION_DEFAULT;
1575 # endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1576 else if (!strcmp(optarg, "1.1"))
1577 # if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1578 ssl_version = CURL_SSLVERSION_TLSv1_1;
1579 # else
1580 ssl_version = CURL_SSLVERSION_DEFAULT;
1581 # endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1582 else if (!strcmp(optarg, "1.2"))
1583 # if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1584 ssl_version = CURL_SSLVERSION_TLSv1_2;
1585 # else
1586 ssl_version = CURL_SSLVERSION_DEFAULT;
1587 # endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1588 else if (!strcmp(optarg, "1.3"))
1589 # if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0)
1590 ssl_version = CURL_SSLVERSION_TLSv1_3;
1591 # else
1592 ssl_version = CURL_SSLVERSION_DEFAULT;
1593 # endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) */
1594 else
1595 usage4(_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2, 1.3 (with optional '+' suffix)"));
1597 # if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0)
1598 if (got_plus) {
1599 switch (ssl_version) {
1600 case CURL_SSLVERSION_TLSv1_3:
1601 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3;
1602 break;
1603 case CURL_SSLVERSION_TLSv1_2:
1604 case CURL_SSLVERSION_TLSv1_1:
1605 case CURL_SSLVERSION_TLSv1_0:
1606 ssl_version |= CURL_SSLVERSION_MAX_DEFAULT;
1607 break;
1609 } else {
1610 switch (ssl_version) {
1611 case CURL_SSLVERSION_TLSv1_3:
1612 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3;
1613 break;
1614 case CURL_SSLVERSION_TLSv1_2:
1615 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_2;
1616 break;
1617 case CURL_SSLVERSION_TLSv1_1:
1618 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_1;
1619 break;
1620 case CURL_SSLVERSION_TLSv1_0:
1621 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_0;
1622 break;
1625 # endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) */
1626 if (verbose >= 2)
1627 printf(_("* Set SSL/TLS version to %d\n"), ssl_version);
1628 if (!specify_port)
1629 server_port = HTTPS_PORT;
1630 break;
1631 #else /* LIBCURL_FEATURE_SSL */
1632 /* -C -J and -K fall through to here without SSL */
1633 usage4(_("Invalid option - SSL is not available"));
1634 break;
1635 case SNI_OPTION: /* --sni is parsed, but ignored, the default is true with libcurl */
1636 use_sni = true;
1637 break;
1638 #endif /* LIBCURL_FEATURE_SSL */
1639 case MAX_REDIRS_OPTION:
1640 if (!is_intnonneg(optarg))
1641 usage2(_("Invalid max_redirs count"), optarg);
1642 else {
1643 max_depth = atoi(optarg);
1645 break;
1646 case 'f': /* onredirect */
1647 if (!strcmp(optarg, "ok"))
1648 onredirect = STATE_OK;
1649 else if (!strcmp(optarg, "warning"))
1650 onredirect = STATE_WARNING;
1651 else if (!strcmp(optarg, "critical"))
1652 onredirect = STATE_CRITICAL;
1653 else if (!strcmp(optarg, "unknown"))
1654 onredirect = STATE_UNKNOWN;
1655 else if (!strcmp(optarg, "follow"))
1656 onredirect = STATE_DEPENDENT;
1657 else if (!strcmp(optarg, "stickyport"))
1658 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST | STICKY_PORT;
1659 else if (!strcmp(optarg, "sticky"))
1660 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST;
1661 else if (!strcmp(optarg, "follow"))
1662 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_NONE;
1663 else if (!strcmp(optarg, "curl"))
1664 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_LIBCURL;
1665 else
1666 usage2(_("Invalid onredirect option"), optarg);
1667 if (verbose >= 2)
1668 printf(_("* Following redirects set to %s\n"), state_text(onredirect));
1669 break;
1670 case 'd': /* string or substring */
1671 strncpy(header_expect, optarg, MAX_INPUT_BUFFER - 1);
1672 header_expect[MAX_INPUT_BUFFER - 1] = 0;
1673 break;
1674 case 's': /* string or substring */
1675 strncpy(string_expect, optarg, MAX_INPUT_BUFFER - 1);
1676 string_expect[MAX_INPUT_BUFFER - 1] = 0;
1677 break;
1678 case 'e': /* string or substring */
1679 strncpy(server_expect, optarg, MAX_INPUT_BUFFER - 1);
1680 server_expect[MAX_INPUT_BUFFER - 1] = 0;
1681 server_expect_yn = 1;
1682 break;
1683 case 'T': /* Content-type */
1684 http_content_type = strdup(optarg);
1685 break;
1686 case 'l': /* linespan */
1687 cflags &= ~REG_NEWLINE;
1688 break;
1689 case 'R': /* regex */
1690 cflags |= REG_ICASE;
1691 // fall through
1692 case 'r': /* regex */
1693 strncpy(regexp, optarg, MAX_RE_SIZE - 1);
1694 regexp[MAX_RE_SIZE - 1] = 0;
1695 errcode = regcomp(&preg, regexp, cflags);
1696 if (errcode != 0) {
1697 (void)regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER);
1698 printf(_("Could Not Compile Regular Expression: %s"), errbuf);
1699 return false;
1701 break;
1702 case INVERT_REGEX:
1703 invert_regex = true;
1704 break;
1705 case STATE_REGEX:
1706 if (!strcasecmp(optarg, "critical"))
1707 state_regex = STATE_CRITICAL;
1708 else if (!strcasecmp(optarg, "warning"))
1709 state_regex = STATE_WARNING;
1710 else
1711 usage2(_("Invalid state-regex option"), optarg);
1712 break;
1713 case '4':
1714 address_family = AF_INET;
1715 break;
1716 case '6':
1717 #if defined(USE_IPV6) && defined(LIBCURL_FEATURE_IPV6)
1718 address_family = AF_INET6;
1719 #else
1720 usage4(_("IPv6 support not available"));
1721 #endif
1722 break;
1723 case 'm': /* min_page_length */
1725 char *tmp;
1726 if (strchr(optarg, ':') != (char *)NULL) {
1727 /* range, so get two values, min:max */
1728 tmp = strtok(optarg, ":");
1729 if (tmp == NULL) {
1730 printf("Bad format: try \"-m min:max\"\n");
1731 exit(STATE_WARNING);
1732 } else
1733 min_page_len = atoi(tmp);
1735 tmp = strtok(NULL, ":");
1736 if (tmp == NULL) {
1737 printf("Bad format: try \"-m min:max\"\n");
1738 exit(STATE_WARNING);
1739 } else
1740 max_page_len = atoi(tmp);
1741 } else
1742 min_page_len = atoi(optarg);
1743 break;
1745 case 'N': /* no-body */
1746 no_body = true;
1747 break;
1748 case 'M': /* max-age */
1750 int L = strlen(optarg);
1751 if (L && optarg[L - 1] == 'm')
1752 maximum_age = atoi(optarg) * 60;
1753 else if (L && optarg[L - 1] == 'h')
1754 maximum_age = atoi(optarg) * 60 * 60;
1755 else if (L && optarg[L - 1] == 'd')
1756 maximum_age = atoi(optarg) * 60 * 60 * 24;
1757 else if (L && (optarg[L - 1] == 's' || isdigit(optarg[L - 1])))
1758 maximum_age = atoi(optarg);
1759 else {
1760 fprintf(stderr, "unparsable max-age: %s\n", optarg);
1761 exit(STATE_WARNING);
1763 if (verbose >= 2)
1764 printf("* Maximal age of document set to %d seconds\n", maximum_age);
1765 } break;
1766 case 'E': /* show extended perfdata */
1767 show_extended_perfdata = true;
1768 break;
1769 case 'B': /* print body content after status line */
1770 show_body = true;
1771 break;
1772 case HTTP_VERSION_OPTION:
1773 curl_http_version = CURL_HTTP_VERSION_NONE;
1774 if (strcmp(optarg, "1.0") == 0) {
1775 curl_http_version = CURL_HTTP_VERSION_1_0;
1776 } else if (strcmp(optarg, "1.1") == 0) {
1777 curl_http_version = CURL_HTTP_VERSION_1_1;
1778 } else if ((strcmp(optarg, "2.0") == 0) || (strcmp(optarg, "2") == 0)) {
1779 #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0)
1780 curl_http_version = CURL_HTTP_VERSION_2_0;
1781 #else
1782 curl_http_version = CURL_HTTP_VERSION_NONE;
1783 #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0) */
1784 } else {
1785 fprintf(stderr, "unknown http-version parameter: %s\n", optarg);
1786 exit(STATE_WARNING);
1788 break;
1789 case AUTOMATIC_DECOMPRESSION:
1790 automatic_decompression = true;
1791 break;
1792 case COOKIE_JAR:
1793 cookie_jar_file = optarg;
1794 break;
1795 case HAPROXY_PROTOCOL:
1796 haproxy_protocol = true;
1797 break;
1798 case '?':
1799 /* print short usage statement if args not parsable */
1800 usage5();
1801 break;
1805 c = optind;
1807 if (server_address == NULL && c < argc)
1808 server_address = strdup(argv[c++]);
1810 if (host_name == NULL && c < argc)
1811 host_name = strdup(argv[c++]);
1813 if (server_address == NULL) {
1814 if (host_name == NULL)
1815 usage4(_("You must specify a server address or host name"));
1816 else
1817 server_address = strdup(host_name);
1820 set_thresholds(&thlds, warning_thresholds, critical_thresholds);
1822 if (critical_thresholds && thlds->critical->end > (double)socket_timeout)
1823 socket_timeout = (int)thlds->critical->end + 1;
1824 if (verbose >= 2)
1825 printf("* Socket timeout set to %ld seconds\n", socket_timeout);
1827 if (http_method == NULL)
1828 http_method = strdup("GET");
1830 if (client_cert && !client_privkey)
1831 usage4(_("If you use a client certificate you must also specify a private key file"));
1833 if (virtual_port == 0)
1834 virtual_port = server_port;
1835 else {
1836 if ((use_ssl && server_port == HTTPS_PORT) || (!use_ssl && server_port == HTTP_PORT))
1837 if (!specify_port)
1838 server_port = virtual_port;
1841 return true;
1844 char *perfd_time(double elapsed_time) {
1845 return fperfdata("time", elapsed_time, "s", thlds->warning ? true : false, thlds->warning ? thlds->warning->end : 0,
1846 thlds->critical ? true : false, thlds->critical ? thlds->critical->end : 0, true, 0, true, socket_timeout);
1849 char *perfd_time_connect(double elapsed_time_connect) {
1850 return fperfdata("time_connect", elapsed_time_connect, "s", false, 0, false, 0, false, 0, true, socket_timeout);
1853 char *perfd_time_ssl(double elapsed_time_ssl) {
1854 return fperfdata("time_ssl", elapsed_time_ssl, "s", false, 0, false, 0, false, 0, true, socket_timeout);
1857 char *perfd_time_headers(double elapsed_time_headers) {
1858 return fperfdata("time_headers", elapsed_time_headers, "s", false, 0, false, 0, false, 0, true, socket_timeout);
1861 char *perfd_time_firstbyte(double elapsed_time_firstbyte) {
1862 return fperfdata("time_firstbyte", elapsed_time_firstbyte, "s", false, 0, false, 0, false, 0, true, socket_timeout);
1865 char *perfd_time_transfer(double elapsed_time_transfer) {
1866 return fperfdata("time_transfer", elapsed_time_transfer, "s", false, 0, false, 0, false, 0, true, socket_timeout);
1869 char *perfd_size(int page_len) {
1870 return perfdata("size", page_len, "B", (min_page_len > 0 ? true : false), min_page_len, (min_page_len > 0 ? true : false), 0, true, 0,
1871 false, 0);
1874 void print_help(void) {
1875 print_revision(progname, NP_VERSION);
1877 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
1878 printf(COPYRIGHT, copyright, email);
1880 printf("%s\n", _("This plugin tests the HTTP service on the specified host. It can test"));
1881 printf("%s\n", _("normal (http) and secure (https) servers, follow redirects, search for"));
1882 printf("%s\n", _("strings and regular expressions, check connection times, and report on"));
1883 printf("%s\n", _("certificate expiration times."));
1884 printf("\n");
1885 printf("%s\n", _("It makes use of libcurl to do so. It tries to be as compatible to check_http"));
1886 printf("%s\n", _("as possible."));
1888 printf("\n\n");
1890 print_usage();
1892 printf(_("NOTE: One or both of -H and -I must be specified"));
1894 printf("\n");
1896 printf(UT_HELP_VRSN);
1897 printf(UT_EXTRA_OPTS);
1899 printf(" %s\n", "-H, --hostname=ADDRESS");
1900 printf(" %s\n", _("Host name argument for servers using host headers (virtual host)"));
1901 printf(" %s\n", _("Append a port to include it in the header (eg: example.com:5000)"));
1902 printf(" %s\n", "-I, --IP-address=ADDRESS");
1903 printf(" %s\n", _("IP address or name (use numeric address if possible to bypass DNS lookup)."));
1904 printf(" %s\n", "-p, --port=INTEGER");
1905 printf(" %s", _("Port number (default: "));
1906 printf("%d)\n", HTTP_PORT);
1908 printf(UT_IPv46);
1910 #ifdef LIBCURL_FEATURE_SSL
1911 printf(" %s\n", "-S, --ssl=VERSION[+]");
1912 printf(" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is optional, and prevents"));
1913 printf(" %s\n", _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,"));
1914 printf(" %s\n", _("1.2 = TLSv1.2, 1.3 = TLSv1.3). With a '+' suffix, newer versions are also accepted."));
1915 printf(" %s\n", _("Note: SSLv2 and SSLv3 are deprecated and are usually disabled in libcurl"));
1916 printf(" %s\n", "--sni");
1917 printf(" %s\n", _("Enable SSL/TLS hostname extension support (SNI)"));
1918 # if LIBCURL_VERSION_NUM >= 0x071801
1919 printf(" %s\n", _("Note: --sni is the default in libcurl as SSLv2 and SSLV3 are deprecated and"));
1920 printf(" %s\n", _(" SNI only really works since TLSv1.0"));
1921 # else
1922 printf(" %s\n", _("Note: SNI is not supported in libcurl before 7.18.1"));
1923 # endif
1924 printf(" %s\n", "-C, --certificate=INTEGER[,INTEGER]");
1925 printf(" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443."));
1926 printf(" %s\n", _("A STATE_WARNING is returned if the certificate has a validity less than the"));
1927 printf(" %s\n", _("first agument's value. If there is a second argument and the certificate's"));
1928 printf(" %s\n", _("validity is less than its value, a STATE_CRITICAL is returned."));
1929 printf(" %s\n", _("(When this option is used the URL is not checked by default. You can use"));
1930 printf(" %s\n", _(" --continue-after-certificate to override this behavior)"));
1931 printf(" %s\n", "--continue-after-certificate");
1932 printf(" %s\n", _("Allows the HTTP check to continue after performing the certificate check."));
1933 printf(" %s\n", _("Does nothing unless -C is used."));
1934 printf(" %s\n", "-J, --client-cert=FILE");
1935 printf(" %s\n", _("Name of file that contains the client certificate (PEM format)"));
1936 printf(" %s\n", _("to be used in establishing the SSL session"));
1937 printf(" %s\n", "-K, --private-key=FILE");
1938 printf(" %s\n", _("Name of file containing the private key (PEM format)"));
1939 printf(" %s\n", _("matching the client certificate"));
1940 printf(" %s\n", "--ca-cert=FILE");
1941 printf(" %s\n", _("CA certificate file to verify peer against"));
1942 printf(" %s\n", "-D, --verify-cert");
1943 printf(" %s\n", _("Verify the peer's SSL certificate and hostname"));
1944 #endif
1946 printf(" %s\n", "-e, --expect=STRING");
1947 printf(" %s\n", _("Comma-delimited list of strings, at least one of them is expected in"));
1948 printf(" %s", _("the first (status) line of the server response (default: "));
1949 printf("%s)\n", HTTP_EXPECT);
1950 printf(" %s\n", _("If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)"));
1951 printf(" %s\n", "-d, --header-string=STRING");
1952 printf(" %s\n", _("String to expect in the response headers"));
1953 printf(" %s\n", "-s, --string=STRING");
1954 printf(" %s\n", _("String to expect in the content"));
1955 printf(" %s\n", "-u, --url=PATH");
1956 printf(" %s\n", _("URL to GET or POST (default: /)"));
1957 printf(" %s\n", "-P, --post=STRING");
1958 printf(" %s\n", _("URL decoded http POST data"));
1959 printf(" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)");
1960 printf(" %s\n", _("Set HTTP method."));
1961 printf(" %s\n", "-N, --no-body");
1962 printf(" %s\n", _("Don't wait for document body: stop reading after headers."));
1963 printf(" %s\n", _("(Note that this still does an HTTP GET or POST, not a HEAD.)"));
1964 printf(" %s\n", "-M, --max-age=SECONDS");
1965 printf(" %s\n", _("Warn if document is more than SECONDS old. the number can also be of"));
1966 printf(" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or \"10d\" for days."));
1967 printf(" %s\n", "-T, --content-type=STRING");
1968 printf(" %s\n", _("specify Content-Type header media type when POSTing\n"));
1969 printf(" %s\n", "-l, --linespan");
1970 printf(" %s\n", _("Allow regex to span newlines (must precede -r or -R)"));
1971 printf(" %s\n", "-r, --regex, --ereg=STRING");
1972 printf(" %s\n", _("Search page for regex STRING"));
1973 printf(" %s\n", "-R, --eregi=STRING");
1974 printf(" %s\n", _("Search page for case-insensitive regex STRING"));
1975 printf(" %s\n", "--invert-regex");
1976 printf(" %s\n", _("Return STATE if found, OK if not (STATE is CRITICAL, per default)"));
1977 printf(" %s\n", _("can be changed with --state--regex)"));
1978 printf(" %s\n", "--state-regex=STATE");
1979 printf(" %s\n", _("Return STATE if regex is found, OK if not. STATE can be one of \"critical\",\"warning\""));
1980 printf(" %s\n", "-a, --authorization=AUTH_PAIR");
1981 printf(" %s\n", _("Username:password on sites with basic authentication"));
1982 printf(" %s\n", "-b, --proxy-authorization=AUTH_PAIR");
1983 printf(" %s\n", _("Username:password on proxy-servers with basic authentication"));
1984 printf(" %s\n", "-A, --useragent=STRING");
1985 printf(" %s\n", _("String to be sent in http header as \"User Agent\""));
1986 printf(" %s\n", "-k, --header=STRING");
1987 printf(" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers"));
1988 printf(" %s\n", "-E, --extended-perfdata");
1989 printf(" %s\n", _("Print additional performance data"));
1990 printf(" %s\n", "-B, --show-body");
1991 printf(" %s\n", _("Print body content below status line"));
1992 printf(" %s\n", "-L, --link");
1993 printf(" %s\n", _("Wrap output in HTML link (obsoleted by urlize)"));
1994 printf(" %s\n", "-f, --onredirect=<ok|warning|critical|follow|sticky|stickyport|curl>");
1995 printf(" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the"));
1996 printf(" %s\n", _("specified IP address. stickyport also ensures port stays the same."));
1997 printf(" %s\n", _("follow uses the old redirection algorithm of check_http."));
1998 printf(" %s\n", _("curl uses CURL_FOLLOWLOCATION built into libcurl."));
1999 printf(" %s\n", "--max-redirs=INTEGER");
2000 printf(" %s", _("Maximal number of redirects (default: "));
2001 printf("%d)\n", DEFAULT_MAX_REDIRS);
2002 printf(" %s\n", "-m, --pagesize=INTEGER<:INTEGER>");
2003 printf(" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)"));
2004 printf("\n");
2005 printf(" %s\n", "--http-version=VERSION");
2006 printf(" %s\n", _("Connect via specific HTTP protocol."));
2007 printf(" %s\n", _("1.0 = HTTP/1.0, 1.1 = HTTP/1.1, 2.0 = HTTP/2 (HTTP/2 will fail without -S)"));
2008 printf(" %s\n", "--enable-automatic-decompression");
2009 printf(" %s\n", _("Enable automatic decompression of body (CURLOPT_ACCEPT_ENCODING)."));
2010 printf(" %s\n", "--haproxy-protocol");
2011 printf(" %s\n", _("Send HAProxy proxy protocol v1 header (CURLOPT_HAPROXYPROTOCOL)."));
2012 printf(" %s\n", "--cookie-jar=FILE");
2013 printf(" %s\n", _("Store cookies in the cookie jar and send them out when requested."));
2014 printf("\n");
2016 printf(UT_WARN_CRIT);
2018 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
2020 printf(UT_VERBOSE);
2022 printf("\n");
2023 printf("%s\n", _("Notes:"));
2024 printf(" %s\n", _("This plugin will attempt to open an HTTP connection with the host."));
2025 printf(" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL"));
2026 printf(" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect response"));
2027 printf(" %s\n", _("messages from the host result in STATE_WARNING return values. If you are"));
2028 printf(" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN"));
2029 printf(" %s\n", _("(fully qualified domain name) as the [host_name] argument."));
2031 #ifdef LIBCURL_FEATURE_SSL
2032 printf("\n");
2033 printf(" %s\n", _("This plugin can also check whether an SSL enabled web server is able to"));
2034 printf(" %s\n", _("serve content (optionally within a specified time) or whether the X509 "));
2035 printf(" %s\n", _("certificate is still valid for the specified number of days."));
2036 printf("\n");
2037 printf(" %s\n", _("Please note that this plugin does not check if the presented server"));
2038 printf(" %s\n", _("certificate matches the hostname of the server, or if the certificate"));
2039 printf(" %s\n", _("has a valid chain of trust to one of the locally installed CAs."));
2040 printf("\n");
2041 printf("%s\n", _("Examples:"));
2042 printf(" %s\n\n", "CHECK CONTENT: check_curl -w 5 -c 10 --ssl -H www.verisign.com");
2043 printf(" %s\n", _("When the 'www.verisign.com' server returns its content within 5 seconds,"));
2044 printf(" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds"));
2045 printf(" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,"));
2046 printf(" %s\n", _("a STATE_CRITICAL will be returned."));
2047 printf("\n");
2048 printf(" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 14");
2049 printf(" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,"));
2050 printf(" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
2051 printf(" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when"));
2052 printf(" %s\n\n", _("the certificate is expired."));
2053 printf("\n");
2054 printf(" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 30,14");
2055 printf(" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 30 days,"));
2056 printf(" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
2057 printf(" %s\n", _("30 days, but more than 14 days, a STATE_WARNING is returned."));
2058 printf(" %s\n", _("A STATE_CRITICAL will be returned when certificate expires in less than 14 days"));
2059 #endif
2061 printf("\n %s\n", "CHECK WEBSERVER CONTENT VIA PROXY:");
2062 printf(" %s\n", _("It is recommended to use an environment proxy like:"));
2063 printf(" %s\n", _("http_proxy=http://192.168.100.35:3128 ./check_curl -H www.monitoring-plugins.org"));
2064 printf(" %s\n", _("legacy proxy requests in check_http style still work:"));
2065 printf(" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u http://www.monitoring-plugins.org/ -H www.monitoring-plugins.org"));
2067 #ifdef LIBCURL_FEATURE_SSL
2068 printf("\n %s\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: ");
2069 printf(" %s\n", _("It is recommended to use an environment proxy like:"));
2070 printf(" %s\n", _("https_proxy=http://192.168.100.35:3128 ./check_curl -H www.verisign.com -S"));
2071 printf(" %s\n", _("legacy proxy requests in check_http style still work:"));
2072 printf(" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u https://www.verisign.com/ -S -j CONNECT -H www.verisign.com "));
2073 printf(" %s\n", _("all these options are needed: -I <proxy> -p <proxy-port> -u <check-url> -S(sl) -j CONNECT -H <webserver>"));
2074 printf(" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds"));
2075 printf(" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,"));
2076 printf(" %s\n", _("a STATE_CRITICAL will be returned."));
2078 #endif
2080 printf(UT_SUPPORT);
2083 void print_usage(void) {
2084 printf("%s\n", _("Usage:"));
2085 printf(" %s -H <vhost> | -I <IP-address> [-u <uri>] [-p <port>]\n", progname);
2086 printf(" [-J <client certificate file>] [-K <private key>] [--ca-cert <CA certificate file>] [-D]\n");
2087 printf(" [-w <warn time>] [-c <critical time>] [-t <timeout>] [-L] [-E] [-a auth]\n");
2088 printf(" [-b proxy_auth] [-f <ok|warning|critical|follow|sticky|stickyport|curl>]\n");
2089 printf(" [-e <expect>] [-d string] [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n");
2090 printf(" [-P string] [-m <min_pg_size>:<max_pg_size>] [-4|-6] [-N] [-M <age>]\n");
2091 printf(" [-A string] [-k string] [-S <version>] [--sni] [--haproxy-protocol]\n");
2092 printf(" [-T <content-type>] [-j method]\n");
2093 printf(" [--http-version=<version>] [--enable-automatic-decompression]\n");
2094 printf(" [--cookie-jar=<cookie jar file>\n");
2095 printf(" %s -H <vhost> | -I <IP-address> -C <warn_age>[,<crit_age>]\n", progname);
2096 printf(" [-p <port>] [-t <timeout>] [-4|-6] [--sni]\n");
2097 printf("\n");
2098 #ifdef LIBCURL_FEATURE_SSL
2099 printf("%s\n", _("In the first form, make an HTTP request."));
2100 printf("%s\n\n", _("In the second form, connect to the server and check the TLS certificate."));
2101 #endif
2104 void print_curl_version(void) { printf("%s\n", curl_version()); }
2106 int curlhelp_initwritebuffer(curlhelp_write_curlbuf *buf) {
2107 buf->bufsize = DEFAULT_BUFFER_SIZE;
2108 buf->buflen = 0;
2109 buf->buf = (char *)malloc((size_t)buf->bufsize);
2110 if (buf->buf == NULL)
2111 return -1;
2112 return 0;
2115 size_t curlhelp_buffer_write_callback(void *buffer, size_t size, size_t nmemb, void *stream) {
2116 curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream;
2118 while (buf->bufsize < buf->buflen + size * nmemb + 1) {
2119 buf->bufsize = buf->bufsize * 2;
2120 buf->buf = (char *)realloc(buf->buf, buf->bufsize);
2121 if (buf->buf == NULL) {
2122 fprintf(stderr, "malloc failed (%d) %s\n", errno, strerror(errno));
2123 return -1;
2127 memcpy(buf->buf + buf->buflen, buffer, size * nmemb);
2128 buf->buflen += size * nmemb;
2129 buf->buf[buf->buflen] = '\0';
2131 return (int)(size * nmemb);
2134 size_t curlhelp_buffer_read_callback(void *buffer, size_t size, size_t nmemb, void *stream) {
2135 curlhelp_read_curlbuf *buf = (curlhelp_read_curlbuf *)stream;
2137 size_t n = min(nmemb * size, buf->buflen - buf->pos);
2139 memcpy(buffer, buf->buf + buf->pos, n);
2140 buf->pos += n;
2142 return (int)n;
2145 void curlhelp_freewritebuffer(curlhelp_write_curlbuf *buf) {
2146 free(buf->buf);
2147 buf->buf = NULL;
2150 int curlhelp_initreadbuffer(curlhelp_read_curlbuf *buf, const char *data, size_t datalen) {
2151 buf->buflen = datalen;
2152 buf->buf = (char *)malloc((size_t)buf->buflen);
2153 if (buf->buf == NULL)
2154 return -1;
2155 memcpy(buf->buf, data, datalen);
2156 buf->pos = 0;
2157 return 0;
2160 void curlhelp_freereadbuffer(curlhelp_read_curlbuf *buf) {
2161 free(buf->buf);
2162 buf->buf = NULL;
2165 /* TODO: where to put this, it's actually part of sstrings2 (logically)?
2167 const char *strrstr2(const char *haystack, const char *needle) {
2168 int counter;
2169 size_t len;
2170 const char *prev_pos;
2171 const char *pos;
2173 if (haystack == NULL || needle == NULL)
2174 return NULL;
2176 if (haystack[0] == '\0' || needle[0] == '\0')
2177 return NULL;
2179 counter = 0;
2180 prev_pos = NULL;
2181 pos = haystack;
2182 len = strlen(needle);
2183 for (;;) {
2184 pos = strstr(pos, needle);
2185 if (pos == NULL) {
2186 if (counter == 0)
2187 return NULL;
2188 return prev_pos;
2190 counter++;
2191 prev_pos = pos;
2192 pos += len;
2193 if (*pos == '\0')
2194 return prev_pos;
2198 int curlhelp_parse_statusline(const char *buf, curlhelp_statusline *status_line) {
2199 char *first_line_end;
2200 char *p;
2201 size_t first_line_len;
2202 char *pp;
2203 const char *start;
2204 char *first_line_buf;
2206 /* find last start of a new header */
2207 start = strrstr2(buf, "\r\nHTTP/");
2208 if (start != NULL) {
2209 start += 2;
2210 buf = start;
2213 first_line_end = strstr(buf, "\r\n");
2214 if (first_line_end == NULL)
2215 return -1;
2217 first_line_len = (size_t)(first_line_end - buf);
2218 status_line->first_line = (char *)malloc(first_line_len + 1);
2219 if (status_line->first_line == NULL)
2220 return -1;
2221 memcpy(status_line->first_line, buf, first_line_len);
2222 status_line->first_line[first_line_len] = '\0';
2223 first_line_buf = strdup(status_line->first_line);
2225 /* protocol and version: "HTTP/x.x" SP or "HTTP/2" SP */
2227 p = strtok(first_line_buf, "/");
2228 if (p == NULL) {
2229 free(first_line_buf);
2230 return -1;
2232 if (strcmp(p, "HTTP") != 0) {
2233 free(first_line_buf);
2234 return -1;
2237 p = strtok(NULL, " ");
2238 if (p == NULL) {
2239 free(first_line_buf);
2240 return -1;
2242 if (strchr(p, '.') != NULL) {
2244 /* HTTP 1.x case */
2245 strtok(p, ".");
2246 status_line->http_major = (int)strtol(p, &pp, 10);
2247 if (*pp != '\0') {
2248 free(first_line_buf);
2249 return -1;
2251 strtok(NULL, " ");
2252 status_line->http_minor = (int)strtol(p, &pp, 10);
2253 if (*pp != '\0') {
2254 free(first_line_buf);
2255 return -1;
2257 p += 4; /* 1.x SP */
2258 } else {
2259 /* HTTP 2 case */
2260 status_line->http_major = (int)strtol(p, &pp, 10);
2261 status_line->http_minor = 0;
2262 p += 2; /* 2 SP */
2265 /* status code: "404" or "404.1", then SP */
2267 p = strtok(p, " ");
2268 if (p == NULL) {
2269 free(first_line_buf);
2270 return -1;
2272 if (strchr(p, '.') != NULL) {
2273 char *ppp;
2274 ppp = strtok(p, ".");
2275 status_line->http_code = (int)strtol(ppp, &pp, 10);
2276 if (*pp != '\0') {
2277 free(first_line_buf);
2278 return -1;
2280 ppp = strtok(NULL, "");
2281 status_line->http_subcode = (int)strtol(ppp, &pp, 10);
2282 if (*pp != '\0') {
2283 free(first_line_buf);
2284 return -1;
2286 p += 6; /* 400.1 SP */
2287 } else {
2288 status_line->http_code = (int)strtol(p, &pp, 10);
2289 status_line->http_subcode = -1;
2290 if (*pp != '\0') {
2291 free(first_line_buf);
2292 return -1;
2294 p += 4; /* 400 SP */
2297 /* Human readable message: "Not Found" CRLF */
2299 p = strtok(p, "");
2300 if (p == NULL) {
2301 status_line->msg = "";
2302 return 0;
2304 status_line->msg = status_line->first_line + (p - first_line_buf);
2305 free(first_line_buf);
2307 return 0;
2310 void curlhelp_free_statusline(curlhelp_statusline *status_line) { free(status_line->first_line); }
2312 char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header) {
2313 for (size_t i = 0; i < nof_headers; i++) {
2314 if (headers[i].name != NULL && strncasecmp(header, headers[i].name, max(headers[i].name_len, 4)) == 0) {
2315 return strndup(headers[i].value, headers[i].value_len);
2318 return NULL;
2321 int check_document_dates(const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFAULT_BUFFER_SIZE]) {
2322 char *server_date = NULL;
2323 char *document_date = NULL;
2324 int date_result = STATE_OK;
2325 curlhelp_statusline status_line;
2326 struct phr_header headers[255];
2327 size_t nof_headers = 255;
2328 size_t msglen;
2330 int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major, &status_line.http_minor,
2331 &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0);
2333 if (res == -1) {
2334 die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n"));
2337 server_date = get_header_value(headers, nof_headers, "date");
2338 document_date = get_header_value(headers, nof_headers, "last-modified");
2340 if (!server_date || !*server_date) {
2341 char tmp[DEFAULT_BUFFER_SIZE];
2343 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sServer date unknown, "), *msg);
2344 strcpy(*msg, tmp);
2346 date_result = max_state_alt(STATE_UNKNOWN, date_result);
2348 } else if (!document_date || !*document_date) {
2349 char tmp[DEFAULT_BUFFER_SIZE];
2351 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sDocument modification date unknown, "), *msg);
2352 strcpy(*msg, tmp);
2354 date_result = max_state_alt(STATE_CRITICAL, date_result);
2356 } else {
2357 time_t srv_data = curl_getdate(server_date, NULL);
2358 time_t doc_data = curl_getdate(document_date, NULL);
2359 if (verbose >= 2)
2360 printf("* server date: '%s' (%d), doc_date: '%s' (%d)\n", server_date, (int)srv_data, document_date, (int)doc_data);
2361 if (srv_data <= 0) {
2362 char tmp[DEFAULT_BUFFER_SIZE];
2364 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sServer date \"%100s\" unparsable, "), *msg, server_date);
2365 strcpy(*msg, tmp);
2367 date_result = max_state_alt(STATE_CRITICAL, date_result);
2368 } else if (doc_data <= 0) {
2369 char tmp[DEFAULT_BUFFER_SIZE];
2371 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date);
2372 strcpy(*msg, tmp);
2374 date_result = max_state_alt(STATE_CRITICAL, date_result);
2375 } else if (doc_data > srv_data + 30) {
2376 char tmp[DEFAULT_BUFFER_SIZE];
2378 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data);
2379 strcpy(*msg, tmp);
2381 date_result = max_state_alt(STATE_CRITICAL, date_result);
2382 } else if (doc_data < srv_data - maximum_age) {
2383 int n = (srv_data - doc_data);
2384 if (n > (60 * 60 * 24 * 2)) {
2385 char tmp[DEFAULT_BUFFER_SIZE];
2387 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sLast modified %.1f days ago, "), *msg, ((float)n) / (60 * 60 * 24));
2388 strcpy(*msg, tmp);
2390 date_result = max_state_alt(STATE_CRITICAL, date_result);
2391 } else {
2392 char tmp[DEFAULT_BUFFER_SIZE];
2394 snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60);
2395 strcpy(*msg, tmp);
2397 date_result = max_state_alt(STATE_CRITICAL, date_result);
2402 if (server_date)
2403 free(server_date);
2404 if (document_date)
2405 free(document_date);
2407 return date_result;
2410 int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf) {
2411 size_t content_length = 0;
2412 struct phr_header headers[255];
2413 size_t nof_headers = 255;
2414 size_t msglen;
2415 char *content_length_s = NULL;
2416 curlhelp_statusline status_line;
2418 int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major, &status_line.http_minor,
2419 &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0);
2421 if (res == -1) {
2422 die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n"));
2425 content_length_s = get_header_value(headers, nof_headers, "content-length");
2426 if (!content_length_s) {
2427 return header_buf->buflen + body_buf->buflen;
2429 content_length_s += strspn(content_length_s, " \t");
2430 content_length = atoi(content_length_s);
2431 if (content_length != body_buf->buflen) {
2432 /* TODO: should we warn if the actual and the reported body length don't match? */
2435 if (content_length_s)
2436 free(content_length_s);
2438 return header_buf->buflen + body_buf->buflen;
2441 /* TODO: is there a better way in libcurl to check for the SSL library? */
2442 curlhelp_ssl_library curlhelp_get_ssl_library(void) {
2443 curl_version_info_data *version_data;
2444 char *ssl_version;
2445 char *library;
2446 curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN;
2448 version_data = curl_version_info(CURLVERSION_NOW);
2449 if (version_data == NULL)
2450 return CURLHELP_SSL_LIBRARY_UNKNOWN;
2452 ssl_version = strdup(version_data->ssl_version);
2453 if (ssl_version == NULL)
2454 return CURLHELP_SSL_LIBRARY_UNKNOWN;
2456 library = strtok(ssl_version, "/");
2457 if (library == NULL)
2458 return CURLHELP_SSL_LIBRARY_UNKNOWN;
2460 if (strcmp(library, "OpenSSL") == 0)
2461 ssl_library = CURLHELP_SSL_LIBRARY_OPENSSL;
2462 else if (strcmp(library, "LibreSSL") == 0)
2463 ssl_library = CURLHELP_SSL_LIBRARY_LIBRESSL;
2464 else if (strcmp(library, "GnuTLS") == 0)
2465 ssl_library = CURLHELP_SSL_LIBRARY_GNUTLS;
2466 else if (strcmp(library, "NSS") == 0)
2467 ssl_library = CURLHELP_SSL_LIBRARY_NSS;
2469 if (verbose >= 2)
2470 printf("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library, ssl_library);
2472 free(ssl_version);
2474 return ssl_library;
2477 const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library ssl_library) {
2478 switch (ssl_library) {
2479 case CURLHELP_SSL_LIBRARY_OPENSSL:
2480 return "OpenSSL";
2481 case CURLHELP_SSL_LIBRARY_LIBRESSL:
2482 return "LibreSSL";
2483 case CURLHELP_SSL_LIBRARY_GNUTLS:
2484 return "GnuTLS";
2485 case CURLHELP_SSL_LIBRARY_NSS:
2486 return "NSS";
2487 case CURLHELP_SSL_LIBRARY_UNKNOWN:
2488 default:
2489 return "unknown";
2493 #ifdef LIBCURL_FEATURE_SSL
2494 # ifndef USE_OPENSSL
2495 time_t parse_cert_date(const char *s) {
2496 struct tm tm;
2497 time_t date;
2498 char *res;
2500 if (!s)
2501 return -1;
2503 /* Jan 17 14:25:12 2020 GMT */
2504 res = strptime(s, "%Y-%m-%d %H:%M:%S GMT", &tm);
2505 /* Sep 11 12:00:00 2020 GMT */
2506 if (res == NULL)
2507 strptime(s, "%Y %m %d %H:%M:%S GMT", &tm);
2508 date = mktime(&tm);
2510 return date;
2513 /* TODO: this needs cleanup in the sslutils.c, maybe we the #else case to
2514 * OpenSSL could be this function
2516 int net_noopenssl_check_certificate(cert_ptr_union *cert_ptr, int days_till_exp_warn, int days_till_exp_crit) {
2517 int i;
2518 struct curl_slist *slist;
2519 int cname_found = 0;
2520 char *start_date_str = NULL;
2521 char *end_date_str = NULL;
2522 time_t start_date;
2523 time_t end_date;
2524 char *tz;
2525 float time_left;
2526 int days_left;
2527 int time_remaining;
2528 char timestamp[50] = "";
2529 int status = STATE_UNKNOWN;
2531 if (verbose >= 2)
2532 printf("**** REQUEST CERTIFICATES ****\n");
2534 for (i = 0; i < cert_ptr->to_certinfo->num_of_certs; i++) {
2535 for (slist = cert_ptr->to_certinfo->certinfo[i]; slist; slist = slist->next) {
2536 /* find first common name in subject,
2537 * TODO: check alternative subjects for
2538 * TODO: have a decent parser here and not a hack
2539 * multi-host certificate, check wildcards
2541 if (strncasecmp(slist->data, "Subject:", 8) == 0) {
2542 int d = 3;
2543 char *p = strstr(slist->data, "CN=");
2544 if (p == NULL) {
2545 d = 5;
2546 p = strstr(slist->data, "CN = ");
2548 if (p != NULL) {
2549 if (strncmp(host_name, p + d, strlen(host_name)) == 0) {
2550 cname_found = 1;
2553 } else if (strncasecmp(slist->data, "Start Date:", 11) == 0) {
2554 start_date_str = &slist->data[11];
2555 } else if (strncasecmp(slist->data, "Expire Date:", 12) == 0) {
2556 end_date_str = &slist->data[12];
2557 } else if (strncasecmp(slist->data, "Cert:", 5) == 0) {
2558 goto HAVE_FIRST_CERT;
2560 if (verbose >= 2)
2561 printf("%d ** %s\n", i, slist->data);
2564 HAVE_FIRST_CERT:
2566 if (verbose >= 2)
2567 printf("**** REQUEST CERTIFICATES ****\n");
2569 if (!cname_found) {
2570 printf("%s\n", _("CRITICAL - Cannot retrieve certificate subject."));
2571 return STATE_CRITICAL;
2574 start_date = parse_cert_date(start_date_str);
2575 if (start_date <= 0) {
2576 snprintf(msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Start Date' in certificate: '%s'"), start_date_str);
2577 puts(msg);
2578 return STATE_WARNING;
2581 end_date = parse_cert_date(end_date_str);
2582 if (end_date <= 0) {
2583 snprintf(msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Expire Date' in certificate: '%s'"), start_date_str);
2584 puts(msg);
2585 return STATE_WARNING;
2588 time_left = difftime(end_date, time(NULL));
2589 days_left = time_left / 86400;
2590 tz = getenv("TZ");
2591 setenv("TZ", "GMT", 1);
2592 tzset();
2593 strftime(timestamp, 50, "%c %z", localtime(&end_date));
2594 if (tz)
2595 setenv("TZ", tz, 1);
2596 else
2597 unsetenv("TZ");
2598 tzset();
2600 if (days_left > 0 && days_left <= days_till_exp_warn) {
2601 printf(_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL",
2602 host_name, days_left, timestamp);
2603 if (days_left > days_till_exp_crit)
2604 status = STATE_WARNING;
2605 else
2606 status = STATE_CRITICAL;
2607 } else if (days_left == 0 && time_left > 0) {
2608 if (time_left >= 3600)
2609 time_remaining = (int)time_left / 3600;
2610 else
2611 time_remaining = (int)time_left / 60;
2613 printf(_("%s - Certificate '%s' expires in %u %s (%s)\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name,
2614 time_remaining, time_left >= 3600 ? "hours" : "minutes", timestamp);
2616 if (days_left > days_till_exp_crit)
2617 status = STATE_WARNING;
2618 else
2619 status = STATE_CRITICAL;
2620 } else if (time_left < 0) {
2621 printf(_("CRITICAL - Certificate '%s' expired on %s.\n"), host_name, timestamp);
2622 status = STATE_CRITICAL;
2623 } else if (days_left == 0) {
2624 printf(_("%s - Certificate '%s' just expired (%s).\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name,
2625 timestamp);
2626 if (days_left > days_till_exp_crit)
2627 status = STATE_WARNING;
2628 else
2629 status = STATE_CRITICAL;
2630 } else {
2631 printf(_("OK - Certificate '%s' will expire on %s.\n"), host_name, timestamp);
2632 status = STATE_OK;
2634 return status;
2636 # endif /* USE_OPENSSL */
2637 #endif /* LIBCURL_FEATURE_SSL */