summaryrefslogtreecommitdiffstats
path: root/plugins/check_curl.d
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/check_curl.d')
-rw-r--r--plugins/check_curl.d/check_curl_helpers.c1297
-rw-r--r--plugins/check_curl.d/check_curl_helpers.h128
-rw-r--r--plugins/check_curl.d/config.h116
3 files changed, 1541 insertions, 0 deletions
diff --git a/plugins/check_curl.d/check_curl_helpers.c b/plugins/check_curl.d/check_curl_helpers.c
new file mode 100644
index 00000000..7be781fc
--- /dev/null
+++ b/plugins/check_curl.d/check_curl_helpers.c
@@ -0,0 +1,1297 @@
1#include "./check_curl_helpers.h"
2#include <stdbool.h>
3#include <arpa/inet.h>
4#include <netinet/in.h>
5#include <netdb.h>
6#include <stdlib.h>
7#include <string.h>
8#include "../utils.h"
9#include "check_curl.d/config.h"
10#include "output.h"
11#include "perfdata.h"
12#include "states.h"
13
14extern int verbose;
15char errbuf[MAX_INPUT_BUFFER];
16bool is_openssl_callback = false;
17bool add_sslctx_verify_fun = false;
18
19check_curl_configure_curl_wrapper
20check_curl_configure_curl(const check_curl_static_curl_config config,
21 check_curl_working_state working_state, bool check_cert,
22 bool on_redirect_dependent, int follow_method, long max_depth) {
23 check_curl_configure_curl_wrapper result = {
24 .errorcode = OK,
25 .curl_state =
26 {
27 .curl_global_initialized = false,
28 .curl_easy_initialized = false,
29 .curl = NULL,
30
31 .body_buf_initialized = false,
32 .body_buf = NULL,
33 .header_buf_initialized = false,
34 .header_buf = NULL,
35 .status_line_initialized = false,
36 .status_line = NULL,
37 .put_buf_initialized = false,
38 .put_buf = NULL,
39
40 .header_list = NULL,
41 .host = NULL,
42 },
43 };
44
45 if ((result.curl_state.status_line = calloc(1, sizeof(curlhelp_statusline))) == NULL) {
46 die(STATE_UNKNOWN, "HTTP UNKNOWN - allocation of statusline failed\n");
47 }
48
49 if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) {
50 die(STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n");
51 }
52 result.curl_state.curl_global_initialized = true;
53
54 if ((result.curl_state.curl = curl_easy_init()) == NULL) {
55 die(STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n");
56 }
57 result.curl_state.curl_easy_initialized = true;
58
59 if (verbose >= 1) {
60 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl, CURLOPT_VERBOSE, 1L),
61 "CURLOPT_VERBOSE");
62 }
63
64 /* print everything on stdout like check_http would do */
65 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl, CURLOPT_STDERR, stdout),
66 "CURLOPT_STDERR");
67
68 if (config.automatic_decompression) {
69#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6)
70 handle_curl_option_return_code(
71 curl_easy_setopt(result.curl_state.curl, CURLOPT_ACCEPT_ENCODING, ""),
72 "CURLOPT_ACCEPT_ENCODING");
73#else
74 handle_curl_option_return_code(
75 curl_easy_setopt(result.curl_state.curl, CURLOPT_ENCODING, ""), "CURLOPT_ENCODING");
76#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6) */
77 }
78
79 /* initialize buffer for body of the answer */
80 if (curlhelp_initwritebuffer(&result.curl_state.body_buf) < 0) {
81 die(STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n");
82 }
83 result.curl_state.body_buf_initialized = true;
84
85 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl, CURLOPT_WRITEFUNCTION,
86 curlhelp_buffer_write_callback),
87 "CURLOPT_WRITEFUNCTION");
88 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl, CURLOPT_WRITEDATA,
89 (void *)result.curl_state.body_buf),
90 "CURLOPT_WRITEDATA");
91
92 /* initialize buffer for header of the answer */
93 if (curlhelp_initwritebuffer(&result.curl_state.header_buf) < 0) {
94 die(STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for header\n");
95 }
96 result.curl_state.header_buf_initialized = true;
97
98 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl, CURLOPT_HEADERFUNCTION,
99 curlhelp_buffer_write_callback),
100 "CURLOPT_HEADERFUNCTION");
101 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl, CURLOPT_WRITEHEADER,
102 (void *)result.curl_state.header_buf),
103 "CURLOPT_WRITEHEADER");
104
105 /* set the error buffer */
106 handle_curl_option_return_code(
107 curl_easy_setopt(result.curl_state.curl, CURLOPT_ERRORBUFFER, errbuf),
108 "CURLOPT_ERRORBUFFER");
109
110 /* set timeouts */
111 handle_curl_option_return_code(
112 curl_easy_setopt(result.curl_state.curl, CURLOPT_CONNECTTIMEOUT, config.socket_timeout),
113 "CURLOPT_CONNECTTIMEOUT");
114
115 handle_curl_option_return_code(
116 curl_easy_setopt(result.curl_state.curl, CURLOPT_TIMEOUT, config.socket_timeout),
117 "CURLOPT_TIMEOUT");
118
119 /* enable haproxy protocol */
120 if (config.haproxy_protocol) {
121 handle_curl_option_return_code(
122 curl_easy_setopt(result.curl_state.curl, CURLOPT_HAPROXYPROTOCOL, 1L),
123 "CURLOPT_HAPROXYPROTOCOL");
124 }
125
126 // fill dns resolve cache to make curl connect to the given server_address instead of the
127 // host_name, only required for ssl, because we use the host_name later on to make SNI happy
128 char dnscache[DEFAULT_BUFFER_SIZE];
129 char addrstr[DEFAULT_BUFFER_SIZE / 2];
130 if (working_state.use_ssl && working_state.host_name != NULL) {
131 char *tmp_mod_address;
132
133 /* lookup_host() requires an IPv6 address without the brackets. */
134 if ((strnlen(working_state.server_address, MAX_IPV4_HOSTLENGTH) > 2) &&
135 (working_state.server_address[0] == '[')) {
136 // Duplicate and strip the leading '['
137 tmp_mod_address =
138 strndup(working_state.server_address + 1, strlen(working_state.server_address) - 2);
139 } else {
140 tmp_mod_address = working_state.server_address;
141 }
142
143 int res;
144 if ((res = lookup_host(tmp_mod_address, addrstr, DEFAULT_BUFFER_SIZE / 2,
145 config.sin_family)) != 0) {
146 die(STATE_CRITICAL,
147 _("Unable to lookup IP address for '%s': getaddrinfo returned %d - %s"),
148 working_state.server_address, res, gai_strerror(res));
149 }
150
151 snprintf(dnscache, DEFAULT_BUFFER_SIZE, "%s:%d:%s", working_state.host_name,
152 working_state.serverPort, addrstr);
153 result.curl_state.host = curl_slist_append(NULL, dnscache);
154 curl_easy_setopt(result.curl_state.curl, CURLOPT_RESOLVE, result.curl_state.host);
155
156 if (verbose >= 1) {
157 printf("* curl CURLOPT_RESOLVE: %s\n", dnscache);
158 }
159 }
160
161 // If server_address is an IPv6 address it must be surround by square brackets
162 struct in6_addr tmp_in_addr;
163 if (inet_pton(AF_INET6, working_state.server_address, &tmp_in_addr) == 1) {
164 char *new_server_address = calloc(strlen(working_state.server_address) + 3, sizeof(char));
165 if (new_server_address == NULL) {
166 die(STATE_UNKNOWN, "HTTP UNKNOWN - Unable to allocate memory\n");
167 }
168 snprintf(new_server_address, strlen(working_state.server_address) + 3, "[%s]",
169 working_state.server_address);
170 working_state.server_address = new_server_address;
171 }
172
173 /* compose URL: use the address we want to connect to, set Host: header later */
174 char *url = fmt_url(working_state);
175
176 if (verbose >= 1) {
177 printf("* curl CURLOPT_URL: %s\n", url);
178 }
179 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl, CURLOPT_URL, url),
180 "CURLOPT_URL");
181
182 free(url);
183
184 /* extract proxy information for legacy proxy https requests */
185 if (!strcmp(working_state.http_method, "CONNECT") ||
186 strstr(working_state.server_url, "http") == working_state.server_url) {
187 handle_curl_option_return_code(
188 curl_easy_setopt(result.curl_state.curl, CURLOPT_PROXY, working_state.server_address),
189 "CURLOPT_PROXY");
190 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl, CURLOPT_PROXYPORT,
191 (long)working_state.serverPort),
192 "CURLOPT_PROXYPORT");
193 if (verbose >= 2) {
194 printf("* curl CURLOPT_PROXY: %s:%d\n", working_state.server_address,
195 working_state.serverPort);
196 }
197 working_state.http_method = "GET";
198 handle_curl_option_return_code(
199 curl_easy_setopt(result.curl_state.curl, CURLOPT_URL, working_state.server_url),
200 "CURLOPT_URL");
201 }
202
203 /* disable body for HEAD request */
204 if (working_state.http_method && !strcmp(working_state.http_method, "HEAD")) {
205 working_state.no_body = true;
206 }
207
208 /* set HTTP protocol version */
209 handle_curl_option_return_code(
210 curl_easy_setopt(result.curl_state.curl, CURLOPT_HTTP_VERSION, config.curl_http_version),
211 "CURLOPT_HTTP_VERSION");
212
213 /* set HTTP method */
214 if (working_state.http_method) {
215 if (!strcmp(working_state.http_method, "POST")) {
216 handle_curl_option_return_code(
217 curl_easy_setopt(result.curl_state.curl, CURLOPT_POST, 1L), "CURLOPT_POST");
218 } else if (!strcmp(working_state.http_method, "PUT")) {
219 handle_curl_option_return_code(
220 curl_easy_setopt(result.curl_state.curl, CURLOPT_UPLOAD, 1L), "CURLOPT_UPLOAD");
221 } else {
222 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl,
223 CURLOPT_CUSTOMREQUEST,
224 working_state.http_method),
225 "CURLOPT_CUSTOMREQUEST");
226 }
227 }
228
229 char *force_host_header = NULL;
230 /* check if Host header is explicitly set in options */
231 if (config.http_opt_headers_count) {
232 for (size_t i = 0; i < config.http_opt_headers_count; i++) {
233 if (strncmp(config.http_opt_headers[i], "Host:", 5) == 0) {
234 force_host_header = config.http_opt_headers[i];
235 }
236 }
237 }
238
239 /* set hostname (virtual hosts), not needed if CURLOPT_CONNECT_TO is used, but left in
240 * anyway */
241 char http_header[DEFAULT_BUFFER_SIZE];
242 if (working_state.host_name != NULL && force_host_header == NULL) {
243 if ((working_state.virtualPort != HTTP_PORT && !working_state.use_ssl) ||
244 (working_state.virtualPort != HTTPS_PORT && working_state.use_ssl)) {
245 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s:%d", working_state.host_name,
246 working_state.virtualPort);
247 } else {
248 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s", working_state.host_name);
249 }
250 result.curl_state.header_list =
251 curl_slist_append(result.curl_state.header_list, http_header);
252 }
253
254 /* always close connection, be nice to servers */
255 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Connection: close");
256 result.curl_state.header_list = curl_slist_append(result.curl_state.header_list, http_header);
257
258 /* attach additional headers supplied by the user */
259 /* optionally send any other header tag */
260 if (config.http_opt_headers_count) {
261 for (size_t i = 0; i < config.http_opt_headers_count; i++) {
262 result.curl_state.header_list =
263 curl_slist_append(result.curl_state.header_list, config.http_opt_headers[i]);
264 }
265 }
266
267 /* set HTTP headers */
268 handle_curl_option_return_code(
269 curl_easy_setopt(result.curl_state.curl, CURLOPT_HTTPHEADER, result.curl_state.header_list),
270 "CURLOPT_HTTPHEADER");
271
272#ifdef LIBCURL_FEATURE_SSL
273 /* set SSL version, warn about insecure or unsupported versions */
274 if (working_state.use_ssl) {
275 handle_curl_option_return_code(
276 curl_easy_setopt(result.curl_state.curl, CURLOPT_SSLVERSION, config.ssl_version),
277 "CURLOPT_SSLVERSION");
278 }
279
280 /* client certificate and key to present to server (SSL) */
281 if (config.client_cert) {
282 handle_curl_option_return_code(
283 curl_easy_setopt(result.curl_state.curl, CURLOPT_SSLCERT, config.client_cert),
284 "CURLOPT_SSLCERT");
285 }
286
287 if (config.client_privkey) {
288 handle_curl_option_return_code(
289 curl_easy_setopt(result.curl_state.curl, CURLOPT_SSLKEY, config.client_privkey),
290 "CURLOPT_SSLKEY");
291 }
292
293 if (config.ca_cert) {
294 handle_curl_option_return_code(
295 curl_easy_setopt(result.curl_state.curl, CURLOPT_CAINFO, config.ca_cert),
296 "CURLOPT_CAINFO");
297 }
298
299 if (config.ca_cert || config.verify_peer_and_host) {
300 /* per default if we have a CA verify both the peer and the
301 * hostname in the certificate, can be switched off later */
302 handle_curl_option_return_code(
303 curl_easy_setopt(result.curl_state.curl, CURLOPT_SSL_VERIFYPEER, 1L),
304 "CURLOPT_SSL_VERIFYPEER");
305 handle_curl_option_return_code(
306 curl_easy_setopt(result.curl_state.curl, CURLOPT_SSL_VERIFYHOST, 2L),
307 "CURLOPT_SSL_VERIFYHOST");
308 } else {
309 /* backward-compatible behaviour, be tolerant in checks
310 * TODO: depending on more options have aspects we want
311 * to be less tolerant about ssl verfications
312 */
313 handle_curl_option_return_code(
314 curl_easy_setopt(result.curl_state.curl, CURLOPT_SSL_VERIFYPEER, 0L),
315 "CURLOPT_SSL_VERIFYPEER");
316 handle_curl_option_return_code(
317 curl_easy_setopt(result.curl_state.curl, CURLOPT_SSL_VERIFYHOST, 0L),
318 "CURLOPT_SSL_VERIFYHOST");
319 }
320
321 /* detect SSL library used by libcurl */
322 curlhelp_ssl_library ssl_library = curlhelp_get_ssl_library();
323
324 /* try hard to get a stack of certificates to verify against */
325 if (check_cert) {
326# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1)
327 /* inform curl to report back certificates */
328 switch (ssl_library) {
329 case CURLHELP_SSL_LIBRARY_OPENSSL:
330 case CURLHELP_SSL_LIBRARY_LIBRESSL:
331 /* set callback to extract certificate with OpenSSL context function (works with
332 * OpenSSL-style libraries only!) */
333# ifdef USE_OPENSSL
334 /* libcurl and monitoring plugins built with OpenSSL, good */
335 add_sslctx_verify_fun = true;
336 is_openssl_callback = true;
337# endif /* USE_OPENSSL */
338 /* libcurl is built with OpenSSL, monitoring plugins, so falling
339 * back to manually extracting certificate information */
340 handle_curl_option_return_code(
341 curl_easy_setopt(result.curl_state.curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
342 break;
343
344 case CURLHELP_SSL_LIBRARY_NSS:
345# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
346 /* NSS: support for CERTINFO is implemented since 7.34.0 */
347 handle_curl_option_return_code(
348 curl_easy_setopt(result.curl_state.curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
349# else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
350 die(STATE_CRITICAL,
351 "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library "
352 "'%s' is too old)\n",
353 curlhelp_get_ssl_library_string(ssl_library));
354# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
355 break;
356
357 case CURLHELP_SSL_LIBRARY_GNUTLS:
358# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0)
359 /* GnuTLS: support for CERTINFO is implemented since 7.42.0 */
360 handle_curl_option_return_code(
361 curl_easy_setopt(result.curl_state.curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
362# else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */
363 die(STATE_CRITICAL,
364 "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library "
365 "'%s' is too old)\n",
366 curlhelp_get_ssl_library_string(ssl_library));
367# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */
368 break;
369
370 case CURLHELP_SSL_LIBRARY_UNKNOWN:
371 default:
372 die(STATE_CRITICAL,
373 "HTTP CRITICAL - Cannot retrieve certificates (unknown SSL library '%s', must "
374 "implement first)\n",
375 curlhelp_get_ssl_library_string(ssl_library));
376 break;
377 }
378# else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */
379 /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */
380 if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL ||
381 ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL) {
382 add_sslctx_verify_fun = true;
383 } else {
384 die(STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (no "
385 "CURLOPT_SSL_CTX_FUNCTION, no OpenSSL library or libcurl "
386 "too old and has no CURLOPT_CERTINFO)\n");
387 }
388# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */
389 }
390
391# if LIBCURL_VERSION_NUM >= \
392 MAKE_LIBCURL_VERSION(7, 10, 6) /* required for CURLOPT_SSL_CTX_FUNCTION */
393 // ssl ctx function is not available with all ssl backends
394 if (curl_easy_setopt(result.curl_state.curl, CURLOPT_SSL_CTX_FUNCTION, NULL) !=
395 CURLE_UNKNOWN_OPTION) {
396 handle_curl_option_return_code(
397 curl_easy_setopt(result.curl_state.curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun),
398 "CURLOPT_SSL_CTX_FUNCTION");
399 }
400# endif
401#endif /* LIBCURL_FEATURE_SSL */
402
403 /* set default or user-given user agent identification */
404 handle_curl_option_return_code(
405 curl_easy_setopt(result.curl_state.curl, CURLOPT_USERAGENT, config.user_agent),
406 "CURLOPT_USERAGENT");
407
408 /* proxy-authentication */
409 if (strcmp(config.proxy_auth, "")) {
410 handle_curl_option_return_code(
411 curl_easy_setopt(result.curl_state.curl, CURLOPT_PROXYUSERPWD, config.proxy_auth),
412 "CURLOPT_PROXYUSERPWD");
413 }
414
415 /* authentication */
416 if (strcmp(config.user_auth, "")) {
417 handle_curl_option_return_code(
418 curl_easy_setopt(result.curl_state.curl, CURLOPT_USERPWD, config.user_auth),
419 "CURLOPT_USERPWD");
420 }
421 /* TODO: parameter auth method, bitfield of following methods:
422 * CURLAUTH_BASIC (default)
423 * CURLAUTH_DIGEST
424 * CURLAUTH_DIGEST_IE
425 * CURLAUTH_NEGOTIATE
426 * CURLAUTH_NTLM
427 * CURLAUTH_NTLM_WB
428 *
429 * convenience tokens for typical sets of methods:
430 * CURLAUTH_ANYSAFE: most secure, without BASIC
431 * or CURLAUTH_ANY: most secure, even BASIC if necessary
432 *
433 * handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPAUTH,
434 * (long)CURLAUTH_DIGEST ), "CURLOPT_HTTPAUTH");
435 */
436
437 /* handle redirections */
438 if (on_redirect_dependent) {
439 if (follow_method == FOLLOW_LIBCURL) {
440 handle_curl_option_return_code(
441 curl_easy_setopt(result.curl_state.curl, CURLOPT_FOLLOWLOCATION, 1L),
442 "CURLOPT_FOLLOWLOCATION");
443
444 /* default -1 is infinite, not good, could lead to zombie plugins!
445 Setting it to one bigger than maximal limit to handle errors nicely below
446 */
447 handle_curl_option_return_code(
448 curl_easy_setopt(result.curl_state.curl, CURLOPT_MAXREDIRS, max_depth + 1),
449 "CURLOPT_MAXREDIRS");
450
451 /* for now allow only http and https (we are a http(s) check plugin in the end) */
452#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 85, 0)
453 handle_curl_option_return_code(
454 curl_easy_setopt(result.curl_state.curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https"),
455 "CURLOPT_REDIR_PROTOCOLS_STR");
456#elif LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4)
457 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl,
458 CURLOPT_REDIR_PROTOCOLS,
459 CURLPROTO_HTTP | CURLPROTO_HTTPS),
460 "CURLOPT_REDIRECT_PROTOCOLS");
461#endif
462
463 /* TODO: handle the following aspects of redirection, make them
464 * command line options too later:
465 CURLOPT_POSTREDIR: method switch
466 CURLINFO_REDIRECT_URL: custom redirect option
467 CURLOPT_REDIRECT_PROTOCOLS: allow people to step outside safe protocols
468 CURLINFO_REDIRECT_COUNT: get the number of redirects, print it, maybe a range
469 option here is nice like for expected page size?
470 */
471 } else {
472 /* old style redirection*/
473 }
474 }
475 /* no-body */
476 if (working_state.no_body) {
477 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl, CURLOPT_NOBODY, 1L),
478 "CURLOPT_NOBODY");
479 }
480
481 /* IPv4 or IPv6 forced DNS resolution */
482 if (config.sin_family == AF_UNSPEC) {
483 handle_curl_option_return_code(
484 curl_easy_setopt(result.curl_state.curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER),
485 "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_WHATEVER)");
486 } else if (config.sin_family == AF_INET) {
487 handle_curl_option_return_code(
488 curl_easy_setopt(result.curl_state.curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4),
489 "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V4)");
490 }
491#if defined(USE_IPV6) && defined(LIBCURL_FEATURE_IPV6)
492 else if (config.sin_family == AF_INET6) {
493 handle_curl_option_return_code(
494 curl_easy_setopt(result.curl_state.curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6),
495 "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V6)");
496 }
497#endif
498
499 /* either send http POST data (any data, not only POST)*/
500 if (!strcmp(working_state.http_method, "POST") || !strcmp(working_state.http_method, "PUT")) {
501 /* set content of payload for POST and PUT */
502 if (config.http_content_type) {
503 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Content-Type: %s",
504 config.http_content_type);
505 result.curl_state.header_list =
506 curl_slist_append(result.curl_state.header_list, http_header);
507 }
508 /* NULL indicates "HTTP Continue" in libcurl, provide an empty string
509 * in case of no POST/PUT data */
510 if (!working_state.http_post_data) {
511 working_state.http_post_data = "";
512 }
513
514 if (!strcmp(working_state.http_method, "POST")) {
515 /* POST method, set payload with CURLOPT_POSTFIELDS */
516 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl,
517 CURLOPT_POSTFIELDS,
518 working_state.http_post_data),
519 "CURLOPT_POSTFIELDS");
520 } else if (!strcmp(working_state.http_method, "PUT")) {
521 handle_curl_option_return_code(
522 curl_easy_setopt(result.curl_state.curl, CURLOPT_READFUNCTION,
523 (curl_read_callback)curlhelp_buffer_read_callback),
524 "CURLOPT_READFUNCTION");
525 if (curlhelp_initreadbuffer(&result.curl_state.put_buf, working_state.http_post_data,
526 strlen(working_state.http_post_data)) < 0) {
527 die(STATE_UNKNOWN,
528 "HTTP CRITICAL - out of memory allocating read buffer for PUT\n");
529 }
530 result.curl_state.put_buf_initialized = true;
531 handle_curl_option_return_code(curl_easy_setopt(result.curl_state.curl,
532 CURLOPT_READDATA,
533 (void *)result.curl_state.put_buf),
534 "CURLOPT_READDATA");
535 handle_curl_option_return_code(
536 curl_easy_setopt(result.curl_state.curl, CURLOPT_INFILESIZE,
537 (curl_off_t)strlen(working_state.http_post_data)),
538 "CURLOPT_INFILESIZE");
539 }
540 }
541
542 /* cookie handling */
543 if (config.cookie_jar_file != NULL) {
544 /* enable reading cookies from a file, and if the filename is an empty string, only
545 * enable the curl cookie engine */
546 handle_curl_option_return_code(
547 curl_easy_setopt(result.curl_state.curl, CURLOPT_COOKIEFILE, config.cookie_jar_file),
548 "CURLOPT_COOKIEFILE");
549 /* now enable saving cookies to a file, but only if the filename is not an empty string,
550 * since writing it would fail */
551 if (*config.cookie_jar_file) {
552 handle_curl_option_return_code(
553 curl_easy_setopt(result.curl_state.curl, CURLOPT_COOKIEJAR, config.cookie_jar_file),
554 "CURLOPT_COOKIEJAR");
555 }
556 }
557
558 result.working_state = working_state;
559
560 return result;
561}
562
563void handle_curl_option_return_code(CURLcode res, const char *option) {
564 if (res != CURLE_OK) {
565 die(STATE_CRITICAL, _("Error while setting cURL option '%s': cURL returned %d - %s"),
566 option, res, curl_easy_strerror(res));
567 }
568}
569
570char *get_header_value(const struct phr_header *headers, const size_t nof_headers,
571 const char *header) {
572 for (size_t i = 0; i < nof_headers; i++) {
573 if (headers[i].name != NULL &&
574 strncasecmp(header, headers[i].name, max(headers[i].name_len, 4)) == 0) {
575 return strndup(headers[i].value, headers[i].value_len);
576 }
577 }
578 return NULL;
579}
580
581check_curl_working_state check_curl_working_state_init() {
582 check_curl_working_state result = {
583 .server_address = NULL,
584 .server_url = DEFAULT_SERVER_URL,
585 .host_name = NULL,
586 .http_method = NULL,
587 .http_post_data = NULL,
588 .virtualPort = 0,
589 .serverPort = HTTP_PORT,
590 .use_ssl = false,
591 .no_body = false,
592 };
593 return result;
594}
595
596check_curl_config check_curl_config_init() {
597 check_curl_config tmp = {
598 .initial_config = check_curl_working_state_init(),
599
600 .curl_config =
601 {
602 .automatic_decompression = false,
603 .socket_timeout = DEFAULT_SOCKET_TIMEOUT,
604 .haproxy_protocol = false,
605 .sin_family = AF_UNSPEC,
606 .curl_http_version = CURL_HTTP_VERSION_NONE,
607 .http_opt_headers = NULL,
608 .http_opt_headers_count = 0,
609 .ssl_version = CURL_SSLVERSION_DEFAULT,
610 .client_cert = NULL,
611 .client_privkey = NULL,
612 .ca_cert = NULL,
613 .verify_peer_and_host = false,
614 .user_agent = {'\0'},
615 .proxy_auth = "",
616 .user_auth = "",
617 .http_content_type = NULL,
618 .cookie_jar_file = NULL,
619 },
620 .max_depth = DEFAULT_MAX_REDIRS,
621 .followmethod = FOLLOW_HTTP_CURL,
622 .followsticky = STICKY_NONE,
623
624 .maximum_age = -1,
625 .regexp = {},
626 .compiled_regex = {},
627 .state_regex = STATE_CRITICAL,
628 .invert_regex = false,
629 .check_cert = false,
630 .continue_after_check_cert = false,
631 .days_till_exp_warn = 0,
632 .days_till_exp_crit = 0,
633 .thlds = mp_thresholds_init(),
634 .page_length_limits = mp_range_init(),
635 .page_length_limits_is_set = false,
636 .server_expect =
637 {
638 .string = HTTP_EXPECT,
639 .is_present = false,
640 },
641 .string_expect = "",
642 .header_expect = "",
643 .on_redirect_result_state = STATE_OK,
644 .on_redirect_dependent = false,
645
646 .show_extended_perfdata = false,
647 .show_body = false,
648
649 .output_format_is_set = false,
650 };
651
652 snprintf(tmp.curl_config.user_agent, DEFAULT_BUFFER_SIZE, "%s/v%s (monitoring-plugins %s, %s)",
653 "check_curl", NP_VERSION, VERSION, curl_version());
654
655 return tmp;
656}
657
658/* TODO: is there a better way in libcurl to check for the SSL library? */
659curlhelp_ssl_library curlhelp_get_ssl_library(void) {
660 curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN;
661
662 curl_version_info_data *version_data = curl_version_info(CURLVERSION_NOW);
663 if (version_data == NULL) {
664 return CURLHELP_SSL_LIBRARY_UNKNOWN;
665 }
666
667 char *ssl_version = strdup(version_data->ssl_version);
668 if (ssl_version == NULL) {
669 return CURLHELP_SSL_LIBRARY_UNKNOWN;
670 }
671
672 char *library = strtok(ssl_version, "/");
673 if (library == NULL) {
674 return CURLHELP_SSL_LIBRARY_UNKNOWN;
675 }
676
677 if (strcmp(library, "OpenSSL") == 0) {
678 ssl_library = CURLHELP_SSL_LIBRARY_OPENSSL;
679 } else if (strcmp(library, "LibreSSL") == 0) {
680 ssl_library = CURLHELP_SSL_LIBRARY_LIBRESSL;
681 } else if (strcmp(library, "GnuTLS") == 0) {
682 ssl_library = CURLHELP_SSL_LIBRARY_GNUTLS;
683 } else if (strcmp(library, "NSS") == 0) {
684 ssl_library = CURLHELP_SSL_LIBRARY_NSS;
685 }
686
687 if (verbose >= 2) {
688 printf("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library,
689 ssl_library);
690 }
691
692 free(ssl_version);
693
694 return ssl_library;
695}
696
697const char *curlhelp_get_ssl_library_string(const curlhelp_ssl_library ssl_library) {
698 switch (ssl_library) {
699 case CURLHELP_SSL_LIBRARY_OPENSSL:
700 return "OpenSSL";
701 case CURLHELP_SSL_LIBRARY_LIBRESSL:
702 return "LibreSSL";
703 case CURLHELP_SSL_LIBRARY_GNUTLS:
704 return "GnuTLS";
705 case CURLHELP_SSL_LIBRARY_NSS:
706 return "NSS";
707 case CURLHELP_SSL_LIBRARY_UNKNOWN:
708 default:
709 return "unknown";
710 }
711}
712
713size_t get_content_length(const curlhelp_write_curlbuf *header_buf,
714 const curlhelp_write_curlbuf *body_buf) {
715 struct phr_header headers[255];
716 size_t nof_headers = 255;
717 size_t msglen;
718 curlhelp_statusline status_line;
719 int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major,
720 &status_line.http_minor, &status_line.http_code, &status_line.msg,
721 &msglen, headers, &nof_headers, 0);
722
723 if (res == -1) {
724 die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n"));
725 }
726
727 char *content_length_s = get_header_value(headers, nof_headers, "content-length");
728 if (!content_length_s) {
729 return header_buf->buflen + body_buf->buflen;
730 }
731
732 content_length_s += strspn(content_length_s, " \t");
733 size_t content_length = atoi(content_length_s);
734 if (content_length != body_buf->buflen) {
735 /* TODO: should we warn if the actual and the reported body length don't match? */
736 }
737
738 if (content_length_s) {
739 free(content_length_s);
740 }
741
742 return header_buf->buflen + body_buf->buflen;
743}
744
745mp_subcheck check_document_dates(const curlhelp_write_curlbuf *header_buf, const int maximum_age) {
746 struct phr_header headers[255];
747 size_t nof_headers = 255;
748 curlhelp_statusline status_line;
749 size_t msglen;
750 int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major,
751 &status_line.http_minor, &status_line.http_code, &status_line.msg,
752 &msglen, headers, &nof_headers, 0);
753
754 if (res == -1) {
755 die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n"));
756 }
757
758 char *server_date = get_header_value(headers, nof_headers, "date");
759 char *document_date = get_header_value(headers, nof_headers, "last-modified");
760
761 mp_subcheck sc_document_dates = mp_subcheck_init();
762 if (!server_date || !*server_date) {
763 xasprintf(&sc_document_dates.output, _("Server date unknown"));
764 sc_document_dates = mp_set_subcheck_state(sc_document_dates, STATE_UNKNOWN);
765 } else if (!document_date || !*document_date) {
766 xasprintf(&sc_document_dates.output, _("Document modification date unknown, "));
767 sc_document_dates = mp_set_subcheck_state(sc_document_dates, STATE_CRITICAL);
768 } else {
769 time_t srv_data = curl_getdate(server_date, NULL);
770 time_t doc_data = curl_getdate(document_date, NULL);
771
772 if (verbose >= 2) {
773 printf("* server date: '%s' (%d), doc_date: '%s' (%d)\n", server_date, (int)srv_data,
774 document_date, (int)doc_data);
775 }
776
777 if (srv_data <= 0) {
778 xasprintf(&sc_document_dates.output, _("Server date \"%100s\" unparsable"),
779 server_date);
780 sc_document_dates = mp_set_subcheck_state(sc_document_dates, STATE_CRITICAL);
781 } else if (doc_data <= 0) {
782
783 xasprintf(&sc_document_dates.output, _("Document date \"%100s\" unparsable"),
784 document_date);
785 sc_document_dates = mp_set_subcheck_state(sc_document_dates, STATE_CRITICAL);
786 } else if (doc_data > srv_data + 30) {
787
788 xasprintf(&sc_document_dates.output, _("Document is %d seconds in the future"),
789 (int)doc_data - (int)srv_data);
790
791 sc_document_dates = mp_set_subcheck_state(sc_document_dates, STATE_CRITICAL);
792 } else if (doc_data < srv_data - maximum_age) {
793 time_t last_modified = (srv_data - doc_data);
794 if (last_modified > (60 * 60 * 24 * 2)) { // two days hardcoded?
795 xasprintf(&sc_document_dates.output, _("Last modified %.1f days ago"),
796 ((float)last_modified) / (60 * 60 * 24));
797 sc_document_dates = mp_set_subcheck_state(sc_document_dates, STATE_CRITICAL);
798 } else {
799 xasprintf(&sc_document_dates.output, _("Last modified %lld:%02d:%02d ago"),
800 (long long)last_modified / (60 * 60), (int)(last_modified / 60) % 60,
801 (int)last_modified % 60);
802 sc_document_dates = mp_set_subcheck_state(sc_document_dates, STATE_CRITICAL);
803 }
804 } else {
805 // TODO is this the OK case?
806 time_t last_modified = (srv_data - doc_data);
807 xasprintf(&sc_document_dates.output, _("Last modified %lld:%02d:%02d ago"),
808 (long long)last_modified / (60 * 60), (int)(last_modified / 60) % 60,
809 (int)last_modified % 60);
810 sc_document_dates = mp_set_subcheck_state(sc_document_dates, STATE_OK);
811 }
812 }
813
814 if (server_date) {
815 free(server_date);
816 }
817 if (document_date) {
818 free(document_date);
819 }
820
821 return sc_document_dates;
822}
823
824void curlhelp_free_statusline(curlhelp_statusline *status_line) { free(status_line->first_line); }
825
826int curlhelp_parse_statusline(const char *buf, curlhelp_statusline *status_line) {
827 /* find last start of a new header */
828 const char *start = strrstr2(buf, "\r\nHTTP/");
829 if (start != NULL) {
830 start += 2;
831 buf = start;
832 }
833
834 // Accept either LF or CRLF as end of line for the status line
835 // CRLF is the standard (RFC9112), but it is recommended to accept both
836 size_t length_of_first_line = strcspn(buf, "\r\n");
837 const char *first_line_end = &buf[length_of_first_line];
838 if (first_line_end == NULL) {
839 return -1;
840 }
841
842 size_t first_line_len = (size_t)(first_line_end - buf);
843 status_line->first_line = (char *)calloc(first_line_len + 1, sizeof(char));
844 if (status_line->first_line == NULL) {
845 return -1;
846 }
847
848 memcpy(status_line->first_line, buf, first_line_len);
849 status_line->first_line[first_line_len] = '\0';
850 char *first_line_buf = strdup(status_line->first_line);
851
852 /* protocol and version: "HTTP/x.x" SP or "HTTP/2" SP */
853 char *temp_string = strtok(first_line_buf, "/");
854 if (temp_string == NULL) {
855 if (verbose > 1) {
856 printf("%s: no / found\n", __func__);
857 }
858 free(first_line_buf);
859 return -1;
860 }
861
862 if (strcmp(temp_string, "HTTP") != 0) {
863 if (verbose > 1) {
864 printf("%s: string 'HTTP' not found\n", __func__);
865 }
866 free(first_line_buf);
867 return -1;
868 }
869
870 // try to find a space in the remaining string?
871 // the space after HTTP/1.1 probably
872 temp_string = strtok(NULL, " ");
873 if (temp_string == NULL) {
874 if (verbose > 1) {
875 printf("%s: no space after protocol definition\n", __func__);
876 }
877 free(first_line_buf);
878 return -1;
879 }
880
881 char *temp_string_2;
882 if (strchr(temp_string, '.') != NULL) {
883 /* HTTP 1.x case */
884 strtok(temp_string, ".");
885 status_line->http_major = (int)strtol(temp_string, &temp_string_2, 10);
886 if (*temp_string_2 != '\0') {
887 free(first_line_buf);
888 return -1;
889 }
890 strtok(NULL, " ");
891 status_line->http_minor = (int)strtol(temp_string, &temp_string_2, 10);
892 if (*temp_string_2 != '\0') {
893 free(first_line_buf);
894 return -1;
895 }
896 temp_string += 4; /* 1.x SP */
897 } else {
898 /* HTTP 2 case */
899 status_line->http_major = (int)strtol(temp_string, &temp_string_2, 10);
900 status_line->http_minor = 0;
901 temp_string += 2; /* 2 SP */
902 }
903
904 /* status code: "404" or "404.1", then SP */
905 temp_string = strtok(temp_string, " ");
906 if (temp_string == NULL) {
907 free(first_line_buf);
908 return -1;
909 }
910 if (strchr(temp_string, '.') != NULL) {
911 char *ppp;
912 ppp = strtok(temp_string, ".");
913 status_line->http_code = (int)strtol(ppp, &temp_string_2, 10);
914 if (*temp_string_2 != '\0') {
915 free(first_line_buf);
916 return -1;
917 }
918 ppp = strtok(NULL, "");
919 status_line->http_subcode = (int)strtol(ppp, &temp_string_2, 10);
920 if (*temp_string_2 != '\0') {
921 free(first_line_buf);
922 return -1;
923 }
924 temp_string += 6; /* 400.1 SP */
925 } else {
926 status_line->http_code = (int)strtol(temp_string, &temp_string_2, 10);
927 status_line->http_subcode = -1;
928 if (*temp_string_2 != '\0') {
929 free(first_line_buf);
930 return -1;
931 }
932 temp_string += 4; /* 400 SP */
933 }
934
935 /* Human readable message: "Not Found" CRLF */
936
937 temp_string = strtok(temp_string, "");
938 if (temp_string == NULL) {
939 status_line->msg = "";
940 return 0;
941 }
942 status_line->msg = status_line->first_line + (temp_string - first_line_buf);
943 free(first_line_buf);
944
945 return 0;
946}
947
948/* TODO: where to put this, it's actually part of sstrings2 (logically)?
949 */
950const char *strrstr2(const char *haystack, const char *needle) {
951 if (haystack == NULL || needle == NULL) {
952 return NULL;
953 }
954
955 if (haystack[0] == '\0' || needle[0] == '\0') {
956 return NULL;
957 }
958
959 int counter = 0;
960 const char *prev_pos = NULL;
961 const char *pos = haystack;
962 size_t len = strlen(needle);
963 for (;;) {
964 pos = strstr(pos, needle);
965 if (pos == NULL) {
966 if (counter == 0) {
967 return NULL;
968 }
969 return prev_pos;
970 }
971 counter++;
972 prev_pos = pos;
973 pos += len;
974 if (*pos == '\0') {
975 return prev_pos;
976 }
977 }
978}
979
980void curlhelp_freereadbuffer(curlhelp_read_curlbuf *buf) {
981 free(buf->buf);
982 buf->buf = NULL;
983}
984
985void curlhelp_freewritebuffer(curlhelp_write_curlbuf *buf) {
986 free(buf->buf);
987 buf->buf = NULL;
988}
989
990int curlhelp_initreadbuffer(curlhelp_read_curlbuf **buf, const char *data, size_t datalen) {
991 if ((*buf = calloc(1, sizeof(curlhelp_read_curlbuf))) == NULL) {
992 return 1;
993 }
994
995 (*buf)->buflen = datalen;
996 (*buf)->buf = (char *)calloc((*buf)->buflen, sizeof(char));
997 if ((*buf)->buf == NULL) {
998 return -1;
999 }
1000 memcpy((*buf)->buf, data, datalen);
1001 (*buf)->pos = 0;
1002 return 0;
1003}
1004
1005size_t curlhelp_buffer_read_callback(void *buffer, size_t size, size_t nmemb, void *stream) {
1006 curlhelp_read_curlbuf *buf = (curlhelp_read_curlbuf *)stream;
1007
1008 size_t minimalSize = min(nmemb * size, buf->buflen - buf->pos);
1009
1010 memcpy(buffer, buf->buf + buf->pos, minimalSize);
1011 buf->pos += minimalSize;
1012
1013 return minimalSize;
1014}
1015
1016int curlhelp_initwritebuffer(curlhelp_write_curlbuf **buf) {
1017 if ((*buf = calloc(1, sizeof(curlhelp_write_curlbuf))) == NULL) {
1018 return 1;
1019 }
1020 (*buf)->bufsize = DEFAULT_BUFFER_SIZE * sizeof(char);
1021 (*buf)->buflen = 0;
1022 (*buf)->buf = (char *)calloc((*buf)->bufsize, sizeof(char));
1023 if ((*buf)->buf == NULL) {
1024 return -1;
1025 }
1026 return 0;
1027}
1028
1029size_t curlhelp_buffer_write_callback(void *buffer, size_t size, size_t nmemb, void *stream) {
1030 curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream;
1031
1032 while (buf->bufsize < buf->buflen + size * nmemb + 1) {
1033 buf->bufsize = buf->bufsize * 2;
1034 buf->buf = (char *)realloc(buf->buf, buf->bufsize);
1035 if (buf->buf == NULL) {
1036 fprintf(stderr, "malloc failed (%d) %s\n", errno, strerror(errno));
1037 return 0;
1038 }
1039 }
1040
1041 memcpy(buf->buf + buf->buflen, buffer, size * nmemb);
1042 buf->buflen += size * nmemb;
1043 buf->buf[buf->buflen] = '\0';
1044
1045 return size * nmemb;
1046}
1047
1048void cleanup(check_curl_global_state global_state) {
1049 if (global_state.status_line_initialized) {
1050 curlhelp_free_statusline(global_state.status_line);
1051 }
1052 global_state.status_line_initialized = false;
1053
1054 if (global_state.curl_easy_initialized) {
1055 curl_easy_cleanup(global_state.curl);
1056 }
1057 global_state.curl_easy_initialized = false;
1058
1059 if (global_state.curl_global_initialized) {
1060 curl_global_cleanup();
1061 }
1062 global_state.curl_global_initialized = false;
1063
1064 if (global_state.body_buf_initialized) {
1065 curlhelp_freewritebuffer(global_state.body_buf);
1066 }
1067 global_state.body_buf_initialized = false;
1068
1069 if (global_state.header_buf_initialized) {
1070 curlhelp_freewritebuffer(global_state.header_buf);
1071 }
1072 global_state.header_buf_initialized = false;
1073
1074 if (global_state.put_buf_initialized) {
1075 curlhelp_freereadbuffer(global_state.put_buf);
1076 }
1077 global_state.put_buf_initialized = false;
1078
1079 if (global_state.header_list) {
1080 curl_slist_free_all(global_state.header_list);
1081 }
1082
1083 if (global_state.host) {
1084 curl_slist_free_all(global_state.host);
1085 }
1086}
1087
1088int lookup_host(const char *host, char *buf, size_t buflen, sa_family_t addr_family) {
1089 struct addrinfo hints = {
1090 .ai_family = addr_family,
1091 .ai_socktype = SOCK_STREAM,
1092 .ai_flags = AI_CANONNAME,
1093 };
1094
1095 struct addrinfo *result;
1096 int errcode = getaddrinfo(host, NULL, &hints, &result);
1097 if (errcode != 0) {
1098 return errcode;
1099 }
1100
1101 strcpy(buf, "");
1102 struct addrinfo *res = result;
1103
1104 size_t buflen_remaining = buflen - 1;
1105 size_t addrstr_len;
1106 char addrstr[100];
1107 void *ptr = {0};
1108 while (res) {
1109 switch (res->ai_family) {
1110 case AF_INET:
1111 ptr = &((struct sockaddr_in *)res->ai_addr)->sin_addr;
1112 break;
1113 case AF_INET6:
1114 ptr = &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
1115 break;
1116 }
1117
1118 inet_ntop(res->ai_family, ptr, addrstr, 100);
1119 if (verbose >= 1) {
1120 printf("* getaddrinfo IPv%d address: %s\n", res->ai_family == PF_INET6 ? 6 : 4,
1121 addrstr);
1122 }
1123
1124 // Append all IPs to buf as a comma-separated string
1125 addrstr_len = strlen(addrstr);
1126 if (buflen_remaining > addrstr_len + 1) {
1127 if (buf[0] != '\0') {
1128 strncat(buf, ",", buflen_remaining);
1129 buflen_remaining -= 1;
1130 }
1131 strncat(buf, addrstr, buflen_remaining);
1132 buflen_remaining -= addrstr_len;
1133 }
1134
1135 res = res->ai_next;
1136 }
1137
1138 freeaddrinfo(result);
1139
1140 return 0;
1141}
1142
1143/* Checks if the server 'reply' is one of the expected 'statuscodes' */
1144bool expected_statuscode(const char *reply, const char *statuscodes) {
1145 char *expected;
1146
1147 if ((expected = strdup(statuscodes)) == NULL) {
1148 die(STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n"));
1149 }
1150
1151 bool result = false;
1152 for (char *code = strtok(expected, ","); code != NULL; code = strtok(NULL, ",")) {
1153 if (strstr(reply, code) != NULL) {
1154 result = true;
1155 break;
1156 }
1157 }
1158
1159 free(expected);
1160 return result;
1161}
1162
1163/* returns a string "HTTP/1.x" or "HTTP/2" */
1164char *string_statuscode(int major, int minor) {
1165 static char buf[10];
1166
1167 switch (major) {
1168 case 1:
1169 snprintf(buf, sizeof(buf), "HTTP/%d.%d", major, minor);
1170 break;
1171 case 2:
1172 case 3:
1173 snprintf(buf, sizeof(buf), "HTTP/%d", major);
1174 break;
1175 default:
1176 /* assuming here HTTP/N with N>=4 */
1177 snprintf(buf, sizeof(buf), "HTTP/%d", major);
1178 break;
1179 }
1180
1181 return buf;
1182}
1183
1184/* check whether a file exists */
1185void test_file(char *path) {
1186 if (access(path, R_OK) == 0) {
1187 return;
1188 }
1189 usage2(_("file does not exist or is not readable"), path);
1190}
1191
1192mp_subcheck mp_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn,
1193 int days_till_exp_crit);
1194
1195mp_subcheck check_curl_certificate_checks(CURL *curl, X509 *cert, int warn_days_till_exp,
1196 int crit_days_till_exp) {
1197 mp_subcheck sc_cert_result = mp_subcheck_init();
1198 sc_cert_result = mp_set_subcheck_default_state(sc_cert_result, STATE_OK);
1199
1200#ifdef LIBCURL_FEATURE_SSL
1201 if (is_openssl_callback) {
1202# ifdef USE_OPENSSL
1203 /* check certificate with OpenSSL functions, curl has been built against OpenSSL
1204 * and we actually have OpenSSL in the monitoring tools
1205 */
1206 return mp_net_ssl_check_certificate(cert, warn_days_till_exp, crit_days_till_exp);
1207# else /* USE_OPENSSL */
1208 xasprintf(&result.output, "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL "
1209 "callback used and not linked against OpenSSL\n");
1210 mp_set_subcheck_state(result, STATE_CRITICAL);
1211# endif /* USE_OPENSSL */
1212 } else {
1213 struct curl_slist *slist;
1214
1215 cert_ptr_union cert_ptr = {0};
1216 cert_ptr.to_info = NULL;
1217 CURLcode res = curl_easy_getinfo(curl, CURLINFO_CERTINFO, &cert_ptr.to_info);
1218 if (!res && cert_ptr.to_info) {
1219# ifdef USE_OPENSSL
1220 /* We have no OpenSSL in libcurl, but we can use OpenSSL for X509 cert
1221 * parsing We only check the first certificate and assume it's the one of
1222 * the server
1223 */
1224 char *raw_cert = NULL;
1225 bool got_first_cert = false;
1226 for (int i = 0; i < cert_ptr.to_certinfo->num_of_certs; i++) {
1227 if (got_first_cert) {
1228 break;
1229 }
1230
1231 for (slist = cert_ptr.to_certinfo->certinfo[i]; slist; slist = slist->next) {
1232 if (verbose >= 2) {
1233 printf("%d ** %s\n", i, slist->data);
1234 }
1235 if (strncmp(slist->data, "Cert:", 5) == 0) {
1236 raw_cert = &slist->data[5];
1237 got_first_cert = true;
1238 break;
1239 }
1240 }
1241 }
1242
1243 if (!raw_cert) {
1244
1245 xasprintf(&sc_cert_result.output,
1246 _("Cannot retrieve certificates from CERTINFO information - "
1247 "certificate data was empty"));
1248 sc_cert_result = mp_set_subcheck_state(sc_cert_result, STATE_CRITICAL);
1249 return sc_cert_result;
1250 }
1251
1252 BIO *cert_BIO = BIO_new(BIO_s_mem());
1253 BIO_write(cert_BIO, raw_cert, (int)strlen(raw_cert));
1254
1255 cert = PEM_read_bio_X509(cert_BIO, NULL, NULL, NULL);
1256 if (!cert) {
1257 xasprintf(&sc_cert_result.output,
1258 _("Cannot read certificate from CERTINFO information - BIO error"));
1259 sc_cert_result = mp_set_subcheck_state(sc_cert_result, STATE_CRITICAL);
1260 return sc_cert_result;
1261 }
1262
1263 BIO_free(cert_BIO);
1264 return mp_net_ssl_check_certificate(cert, warn_days_till_exp, crit_days_till_exp);
1265# else /* USE_OPENSSL */
1266 /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our
1267 * disposal, so we use the libcurl CURLINFO data
1268 */
1269 return net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn,
1270 days_till_exp_crit);
1271# endif /* USE_OPENSSL */
1272 } else {
1273 xasprintf(&sc_cert_result.output,
1274 _("Cannot retrieve certificates - cURL returned %d - %s"), res,
1275 curl_easy_strerror(res));
1276 mp_set_subcheck_state(sc_cert_result, STATE_CRITICAL);
1277 }
1278 }
1279#endif /* LIBCURL_FEATURE_SSL */
1280
1281 return sc_cert_result;
1282}
1283
1284char *fmt_url(check_curl_working_state workingState) {
1285 char *url = calloc(DEFAULT_BUFFER_SIZE, sizeof(char));
1286 if (url == NULL) {
1287 die(STATE_UNKNOWN, "memory allocation failed");
1288 }
1289
1290 snprintf(url, DEFAULT_BUFFER_SIZE, "%s://%s:%d%s", workingState.use_ssl ? "https" : "http",
1291 (workingState.use_ssl & (workingState.host_name != NULL))
1292 ? workingState.host_name
1293 : workingState.server_address,
1294 workingState.serverPort, workingState.server_url);
1295
1296 return url;
1297}
diff --git a/plugins/check_curl.d/check_curl_helpers.h b/plugins/check_curl.d/check_curl_helpers.h
new file mode 100644
index 00000000..e77b763b
--- /dev/null
+++ b/plugins/check_curl.d/check_curl_helpers.h
@@ -0,0 +1,128 @@
1#include "./config.h"
2#include <curl/curl.h>
3#include "../picohttpparser/picohttpparser.h"
4#include "output.h"
5
6#if defined(HAVE_SSL) && defined(USE_OPENSSL)
7# include <openssl/opensslv.h>
8#endif
9
10enum {
11 MAX_IPV4_HOSTLENGTH = 255,
12};
13
14/* for buffers for header and body */
15typedef struct {
16 size_t buflen;
17 size_t bufsize;
18 char *buf;
19} curlhelp_write_curlbuf;
20
21/* for buffering the data sent in PUT */
22typedef struct {
23 size_t buflen;
24 off_t pos;
25 char *buf;
26} curlhelp_read_curlbuf;
27
28/* for parsing the HTTP status line */
29typedef struct {
30 int http_major; /* major version of the protocol, always 1 (HTTP/0.9
31 * never reached the big internet most likely) */
32 int http_minor; /* minor version of the protocol, usually 0 or 1 */
33 int http_code; /* HTTP return code as in RFC 2145 */
34 int http_subcode; /* Microsoft IIS extension, HTTP subcodes, see
35 * http://support.microsoft.com/kb/318380/en-us */
36 const char *msg; /* the human readable message */
37 char *first_line; /* a copy of the first line */
38} curlhelp_statusline;
39
40typedef struct {
41 bool curl_global_initialized;
42 bool curl_easy_initialized;
43
44 bool body_buf_initialized;
45 curlhelp_write_curlbuf *body_buf;
46
47 bool header_buf_initialized;
48 curlhelp_write_curlbuf *header_buf;
49
50 bool status_line_initialized;
51 curlhelp_statusline *status_line;
52
53 bool put_buf_initialized;
54 curlhelp_read_curlbuf *put_buf;
55
56 CURL *curl;
57
58 struct curl_slist *header_list;
59 struct curl_slist *host;
60} check_curl_global_state;
61
62/* to know the underlying SSL library used by libcurl */
63typedef enum curlhelp_ssl_library {
64 CURLHELP_SSL_LIBRARY_UNKNOWN,
65 CURLHELP_SSL_LIBRARY_OPENSSL,
66 CURLHELP_SSL_LIBRARY_LIBRESSL,
67 CURLHELP_SSL_LIBRARY_GNUTLS,
68 CURLHELP_SSL_LIBRARY_NSS
69} curlhelp_ssl_library;
70
71#define MAKE_LIBCURL_VERSION(major, minor, patch) ((major) * 0x10000 + (minor) * 0x100 + (patch))
72
73typedef struct {
74 int errorcode;
75 check_curl_global_state curl_state;
76 check_curl_working_state working_state;
77} check_curl_configure_curl_wrapper;
78
79check_curl_configure_curl_wrapper check_curl_configure_curl(check_curl_static_curl_config config,
80 check_curl_working_state working_state,
81 bool check_cert,
82 bool on_redirect_dependent,
83 int follow_method, long max_depth);
84
85void handle_curl_option_return_code(CURLcode res, const char *option);
86
87int curlhelp_initwritebuffer(curlhelp_write_curlbuf **buf);
88size_t curlhelp_buffer_write_callback(void * /*buffer*/, size_t /*size*/, size_t /*nmemb*/,
89 void * /*stream*/);
90void curlhelp_freewritebuffer(curlhelp_write_curlbuf * /*buf*/);
91
92int curlhelp_initreadbuffer(curlhelp_read_curlbuf **buf, const char * /*data*/, size_t /*datalen*/);
93size_t curlhelp_buffer_read_callback(void * /*buffer*/, size_t /*size*/, size_t /*nmemb*/,
94 void * /*stream*/);
95void curlhelp_freereadbuffer(curlhelp_read_curlbuf * /*buf*/);
96
97curlhelp_ssl_library curlhelp_get_ssl_library(void);
98const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library /*ssl_library*/);
99
100typedef union {
101 struct curl_slist *to_info;
102 struct curl_certinfo *to_certinfo;
103} cert_ptr_union;
104int net_noopenssl_check_certificate(cert_ptr_union *, int, int);
105
106int curlhelp_parse_statusline(const char * /*buf*/, curlhelp_statusline * /*status_line*/);
107void curlhelp_free_statusline(curlhelp_statusline * /*status_line*/);
108
109char *get_header_value(const struct phr_header *headers, size_t nof_headers, const char *header);
110mp_subcheck check_document_dates(const curlhelp_write_curlbuf * /*header_buf*/,
111 int /*maximum_age*/);
112size_t get_content_length(const curlhelp_write_curlbuf *header_buf,
113 const curlhelp_write_curlbuf *body_buf);
114int lookup_host(const char *host, char *buf, size_t buflen, sa_family_t addr_family);
115CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm);
116
117#define INET_ADDR_MAX_SIZE INET6_ADDRSTRLEN
118const char *strrstr2(const char *haystack, const char *needle);
119
120void cleanup(check_curl_global_state global_state);
121
122bool expected_statuscode(const char *reply, const char *statuscodes);
123char *string_statuscode(int major, int minor);
124
125void test_file(char *path);
126mp_subcheck check_curl_certificate_checks(CURL *curl, X509 *cert, int warn_days_till_exp,
127 int crit_days_till_exp);
128char *fmt_url(check_curl_working_state workingState);
diff --git a/plugins/check_curl.d/config.h b/plugins/check_curl.d/config.h
new file mode 100644
index 00000000..61067d46
--- /dev/null
+++ b/plugins/check_curl.d/config.h
@@ -0,0 +1,116 @@
1#pragma once
2
3#include "../../config.h"
4#include "../common.h"
5#include "../../lib/states.h"
6#include "../../lib/thresholds.h"
7#include <stddef.h>
8#include <string.h>
9#include <sys/socket.h>
10#include "curl/curl.h"
11#include "perfdata.h"
12#include "regex.h"
13
14enum {
15 MAX_RE_SIZE = 1024,
16 HTTP_PORT = 80,
17 HTTPS_PORT = 443,
18 MAX_PORT = 65535,
19 DEFAULT_MAX_REDIRS = 15
20};
21
22enum {
23 FOLLOW_HTTP_CURL = 0,
24 FOLLOW_LIBCURL = 1
25};
26
27enum {
28 STICKY_NONE = 0,
29 STICKY_HOST = 1,
30 STICKY_PORT = 2
31};
32
33#define HTTP_EXPECT "HTTP/"
34#define DEFAULT_BUFFER_SIZE 2048
35#define DEFAULT_SERVER_URL "/"
36
37typedef struct {
38 char *server_address;
39 char *server_url;
40 char *host_name;
41
42 char *http_method;
43
44 char *http_post_data;
45
46 unsigned short virtualPort;
47 unsigned short serverPort;
48
49 bool use_ssl;
50 bool no_body;
51} check_curl_working_state;
52
53check_curl_working_state check_curl_working_state_init();
54
55typedef struct {
56 bool automatic_decompression;
57 bool haproxy_protocol;
58 long socket_timeout;
59 sa_family_t sin_family;
60 long curl_http_version;
61 char **http_opt_headers;
62 size_t http_opt_headers_count;
63 long ssl_version;
64 char *client_cert;
65 char *client_privkey;
66 char *ca_cert;
67 bool verify_peer_and_host;
68 char user_agent[DEFAULT_BUFFER_SIZE];
69 char proxy_auth[MAX_INPUT_BUFFER];
70 char user_auth[MAX_INPUT_BUFFER];
71 char *http_content_type;
72 char *cookie_jar_file;
73} check_curl_static_curl_config;
74
75typedef struct {
76 check_curl_working_state initial_config;
77
78 check_curl_static_curl_config curl_config;
79 long max_depth;
80 int followmethod;
81 int followsticky;
82
83 int maximum_age;
84
85 // the original regex string from the command line
86 char regexp[MAX_RE_SIZE];
87
88 // the compiled regex for usage later
89 regex_t compiled_regex;
90
91 mp_state_enum state_regex;
92 bool invert_regex;
93 bool check_cert;
94 bool continue_after_check_cert;
95 int days_till_exp_warn;
96 int days_till_exp_crit;
97 mp_thresholds thlds;
98 mp_range page_length_limits;
99 bool page_length_limits_is_set;
100 struct {
101 char string[MAX_INPUT_BUFFER];
102 bool is_present;
103 } server_expect;
104 char string_expect[MAX_INPUT_BUFFER];
105 char header_expect[MAX_INPUT_BUFFER];
106 mp_state_enum on_redirect_result_state;
107 bool on_redirect_dependent;
108
109 bool show_extended_perfdata;
110 bool show_body;
111
112 bool output_format_is_set;
113 mp_output_format output_format;
114} check_curl_config;
115
116check_curl_config check_curl_config_init();