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