From 9f1ec43ce1637b41117d03b8456af8c0829a54f2 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:43:12 +0100 Subject: check_by_ssh: clang-format --- plugins/check_by_ssh.c | 481 +++++++++++++++++++++++-------------------------- 1 file changed, 227 insertions(+), 254 deletions(-) diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index 2a23b397..35aa1b8c 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -1,30 +1,30 @@ /***************************************************************************** -* -* Monitoring check_by_ssh plugin -* -* License: GPL -* Copyright (c) 2000-2008 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_by_ssh plugin -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_by_ssh plugin + * + * License: GPL + * Copyright (c) 2000-2008 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_by_ssh plugin + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_by_ssh"; const char *copyright = "2000-2008"; @@ -36,14 +36,14 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils_cmd.h" #ifndef NP_MAXARGS -#define NP_MAXARGS 1024 +# define NP_MAXARGS 1024 #endif -int process_arguments (int, char **); -int validate_arguments (void); -void comm_append (const char *); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void comm_append(const char *); +void print_help(void); +void print_usage(void); unsigned int commands = 0; unsigned int services = 0; @@ -61,9 +61,7 @@ char **service; bool passive = false; bool verbose = false; -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { char *status_text; int cresult; @@ -75,43 +73,42 @@ main (int argc, char **argv) remotecmd = ""; comm_append(SSH_COMMAND); - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); /* process arguments */ - if (process_arguments (argc, argv) == ERROR) + if (process_arguments(argc, argv) == ERROR) usage_va(_("Could not parse arguments")); /* Set signal handling and alarm timeout */ - if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) { + if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) { usage_va(_("Cannot catch SIGALRM")); } - alarm (timeout_interval); + alarm(timeout_interval); /* run the command */ if (verbose) { - printf ("Command: %s\n", commargv[0]); + printf("Command: %s\n", commargv[0]); for (int i = 1; i < commargc; i++) - printf ("Argument %i: %s\n", i, commargv[i]); + printf("Argument %i: %s\n", i, commargv[i]); } - result = cmd_run_array (commargv, &chld_out, &chld_err, 0); + result = cmd_run_array(commargv, &chld_out, &chld_err, 0); /* SSH returns 255 if connection attempt fails; include the first line of error output */ if (result == 255 && unknown_timeout) { - printf (_("SSH connection failed: %s\n"), - chld_err.lines > 0 ? chld_err.line[0] : "(no error output)"); + printf(_("SSH connection failed: %s\n"), chld_err.lines > 0 ? chld_err.line[0] : "(no error output)"); return STATE_UNKNOWN; } if (verbose) { - for(size_t i = 0; i < chld_out.lines; i++) + for (size_t i = 0; i < chld_out.lines; i++) printf("stdout: %s\n", chld_out.line[i]); - for(size_t i = 0; i < chld_err.lines; i++) + for (size_t i = 0; i < chld_err.lines; i++) printf("stderr: %s\n", chld_err.line[i]); } @@ -121,10 +118,9 @@ main (int argc, char **argv) skip_stderr = chld_err.lines; /* UNKNOWN or worse if (non-skipped) output found on stderr */ - if(chld_err.lines > (size_t)skip_stderr) { - printf (_("Remote command execution failed: %s\n"), - chld_err.line[skip_stderr]); - if ( warn_on_stderr ) + if (chld_err.lines > (size_t)skip_stderr) { + printf(_("Remote command execution failed: %s\n"), chld_err.line[skip_stderr]); + if (warn_on_stderr) return max_state_alt(result, STATE_WARNING); else return max_state_alt(result, STATE_UNKNOWN); @@ -132,144 +128,134 @@ main (int argc, char **argv) /* this is simple if we're not supposed to be passive. * Wrap up quickly and keep the tricks below */ - if(!passive) { + if (!passive) { if (chld_out.lines > (size_t)skip_stdout) for (size_t i = skip_stdout; i < chld_out.lines; i++) - puts (chld_out.line[i]); + puts(chld_out.line[i]); else - printf (_("%s - check_by_ssh: Remote command '%s' returned status %d\n"), - state_text(result), remotecmd, result); - return result; /* return error status from remote command */ + printf(_("%s - check_by_ssh: Remote command '%s' returned status %d\n"), state_text(result), remotecmd, result); + return result; /* return error status from remote command */ } - /* * Passive mode */ /* process output */ - if (!(fp = fopen (outputfile, "a"))) { - printf (_("SSH WARNING: could not open %s\n"), outputfile); - exit (STATE_UNKNOWN); + if (!(fp = fopen(outputfile, "a"))) { + printf(_("SSH WARNING: could not open %s\n"), outputfile); + exit(STATE_UNKNOWN); } - local_time = time (NULL); + local_time = time(NULL); commands = 0; - for(size_t i = skip_stdout; i < chld_out.lines; i++) { + for (size_t i = skip_stdout; i < chld_out.lines; i++) { status_text = chld_out.line[i++]; - if (i == chld_out.lines || strstr (chld_out.line[i], "STATUS CODE: ") == NULL) - die (STATE_UNKNOWN, _("%s: Error parsing output\n"), progname); - - if (service[commands] && status_text - && sscanf (chld_out.line[i], "STATUS CODE: %d", &cresult) == 1) - { - fprintf (fp, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n", - (int) local_time, host_shortname, service[commands++], - cresult, status_text); + if (i == chld_out.lines || strstr(chld_out.line[i], "STATUS CODE: ") == NULL) + die(STATE_UNKNOWN, _("%s: Error parsing output\n"), progname); + + if (service[commands] && status_text && sscanf(chld_out.line[i], "STATUS CODE: %d", &cresult) == 1) { + fprintf(fp, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n", (int)local_time, host_shortname, service[commands++], cresult, + status_text); } } - + /* Multiple commands and passive checking should always return OK */ return result; } /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; char *p1, *p2; int option = 0; - static struct option longopts[] = { - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {"verbose", no_argument, 0, 'v'}, - {"fork", no_argument, 0, 'f'}, - {"timeout", required_argument, 0, 't'}, - {"unknown-timeout", no_argument, 0, 'U'}, - {"host", required_argument, 0, 'H'}, /* backward compatibility */ - {"hostname", required_argument, 0, 'H'}, - {"port", required_argument,0,'p'}, - {"output", required_argument, 0, 'O'}, - {"name", required_argument, 0, 'n'}, - {"services", required_argument, 0, 's'}, - {"identity", required_argument, 0, 'i'}, - {"user", required_argument, 0, 'u'}, - {"logname", required_argument, 0, 'l'}, - {"command", required_argument, 0, 'C'}, - {"skip", optional_argument, 0, 'S'}, /* backwards compatibility */ - {"skip-stdout", optional_argument, 0, 'S'}, - {"skip-stderr", optional_argument, 0, 'E'}, - {"warn-on-stderr", no_argument, 0, 'W'}, - {"proto1", no_argument, 0, '1'}, - {"proto2", no_argument, 0, '2'}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {"ssh-option", required_argument, 0, 'o'}, - {"quiet", no_argument, 0, 'q'}, - {"configfile", optional_argument, 0, 'F'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {"verbose", no_argument, 0, 'v'}, + {"fork", no_argument, 0, 'f'}, + {"timeout", required_argument, 0, 't'}, + {"unknown-timeout", no_argument, 0, 'U'}, + {"host", required_argument, 0, 'H'}, /* backward compatibility */ + {"hostname", required_argument, 0, 'H'}, + {"port", required_argument, 0, 'p'}, + {"output", required_argument, 0, 'O'}, + {"name", required_argument, 0, 'n'}, + {"services", required_argument, 0, 's'}, + {"identity", required_argument, 0, 'i'}, + {"user", required_argument, 0, 'u'}, + {"logname", required_argument, 0, 'l'}, + {"command", required_argument, 0, 'C'}, + {"skip", optional_argument, 0, 'S'}, /* backwards compatibility */ + {"skip-stdout", optional_argument, 0, 'S'}, + {"skip-stderr", optional_argument, 0, 'E'}, + {"warn-on-stderr", no_argument, 0, 'W'}, + {"proto1", no_argument, 0, '1'}, + {"proto2", no_argument, 0, '2'}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {"ssh-option", required_argument, 0, 'o'}, + {"quiet", no_argument, 0, 'q'}, + {"configfile", optional_argument, 0, 'F'}, + {0, 0, 0, 0}}; if (argc < 2) return ERROR; for (c = 1; c < argc; c++) - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); while (1) { - c = getopt_long (argc, argv, "Vvh1246fqt:UH:O:p:i:u:l:C:S::E::n:s:o:F:", longopts, - &option); + c = getopt_long(argc, argv, "Vvh1246fqt:UH:O:p:i:u:l:C:S::E::n:s:o:F:", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'v': /* help */ + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'v': /* help */ verbose = true; break; - case 't': /* timeout period */ - if (!is_integer (optarg)) + case 't': /* timeout period */ + if (!is_integer(optarg)) usage_va(_("Timeout interval must be a positive integer")); else - timeout_interval = atoi (optarg); + timeout_interval = atoi(optarg); break; case 'U': unknown_timeout = true; break; - case 'H': /* host */ + case 'H': /* host */ hostname = optarg; break; case 'p': /* port number */ - if (!is_integer (optarg)) + if (!is_integer(optarg)) usage_va(_("Port must be a positive integer")); comm_append("-p"); comm_append(optarg); break; - case 'O': /* output file */ + case 'O': /* output file */ outputfile = optarg; passive = true; break; - case 's': /* description of service to check */ + case 's': /* description of service to check */ p1 = optarg; - service = realloc (service, (++services) * sizeof(char *)); - while ((p2 = index (p1, ':'))) { + service = realloc(service, (++services) * sizeof(char *)); + while ((p2 = index(p1, ':'))) { *p2 = '\0'; service[services - 1] = p1; - service = realloc (service, (++services) * sizeof(char *)); + service = realloc(service, (++services) * sizeof(char *)); p1 = p2 + 1; } service[services - 1] = p1; break; - case 'n': /* short name of host in the monitoring configuration */ + case 'n': /* short name of host in the monitoring configuration */ host_shortname = optarg; break; @@ -277,67 +263,67 @@ process_arguments (int argc, char **argv) comm_append("-l"); comm_append(optarg); break; - case 'l': /* login name */ + case 'l': /* login name */ comm_append("-l"); comm_append(optarg); break; - case 'i': /* identity */ + case 'i': /* identity */ comm_append("-i"); comm_append(optarg); break; - case '1': /* Pass these switches directly to ssh */ + case '1': /* Pass these switches directly to ssh */ comm_append("-1"); break; - case '2': /* 1 to force version 1, 2 to force version 2 */ + case '2': /* 1 to force version 1, 2 to force version 2 */ comm_append("-2"); break; - case '4': /* -4 for IPv4 */ + case '4': /* -4 for IPv4 */ comm_append("-4"); break; - case '6': /* -6 for IPv6 */ + case '6': /* -6 for IPv6 */ comm_append("-6"); break; - case 'f': /* fork to background */ + case 'f': /* fork to background */ comm_append("-f"); break; - case 'C': /* Command for remote machine */ + case 'C': /* Command for remote machine */ commands++; if (commands > 1) - xasprintf (&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd); - xasprintf (&remotecmd, "%s%s", remotecmd, optarg); + xasprintf(&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd); + xasprintf(&remotecmd, "%s%s", remotecmd, optarg); break; - case 'S': /* skip n (or all) lines on stdout */ + case 'S': /* skip n (or all) lines on stdout */ if (optarg == NULL) skip_stdout = -1; /* skip all output on stdout */ - else if (!is_integer (optarg)) + else if (!is_integer(optarg)) usage_va(_("skip-stdout argument must be an integer")); else - skip_stdout = atoi (optarg); + skip_stdout = atoi(optarg); break; - case 'E': /* skip n (or all) lines on stderr */ + case 'E': /* skip n (or all) lines on stderr */ if (optarg == NULL) skip_stderr = -1; /* skip all output on stderr */ - else if (!is_integer (optarg)) + else if (!is_integer(optarg)) usage_va(_("skip-stderr argument must be an integer")); else - skip_stderr = atoi (optarg); + skip_stderr = atoi(optarg); break; - case 'W': /* exit with warning if there is an output on stderr */ + case 'W': /* exit with warning if there is an output on stderr */ warn_on_stderr = 1; break; - case 'o': /* Extra options for the ssh command */ + case 'o': /* Extra options for the ssh command */ comm_append("-o"); comm_append(optarg); break; - case 'q': /* Tell the ssh command to be quiet */ + case 'q': /* Tell the ssh command to be quiet */ comm_append("-q"); break; - case 'F': /* ssh configfile */ + case 'F': /* ssh configfile */ comm_append("-F"); comm_append(optarg); break; - default: /* help */ + default: /* help */ usage5(); } } @@ -345,7 +331,7 @@ process_arguments (int argc, char **argv) c = optind; if (hostname == NULL) { if (c <= argc) { - die (STATE_UNKNOWN, _("%s: You must provide a host name\n"), progname); + die(STATE_UNKNOWN, _("%s: You must provide a host name\n"), progname); } hostname = argv[c++]; } @@ -353,143 +339,130 @@ process_arguments (int argc, char **argv) if (strlen(remotecmd) == 0) { for (; c < argc; c++) if (strlen(remotecmd) > 0) - xasprintf (&remotecmd, "%s %s", remotecmd, argv[c]); + xasprintf(&remotecmd, "%s %s", remotecmd, argv[c]); else - xasprintf (&remotecmd, "%s", argv[c]); + xasprintf(&remotecmd, "%s", argv[c]); } if (commands > 1 || passive) - xasprintf (&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd); + xasprintf(&remotecmd, "%s;echo STATUS CODE: $?;", remotecmd); - if (remotecmd == NULL || strlen (remotecmd) <= 1) + if (remotecmd == NULL || strlen(remotecmd) <= 1) usage_va(_("No remotecmd")); comm_append(hostname); comm_append(remotecmd); - return validate_arguments (); + return validate_arguments(); } - -void -comm_append (const char *str) -{ +void comm_append(const char *str) { if (++commargc > NP_MAXARGS) die(STATE_UNKNOWN, _("%s: Argument limit of %d exceeded\n"), progname, NP_MAXARGS); - if ((commargv = (char **)realloc(commargv, (commargc+1) * sizeof(char *))) == NULL) + if ((commargv = (char **)realloc(commargv, (commargc + 1) * sizeof(char *))) == NULL) die(STATE_UNKNOWN, _("Can not (re)allocate 'commargv' buffer\n")); - commargv[commargc-1] = strdup(str); + commargv[commargc - 1] = strdup(str); commargv[commargc] = NULL; - } -int -validate_arguments (void) -{ +int validate_arguments(void) { if (remotecmd == NULL || hostname == NULL) return ERROR; if (passive && commands != services) - die (STATE_UNKNOWN, _("%s: In passive mode, you must provide a service name for each command.\n"), progname); + die(STATE_UNKNOWN, _("%s: In passive mode, you must provide a service name for each command.\n"), progname); if (passive && host_shortname == NULL) - die (STATE_UNKNOWN, _("%s: In passive mode, you must provide the host short name from the monitoring configs.\n"), progname); + die(STATE_UNKNOWN, _("%s: In passive mode, you must provide the host short name from the monitoring configs.\n"), progname); return OK; } - -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Karl DeBisschop \n"); - printf (COPYRIGHT, copyright, email); - - printf (_("This plugin uses SSH to execute commands on a remote host")); - - printf ("\n\n"); - - print_usage (); - - printf (UT_HELP_VRSN); - - printf (UT_EXTRA_OPTS); - - printf (UT_HOST_PORT, 'p', "none"); - - printf (UT_IPv46); - - printf (" %s\n", "-1, --proto1"); - printf (" %s\n", _("tell ssh to use Protocol 1 [optional]")); - printf (" %s\n", "-2, --proto2"); - printf (" %s\n", _("tell ssh to use Protocol 2 [optional]")); - printf (" %s\n", "-S, --skip-stdout[=n]"); - printf (" %s\n", _("Ignore all or (if specified) first n lines on STDOUT [optional]")); - printf (" %s\n", "-E, --skip-stderr[=n]"); - printf (" %s\n", _("Ignore all or (if specified) first n lines on STDERR [optional]")); - printf (" %s\n", "-W, --warn-on-stderr]"); - printf (" %s\n", _("Exit with an warning, if there is an output on STDERR")); - printf (" %s\n", "-f"); - printf (" %s\n", _("tells ssh to fork rather than create a tty [optional]. This will always return OK if ssh is executed")); - printf (" %s\n","-C, --command='COMMAND STRING'"); - printf (" %s\n", _("command to execute on the remote machine")); - printf (" %s\n","-l, --logname=USERNAME"); - printf (" %s\n", _("SSH user name on remote host [optional]")); - printf (" %s\n","-i, --identity=KEYFILE"); - printf (" %s\n", _("identity of an authorized key [optional]")); - printf (" %s\n","-O, --output=FILE"); - printf (" %s\n", _("external command file for monitoring [optional]")); - printf (" %s\n","-s, --services=LIST"); - printf (" %s\n", _("list of monitoring service names, separated by ':' [optional]")); - printf (" %s\n","-n, --name=NAME"); - printf (" %s\n", _("short name of host in the monitoring configuration [optional]")); - printf (" %s\n","-o, --ssh-option=OPTION"); - printf (" %s\n", _("Call ssh with '-o OPTION' (may be used multiple times) [optional]")); - printf (" %s\n","-F, --configfile"); - printf (" %s\n", _("Tell ssh to use this configfile [optional]")); - printf (" %s\n","-q, --quiet"); - printf (" %s\n", _("Tell ssh to suppress warning and diagnostic messages [optional]")); - printf (UT_WARN_CRIT); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf (" %s\n","-U, --unknown-timeout"); - printf (" %s\n", _("Make connection problems return UNKNOWN instead of CRITICAL")); - printf (UT_VERBOSE); +void print_help(void) { + print_revision(progname, NP_VERSION); + + printf("Copyright (c) 1999 Karl DeBisschop \n"); + printf(COPYRIGHT, copyright, email); + + printf(_("This plugin uses SSH to execute commands on a remote host")); + + printf("\n\n"); + + print_usage(); + + printf(UT_HELP_VRSN); + + printf(UT_EXTRA_OPTS); + + printf(UT_HOST_PORT, 'p', "none"); + + printf(UT_IPv46); + + printf(" %s\n", "-1, --proto1"); + printf(" %s\n", _("tell ssh to use Protocol 1 [optional]")); + printf(" %s\n", "-2, --proto2"); + printf(" %s\n", _("tell ssh to use Protocol 2 [optional]")); + printf(" %s\n", "-S, --skip-stdout[=n]"); + printf(" %s\n", _("Ignore all or (if specified) first n lines on STDOUT [optional]")); + printf(" %s\n", "-E, --skip-stderr[=n]"); + printf(" %s\n", _("Ignore all or (if specified) first n lines on STDERR [optional]")); + printf(" %s\n", "-W, --warn-on-stderr]"); + printf(" %s\n", _("Exit with an warning, if there is an output on STDERR")); + printf(" %s\n", "-f"); + printf(" %s\n", _("tells ssh to fork rather than create a tty [optional]. This will always return OK if ssh is executed")); + printf(" %s\n", "-C, --command='COMMAND STRING'"); + printf(" %s\n", _("command to execute on the remote machine")); + printf(" %s\n", "-l, --logname=USERNAME"); + printf(" %s\n", _("SSH user name on remote host [optional]")); + printf(" %s\n", "-i, --identity=KEYFILE"); + printf(" %s\n", _("identity of an authorized key [optional]")); + printf(" %s\n", "-O, --output=FILE"); + printf(" %s\n", _("external command file for monitoring [optional]")); + printf(" %s\n", "-s, --services=LIST"); + printf(" %s\n", _("list of monitoring service names, separated by ':' [optional]")); + printf(" %s\n", "-n, --name=NAME"); + printf(" %s\n", _("short name of host in the monitoring configuration [optional]")); + printf(" %s\n", "-o, --ssh-option=OPTION"); + printf(" %s\n", _("Call ssh with '-o OPTION' (may be used multiple times) [optional]")); + printf(" %s\n", "-F, --configfile"); + printf(" %s\n", _("Tell ssh to use this configfile [optional]")); + printf(" %s\n", "-q, --quiet"); + printf(" %s\n", _("Tell ssh to suppress warning and diagnostic messages [optional]")); + printf(UT_WARN_CRIT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(" %s\n", "-U, --unknown-timeout"); + printf(" %s\n", _("Make connection problems return UNKNOWN instead of CRITICAL")); + printf(UT_VERBOSE); + printf("\n"); + printf(" %s\n", _("The most common mode of use is to refer to a local identity file with")); + printf(" %s\n", _("the '-i' option. In this mode, the identity pair should have a null")); + printf(" %s\n", _("passphrase and the public key should be listed in the authorized_keys")); + printf(" %s\n", _("file of the remote host. Usually the key will be restricted to running")); + printf(" %s\n", _("only one command on the remote server. If the remote SSH server tracks")); + printf(" %s\n", _("invocation arguments, the one remote program may be an agent that can")); + printf(" %s\n", _("execute additional commands as proxy")); + printf("\n"); + printf(" %s\n", _("To use passive mode, provide multiple '-C' options, and provide")); + printf(" %s\n", _("all of -O, -s, and -n options (servicelist order must match '-C'options)")); printf("\n"); - printf (" %s\n", _("The most common mode of use is to refer to a local identity file with")); - printf (" %s\n", _("the '-i' option. In this mode, the identity pair should have a null")); - printf (" %s\n", _("passphrase and the public key should be listed in the authorized_keys")); - printf (" %s\n", _("file of the remote host. Usually the key will be restricted to running")); - printf (" %s\n", _("only one command on the remote server. If the remote SSH server tracks")); - printf (" %s\n", _("invocation arguments, the one remote program may be an agent that can")); - printf (" %s\n", _("execute additional commands as proxy")); - printf("\n"); - printf (" %s\n", _("To use passive mode, provide multiple '-C' options, and provide")); - printf (" %s\n", _("all of -O, -s, and -n options (servicelist order must match '-C'options)")); - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n", "$ check_by_ssh -H localhost -n lh -s c1:c2:c3 -C uptime -C uptime -C uptime -O /tmp/foo"); - printf (" %s\n", "$ cat /tmp/foo"); - printf (" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c1;0; up 2 days"); - printf (" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c2;0; up 2 days"); - printf (" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c3;0; up 2 days"); + printf("%s\n", _("Examples:")); + printf(" %s\n", "$ check_by_ssh -H localhost -n lh -s c1:c2:c3 -C uptime -C uptime -C uptime -O /tmp/foo"); + printf(" %s\n", "$ cat /tmp/foo"); + printf(" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c1;0; up 2 days"); + printf(" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c2;0; up 2 days"); + printf(" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c3;0; up 2 days"); printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s -H -C [-fqvU] [-1|-2] [-4|-6]\n" - " [-S [lines]] [-E [lines]] [-W] [-t timeout] [-i identity]\n" - " [-l user] [-n name] [-s servicelist] [-O outputfile]\n" - " [-p port] [-o ssh-option] [-F configfile]\n", - progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s -H -C [-fqvU] [-1|-2] [-4|-6]\n" + " [-S [lines]] [-E [lines]] [-W] [-t timeout] [-i identity]\n" + " [-l user] [-n name] [-s servicelist] [-O outputfile]\n" + " [-p port] [-o ssh-option] [-F configfile]\n", + progname); } -- cgit v1.2.3-74-g34f1 From 744568f1f804f6676358a4ad654e4319598cebdf Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:44:09 +0100 Subject: check_by_ssh: Copyright update --- plugins/check_by_ssh.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index 35aa1b8c..4bcac003 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -3,7 +3,7 @@ * Monitoring check_by_ssh plugin * * License: GPL - * Copyright (c) 2000-2008 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -27,7 +27,7 @@ *****************************************************************************/ const char *progname = "check_by_ssh"; -const char *copyright = "2000-2008"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From ba47cca3ef026209868da044741554cbb6c2bb3b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:45:58 +0100 Subject: check_by_ssh: do not export local symbols --- plugins/check_by_ssh.c | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index 4bcac003..598e0463 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -39,27 +39,27 @@ const char *email = "devel@monitoring-plugins.org"; # define NP_MAXARGS 1024 #endif -int process_arguments(int, char **); -int validate_arguments(void); -void comm_append(const char *); -void print_help(void); +static int process_arguments(int, char **); +static int validate_arguments(void); +static void comm_append(const char *); +static void print_help(void); void print_usage(void); -unsigned int commands = 0; -unsigned int services = 0; -int skip_stdout = 0; -int skip_stderr = 0; -int warn_on_stderr = 0; -bool unknown_timeout = false; -char *remotecmd = NULL; -char **commargv = NULL; -int commargc = 0; -char *hostname = NULL; -char *outputfile = NULL; -char *host_shortname = NULL; -char **service; -bool passive = false; -bool verbose = false; +static unsigned int commands = 0; +static unsigned int services = 0; +static int skip_stdout = 0; +static int skip_stderr = 0; +static int warn_on_stderr = 0; +static bool unknown_timeout = false; +static char *remotecmd = NULL; +static char **commargv = NULL; +static int commargc = 0; +static char *hostname = NULL; +static char *outputfile = NULL; +static char *host_shortname = NULL; +static char **service; +static bool passive = false; +static bool verbose = false; int main(int argc, char **argv) { -- cgit v1.2.3-74-g34f1 From 060bd01d89a6da0a5a7c3c1779c98a2b2c8c0c53 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:50:34 +0100 Subject: check_by_ssh: linter fixes --- plugins/check_by_ssh.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c index 598e0463..905b2393 100644 --- a/plugins/check_by_ssh.c +++ b/plugins/check_by_ssh.c @@ -39,9 +39,9 @@ const char *email = "devel@monitoring-plugins.org"; # define NP_MAXARGS 1024 #endif -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static int validate_arguments(void); -static void comm_append(const char *); +static void comm_append(const char * /*str*/); static void print_help(void); void print_usage(void); @@ -67,8 +67,9 @@ int main(int argc, char **argv) { int cresult; int result = STATE_UNKNOWN; time_t local_time; - FILE *fp = NULL; - output chld_out, chld_err; + FILE *file_pointer = NULL; + output chld_out; + output chld_err; remotecmd = ""; comm_append(SSH_COMMAND); @@ -122,8 +123,7 @@ int main(int argc, char **argv) { printf(_("Remote command execution failed: %s\n"), chld_err.line[skip_stderr]); if (warn_on_stderr) return max_state_alt(result, STATE_WARNING); - else - return max_state_alt(result, STATE_UNKNOWN); + return max_state_alt(result, STATE_UNKNOWN); } /* this is simple if we're not supposed to be passive. @@ -142,7 +142,7 @@ int main(int argc, char **argv) { */ /* process output */ - if (!(fp = fopen(outputfile, "a"))) { + if (!(file_pointer = fopen(outputfile, "a"))) { printf(_("SSH WARNING: could not open %s\n"), outputfile); exit(STATE_UNKNOWN); } @@ -155,8 +155,8 @@ int main(int argc, char **argv) { die(STATE_UNKNOWN, _("%s: Error parsing output\n"), progname); if (service[commands] && status_text && sscanf(chld_out.line[i], "STATUS CODE: %d", &cresult) == 1) { - fprintf(fp, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n", (int)local_time, host_shortname, service[commands++], cresult, - status_text); + fprintf(file_pointer, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n", (int)local_time, host_shortname, service[commands++], + cresult, status_text); } } @@ -167,7 +167,8 @@ int main(int argc, char **argv) { /* process command-line arguments */ int process_arguments(int argc, char **argv) { int c; - char *p1, *p2; + char *p1; + char *p2; int option = 0; static struct option longopts[] = {{"version", no_argument, 0, 'V'}, -- cgit v1.2.3-74-g34f1 From 80ec3f0f046384399d4850b06806815cbc5cc7c9 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:51:49 +0100 Subject: check_cluster: clang-format --- plugins/check_cluster.c | 247 ++++++++++++++++++++++-------------------------- 1 file changed, 112 insertions(+), 135 deletions(-) diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c index e1ede9f7..aa555280 100644 --- a/plugins/check_cluster.c +++ b/plugins/check_cluster.c @@ -1,26 +1,26 @@ /***************************************************************************** -* -* check_cluster.c - Host and Service Cluster Plugin for Monitoring -* -* License: GPL -* Copyright (c) 2000-2004 Ethan Galstad (nagios@nagios.org) -* Copyright (c) 2007 Monitoring Plugins Development Team -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * check_cluster.c - Host and Service Cluster Plugin for Monitoring + * + * License: GPL + * Copyright (c) 2000-2004 Ethan Galstad (nagios@nagios.org) + * Copyright (c) 2007 Monitoring Plugins Development Team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_cluster"; const char *copyright = "2000-2007"; @@ -30,63 +30,61 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "utils_base.h" -#define CHECK_SERVICES 1 -#define CHECK_HOSTS 2 +#define CHECK_SERVICES 1 +#define CHECK_HOSTS 2 -void print_help (void); -void print_usage (void); +void print_help(void); +void print_usage(void); -int total_services_ok=0; -int total_services_warning=0; -int total_services_unknown=0; -int total_services_critical=0; +int total_services_ok = 0; +int total_services_warning = 0; +int total_services_unknown = 0; +int total_services_critical = 0; -int total_hosts_up=0; -int total_hosts_down=0; -int total_hosts_unreachable=0; +int total_hosts_up = 0; +int total_hosts_down = 0; +int total_hosts_unreachable = 0; char *warn_threshold; char *crit_threshold; -int check_type=CHECK_SERVICES; +int check_type = CHECK_SERVICES; -char *data_vals=NULL; -char *label=NULL; +char *data_vals = NULL; +char *label = NULL; -int verbose=0; +int verbose = 0; -int process_arguments(int,char **); +int process_arguments(int, char **); - - -int main(int argc, char **argv){ +int main(int argc, char **argv) { char *ptr; int data_val; - int return_code=STATE_OK; + int return_code = STATE_OK; thresholds *thresholds = NULL; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts(&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if(process_arguments(argc,argv)==ERROR) + if (process_arguments(argc, argv) == ERROR) usage(_("Could not parse arguments")); /* Initialize the thresholds */ set_thresholds(&thresholds, warn_threshold, crit_threshold); - if(verbose) + if (verbose) print_thresholds("check_cluster", thresholds); /* check the data values */ - for(ptr=strtok(data_vals,",");ptr!=NULL;ptr=strtok(NULL,",")){ + for (ptr = strtok(data_vals, ","); ptr != NULL; ptr = strtok(NULL, ",")) { - data_val=atoi(ptr); + data_val = atoi(ptr); - if(check_type==CHECK_SERVICES){ - switch(data_val){ + if (check_type == CHECK_SERVICES) { + switch (data_val) { case 0: total_services_ok++; break; @@ -101,10 +99,9 @@ int main(int argc, char **argv){ break; default: break; - } - } - else{ - switch(data_val){ + } + } else { + switch (data_val) { case 0: total_hosts_up++; break; @@ -116,67 +113,54 @@ int main(int argc, char **argv){ break; default: break; - } - } - } - + } + } + } /* return the status of the cluster */ - if(check_type==CHECK_SERVICES){ - return_code=get_status(total_services_warning+total_services_unknown+total_services_critical, thresholds); - printf("CLUSTER %s: %s: %d ok, %d warning, %d unknown, %d critical\n", - state_text(return_code), (label==NULL)?"Service cluster":label, - total_services_ok,total_services_warning, - total_services_unknown,total_services_critical); - } - else{ - return_code=get_status(total_hosts_down+total_hosts_unreachable, thresholds); - printf("CLUSTER %s: %s: %d up, %d down, %d unreachable\n", - state_text(return_code), (label==NULL)?"Host cluster":label, - total_hosts_up,total_hosts_down,total_hosts_unreachable); + if (check_type == CHECK_SERVICES) { + return_code = get_status(total_services_warning + total_services_unknown + total_services_critical, thresholds); + printf("CLUSTER %s: %s: %d ok, %d warning, %d unknown, %d critical\n", state_text(return_code), + (label == NULL) ? "Service cluster" : label, total_services_ok, total_services_warning, total_services_unknown, + total_services_critical); + } else { + return_code = get_status(total_hosts_down + total_hosts_unreachable, thresholds); + printf("CLUSTER %s: %s: %d up, %d down, %d unreachable\n", state_text(return_code), (label == NULL) ? "Host cluster" : label, + total_hosts_up, total_hosts_down, total_hosts_unreachable); } return return_code; } - - -int process_arguments(int argc, char **argv){ +int process_arguments(int argc, char **argv) { int c; char *ptr; - int option=0; - static struct option longopts[]={ - {"data", required_argument,0,'d'}, - {"warning", required_argument,0,'w'}, - {"critical", required_argument,0,'c'}, - {"label", required_argument,0,'l'}, - {"host", no_argument, 0,'h'}, - {"service", no_argument, 0,'s'}, - {"verbose", no_argument, 0,'v'}, - {"version", no_argument, 0,'V'}, - {"help", no_argument, 0,'H'}, - {0,0,0,0} - }; + int option = 0; + static struct option longopts[] = {{"data", required_argument, 0, 'd'}, {"warning", required_argument, 0, 'w'}, + {"critical", required_argument, 0, 'c'}, {"label", required_argument, 0, 'l'}, + {"host", no_argument, 0, 'h'}, {"service", no_argument, 0, 's'}, + {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'H'}, {0, 0, 0, 0}}; /* no options were supplied */ - if(argc<2) + if (argc < 2) return ERROR; - while(1){ + while (1) { - c=getopt_long(argc,argv,"hHsvVw:c:d:l:",longopts,&option); + c = getopt_long(argc, argv, "hHsvVw:c:d:l:", longopts, &option); - if(c==-1 || c==EOF || c==1) + if (c == -1 || c == EOF || c == 1) break; - switch(c){ + switch (c) { case 'h': /* host cluster */ - check_type=CHECK_HOSTS; + check_type = CHECK_HOSTS; break; case 's': /* service cluster */ - check_type=CHECK_SERVICES; + check_type = CHECK_SERVICES; break; case 'w': /* warning threshold */ @@ -188,20 +172,20 @@ int process_arguments(int argc, char **argv){ break; case 'd': /* data values */ - data_vals=(char *)strdup(optarg); + data_vals = (char *)strdup(optarg); /* validate data */ - for (ptr=data_vals;ptr!=NULL;ptr+=2){ - if (ptr[0]<'0' || ptr[0]>'3') + for (ptr = data_vals; ptr != NULL; ptr += 2) { + if (ptr[0] < '0' || ptr[0] > '3') return ERROR; - if (ptr[1]=='\0') + if (ptr[1] == '\0') break; - if (ptr[1]!=',') + if (ptr[1] != ',') return ERROR; } break; case 'l': /* text label */ - label=(char *)strdup(optarg); + label = (char *)strdup(optarg); break; case 'v': /* verbose */ @@ -209,8 +193,8 @@ int process_arguments(int argc, char **argv){ break; case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); break; case 'H': /* help */ @@ -221,20 +205,18 @@ int process_arguments(int argc, char **argv){ default: return ERROR; break; - } + } } - if(data_vals==NULL) + if (data_vals == NULL) return ERROR; return OK; } -void -print_help(void) -{ +void print_help(void) { print_revision(progname, NP_VERSION); - printf ("Copyright (c) 2000-2004 Ethan Galstad (nagios@nagios.org)\n"); + printf("Copyright (c) 2000-2004 Ethan Galstad (nagios@nagios.org)\n"); printf(COPYRIGHT, copyright, email); printf(_("Host/Service Cluster Plugin for Monitoring")); @@ -245,21 +227,21 @@ print_help(void) printf("\n"); printf("%s\n", _("Options:")); printf(UT_EXTRA_OPTS); - printf (" %s\n", "-s, --service"); - printf (" %s\n", _("Check service cluster status")); - printf (" %s\n", "-h, --host"); - printf (" %s\n", _("Check host cluster status")); - printf (" %s\n", "-l, --label=STRING"); - printf (" %s\n", _("Optional prepended text output (i.e. \"Host cluster\")")); - printf (" %s\n", "-w, --warning=THRESHOLD"); - printf (" %s\n", _("Specifies the range of hosts or services in cluster that must be in a")); - printf (" %s\n", _("non-OK state in order to return a WARNING status level")); - printf (" %s\n", "-c, --critical=THRESHOLD"); - printf (" %s\n", _("Specifies the range of hosts or services in cluster that must be in a")); - printf (" %s\n", _("non-OK state in order to return a CRITICAL status level")); - printf (" %s\n", "-d, --data=LIST"); - printf (" %s\n", _("The status codes of the hosts or services in the cluster, separated by")); - printf (" %s\n", _("commas")); + printf(" %s\n", "-s, --service"); + printf(" %s\n", _("Check service cluster status")); + printf(" %s\n", "-h, --host"); + printf(" %s\n", _("Check host cluster status")); + printf(" %s\n", "-l, --label=STRING"); + printf(" %s\n", _("Optional prepended text output (i.e. \"Host cluster\")")); + printf(" %s\n", "-w, --warning=THRESHOLD"); + printf(" %s\n", _("Specifies the range of hosts or services in cluster that must be in a")); + printf(" %s\n", _("non-OK state in order to return a WARNING status level")); + printf(" %s\n", "-c, --critical=THRESHOLD"); + printf(" %s\n", _("Specifies the range of hosts or services in cluster that must be in a")); + printf(" %s\n", _("non-OK state in order to return a CRITICAL status level")); + printf(" %s\n", "-d, --data=LIST"); + printf(" %s\n", _("The status codes of the hosts or services in the cluster, separated by")); + printf(" %s\n", _("commas")); printf(UT_VERBOSE); @@ -267,23 +249,18 @@ print_help(void) printf("%s\n", _("Notes:")); printf(UT_THRESHOLDS_NOTES); - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n", "check_cluster -s -d 2,0,2,0 -c @3:"); - printf (" %s\n", _("Will alert critical if there are 3 or more service data points in a non-OK") ); - printf (" %s\n", _("state.") ); + printf("\n"); + printf("%s\n", _("Examples:")); + printf(" %s\n", "check_cluster -s -d 2,0,2,0 -c @3:"); + printf(" %s\n", _("Will alert critical if there are 3 or more service data points in a non-OK")); + printf(" %s\n", _("state.")); printf(UT_SUPPORT); } - -void -print_usage(void) -{ +void print_usage(void) { printf("%s\n", _("Usage:")); printf(" %s (-s | -h) -d val1[,val2,...,valn] [-l label]\n", progname); printf("[-w threshold] [-c threshold] [-v] [--help]\n"); - } - -- cgit v1.2.3-74-g34f1 From a30f0c6c08f90de8abe6ca277e98102aa4d6950c Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:53:01 +0100 Subject: check_cluster: Copyright update --- plugins/check_cluster.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c index aa555280..6ca43c63 100644 --- a/plugins/check_cluster.c +++ b/plugins/check_cluster.c @@ -4,7 +4,7 @@ * * License: GPL * Copyright (c) 2000-2004 Ethan Galstad (nagios@nagios.org) - * Copyright (c) 2007 Monitoring Plugins Development Team + * Copyright (c) 2007-2024 Monitoring Plugins Development Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -23,7 +23,7 @@ *****************************************************************************/ const char *progname = "check_cluster"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From ebb453f55ef6e64033ac50341963eb49cf457796 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:54:48 +0100 Subject: check_cluster: do not export local symbols --- plugins/check_cluster.c | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c index 6ca43c63..0afb3f42 100644 --- a/plugins/check_cluster.c +++ b/plugins/check_cluster.c @@ -33,29 +33,29 @@ const char *email = "devel@monitoring-plugins.org"; #define CHECK_SERVICES 1 #define CHECK_HOSTS 2 -void print_help(void); +static void print_help(void); void print_usage(void); -int total_services_ok = 0; -int total_services_warning = 0; -int total_services_unknown = 0; -int total_services_critical = 0; +static int total_services_ok = 0; +static int total_services_warning = 0; +static int total_services_unknown = 0; +static int total_services_critical = 0; -int total_hosts_up = 0; -int total_hosts_down = 0; -int total_hosts_unreachable = 0; +static int total_hosts_up = 0; +static int total_hosts_down = 0; +static int total_hosts_unreachable = 0; -char *warn_threshold; -char *crit_threshold; +static char *warn_threshold; +static char *crit_threshold; -int check_type = CHECK_SERVICES; +static int check_type = CHECK_SERVICES; -char *data_vals = NULL; -char *label = NULL; +static char *data_vals = NULL; +static char *label = NULL; -int verbose = 0; +static int verbose = 0; -int process_arguments(int, char **); +static int process_arguments(int, char **); int main(int argc, char **argv) { char *ptr; -- cgit v1.2.3-74-g34f1 From 289f07d754554191d202684b7664f9012c662f10 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:57:07 +0100 Subject: check_cluster: linter fixes --- plugins/check_cluster.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c index 0afb3f42..b40c38c7 100644 --- a/plugins/check_cluster.c +++ b/plugins/check_cluster.c @@ -30,8 +30,10 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "utils_base.h" -#define CHECK_SERVICES 1 -#define CHECK_HOSTS 2 +enum { + CHECK_SERVICES = 1, + CHECK_HOSTS = 2 +}; static void print_help(void); void print_usage(void); @@ -55,7 +57,7 @@ static char *label = NULL; static int verbose = 0; -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); int main(int argc, char **argv) { char *ptr; -- cgit v1.2.3-74-g34f1 From 80f07ff92b73d24614c0d3d15021f115bf85b152 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:58:41 +0100 Subject: check_curl: clang-format --- plugins/check_curl.c | 4416 ++++++++++++++++++++++++-------------------------- 1 file changed, 2156 insertions(+), 2260 deletions(-) diff --git a/plugins/check_curl.c b/plugins/check_curl.c index d3bddacd..8936110f 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -1,37 +1,37 @@ /***************************************************************************** -* -* Monitoring check_curl plugin -* -* License: GPL -* Copyright (c) 1999-2019 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_curl plugin -* -* This plugin tests the HTTP service on the specified host. It can test -* normal (http) and secure (https) servers, follow redirects, search for -* strings and regular expressions, check connection times, and report on -* certificate expiration times. -* -* This plugin uses functions from the curl library, see -* http://curl.haxx.se -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_curl plugin + * + * License: GPL + * Copyright (c) 1999-2019 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_curl plugin + * + * This plugin tests the HTTP service on the specified host. It can test + * normal (http) and secure (https) servers, follow redirects, search for + * strings and regular expressions, check connection times, and report on + * certificate expiration times. + * + * This plugin uses functions from the curl library, see + * http://curl.haxx.se + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_curl"; const char *copyright = "2006-2019"; @@ -44,7 +44,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #ifndef LIBCURL_PROTOCOL_HTTP -#error libcurl compiled without HTTP support, compiling check_curl plugin does not makes a lot of sense +# error libcurl compiled without HTTP support, compiling check_curl plugin does not makes a lot of sense #endif #include "curl/curl.h" @@ -58,7 +58,7 @@ const char *email = "devel@monitoring-plugins.org"; #include #if defined(HAVE_SSL) && defined(USE_OPENSSL) -#include +# include #endif #include @@ -66,66 +66,66 @@ const char *email = "devel@monitoring-plugins.org"; #define MAKE_LIBCURL_VERSION(major, minor, patch) ((major)*0x10000 + (minor)*0x100 + (patch)) #define DEFAULT_BUFFER_SIZE 2048 -#define DEFAULT_SERVER_URL "/" -#define HTTP_EXPECT "HTTP/" -#define INET_ADDR_MAX_SIZE INET6_ADDRSTRLEN +#define DEFAULT_SERVER_URL "/" +#define HTTP_EXPECT "HTTP/" +#define INET_ADDR_MAX_SIZE INET6_ADDRSTRLEN enum { - MAX_IPV4_HOSTLENGTH = 255, - HTTP_PORT = 80, - HTTPS_PORT = 443, - MAX_PORT = 65535, - DEFAULT_MAX_REDIRS = 15 + MAX_IPV4_HOSTLENGTH = 255, + HTTP_PORT = 80, + HTTPS_PORT = 443, + MAX_PORT = 65535, + DEFAULT_MAX_REDIRS = 15 }; enum { - STICKY_NONE = 0, - STICKY_HOST = 1, - STICKY_PORT = 2 + STICKY_NONE = 0, + STICKY_HOST = 1, + STICKY_PORT = 2 }; enum { - FOLLOW_HTTP_CURL = 0, - FOLLOW_LIBCURL = 1 + FOLLOW_HTTP_CURL = 0, + FOLLOW_LIBCURL = 1 }; /* for buffers for header and body */ typedef struct { - char *buf; - size_t buflen; - size_t bufsize; + char *buf; + size_t buflen; + size_t bufsize; } curlhelp_write_curlbuf; /* for buffering the data sent in PUT */ typedef struct { - char *buf; - size_t buflen; - off_t pos; + char *buf; + size_t buflen; + off_t pos; } curlhelp_read_curlbuf; /* for parsing the HTTP status line */ typedef struct { - int http_major; /* major version of the protocol, always 1 (HTTP/0.9 - * never reached the big internet most likely) */ - int http_minor; /* minor version of the protocol, usually 0 or 1 */ - int http_code; /* HTTP return code as in RFC 2145 */ - int http_subcode; /* Microsoft IIS extension, HTTP subcodes, see - * http://support.microsoft.com/kb/318380/en-us */ - const char *msg; /* the human readable message */ - char *first_line; /* a copy of the first line */ + int http_major; /* major version of the protocol, always 1 (HTTP/0.9 + * never reached the big internet most likely) */ + int http_minor; /* minor version of the protocol, usually 0 or 1 */ + int http_code; /* HTTP return code as in RFC 2145 */ + int http_subcode; /* Microsoft IIS extension, HTTP subcodes, see + * http://support.microsoft.com/kb/318380/en-us */ + const char *msg; /* the human readable message */ + char *first_line; /* a copy of the first line */ } curlhelp_statusline; /* to know the underlying SSL library used by libcurl */ typedef enum curlhelp_ssl_library { - CURLHELP_SSL_LIBRARY_UNKNOWN, - CURLHELP_SSL_LIBRARY_OPENSSL, - CURLHELP_SSL_LIBRARY_LIBRESSL, - CURLHELP_SSL_LIBRARY_GNUTLS, - CURLHELP_SSL_LIBRARY_NSS + CURLHELP_SSL_LIBRARY_UNKNOWN, + CURLHELP_SSL_LIBRARY_OPENSSL, + CURLHELP_SSL_LIBRARY_LIBRESSL, + CURLHELP_SSL_LIBRARY_GNUTLS, + CURLHELP_SSL_LIBRARY_NSS } curlhelp_ssl_library; enum { - REGS = 2, - MAX_RE_SIZE = 1024 + REGS = 2, + MAX_RE_SIZE = 1024 }; #include "regex.h" regex_t preg; @@ -204,8 +204,8 @@ bool use_sni = true; bool check_cert = false; bool continue_after_check_cert = false; typedef union { - struct curl_slist* to_info; - struct curl_certinfo* to_certinfo; + struct curl_slist *to_info; + struct curl_certinfo *to_certinfo; } cert_ptr_union; cert_ptr_union cert_ptr; int ssl_version = CURL_SSLVERSION_DEFAULT; @@ -227,946 +227,889 @@ bool automatic_decompression = false; char *cookie_jar_file = NULL; bool haproxy_protocol = false; -bool process_arguments (int, char**); -void handle_curl_option_return_code (CURLcode res, const char* option); -int check_http (void); -void redir (curlhelp_write_curlbuf*); -char *perfd_time (double microsec); -char *perfd_time_connect (double microsec); -char *perfd_time_ssl (double microsec); -char *perfd_time_firstbyte (double microsec); -char *perfd_time_headers (double microsec); -char *perfd_time_transfer (double microsec); -char *perfd_size (int page_len); -void print_help (void); -void print_usage (void); -void print_curl_version (void); -int curlhelp_initwritebuffer (curlhelp_write_curlbuf*); -size_t curlhelp_buffer_write_callback(void*, size_t , size_t , void*); -void curlhelp_freewritebuffer (curlhelp_write_curlbuf*); -int curlhelp_initreadbuffer (curlhelp_read_curlbuf *, const char *, size_t); -size_t curlhelp_buffer_read_callback(void *, size_t , size_t , void *); -void curlhelp_freereadbuffer (curlhelp_read_curlbuf *); -curlhelp_ssl_library curlhelp_get_ssl_library (); -const char* curlhelp_get_ssl_library_string (curlhelp_ssl_library); -int net_noopenssl_check_certificate (cert_ptr_union*, int, int); - -int curlhelp_parse_statusline (const char*, curlhelp_statusline *); -void curlhelp_free_statusline (curlhelp_statusline *); -char *get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header); -int check_document_dates (const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); -int get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_write_curlbuf* body_buf); +bool process_arguments(int, char **); +void handle_curl_option_return_code(CURLcode res, const char *option); +int check_http(void); +void redir(curlhelp_write_curlbuf *); +char *perfd_time(double microsec); +char *perfd_time_connect(double microsec); +char *perfd_time_ssl(double microsec); +char *perfd_time_firstbyte(double microsec); +char *perfd_time_headers(double microsec); +char *perfd_time_transfer(double microsec); +char *perfd_size(int page_len); +void print_help(void); +void print_usage(void); +void print_curl_version(void); +int curlhelp_initwritebuffer(curlhelp_write_curlbuf *); +size_t curlhelp_buffer_write_callback(void *, size_t, size_t, void *); +void curlhelp_freewritebuffer(curlhelp_write_curlbuf *); +int curlhelp_initreadbuffer(curlhelp_read_curlbuf *, const char *, size_t); +size_t curlhelp_buffer_read_callback(void *, size_t, size_t, void *); +void curlhelp_freereadbuffer(curlhelp_read_curlbuf *); +curlhelp_ssl_library curlhelp_get_ssl_library(); +const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library); +int net_noopenssl_check_certificate(cert_ptr_union *, int, int); + +int curlhelp_parse_statusline(const char *, curlhelp_statusline *); +void curlhelp_free_statusline(curlhelp_statusline *); +char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header); +int check_document_dates(const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); +int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf); #if defined(HAVE_SSL) && defined(USE_OPENSSL) int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit); #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ -void remove_newlines (char *); -void test_file (char *); +void remove_newlines(char *); +void test_file(char *); -int -main (int argc, char **argv) -{ - int result = STATE_UNKNOWN; +int main(int argc, char **argv) { + int result = STATE_UNKNOWN; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); - /* Parse extra opts if any */ - argv = np_extra_opts (&argc, argv, progname); + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); - /* set defaults */ - snprintf( user_agent, DEFAULT_BUFFER_SIZE, "%s/v%s (monitoring-plugins %s, %s)", - progname, NP_VERSION, VERSION, curl_version()); + /* set defaults */ + snprintf(user_agent, DEFAULT_BUFFER_SIZE, "%s/v%s (monitoring-plugins %s, %s)", progname, NP_VERSION, VERSION, curl_version()); - /* parse arguments */ - if (process_arguments (argc, argv) == false) - usage4 (_("Could not parse arguments")); + /* parse arguments */ + if (process_arguments(argc, argv) == false) + usage4(_("Could not parse arguments")); - if (display_html) - printf ("", - use_ssl ? "https" : "http", - host_name ? host_name : server_address, - virtual_port ? virtual_port : server_port, - server_url); + if (display_html) + printf("", use_ssl ? "https" : "http", host_name ? host_name : server_address, + virtual_port ? virtual_port : server_port, server_url); - result = check_http (); - return result; + result = check_http(); + return result; } #ifdef HAVE_SSL -#ifdef USE_OPENSSL - -int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) -{ - (void) preverify_ok; - /* TODO: we get all certificates of the chain, so which ones - * should we test? - * TODO: is the last certificate always the server certificate? - */ - cert = X509_STORE_CTX_get_current_cert(x509_ctx); -#if OPENSSL_VERSION_NUMBER >= 0x10100000L - X509_up_ref(cert); -#endif - if (verbose>=2) { - puts("* SSL verify callback with certificate:"); - X509_NAME *subject, *issuer; - printf("* issuer:\n"); - issuer = X509_get_issuer_name( cert ); - X509_NAME_print_ex_fp(stdout, issuer, 5, XN_FLAG_MULTILINE); - printf("* curl verify_callback:\n* subject:\n"); - subject = X509_get_subject_name( cert ); - X509_NAME_print_ex_fp(stdout, subject, 5, XN_FLAG_MULTILINE); - puts(""); - } - return 1; +# ifdef USE_OPENSSL + +int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) { + (void)preverify_ok; + /* TODO: we get all certificates of the chain, so which ones + * should we test? + * TODO: is the last certificate always the server certificate? + */ + cert = X509_STORE_CTX_get_current_cert(x509_ctx); +# if OPENSSL_VERSION_NUMBER >= 0x10100000L + X509_up_ref(cert); +# endif + if (verbose >= 2) { + puts("* SSL verify callback with certificate:"); + X509_NAME *subject, *issuer; + printf("* issuer:\n"); + issuer = X509_get_issuer_name(cert); + X509_NAME_print_ex_fp(stdout, issuer, 5, XN_FLAG_MULTILINE); + printf("* curl verify_callback:\n* subject:\n"); + subject = X509_get_subject_name(cert); + X509_NAME_print_ex_fp(stdout, subject, 5, XN_FLAG_MULTILINE); + puts(""); + } + return 1; } -CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm) -{ - (void) curl; // ignore unused parameter - (void) parm; // ignore unused parameter - if(add_sslctx_verify_fun) { - SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback); - } - - // workaround for issue: - // OpenSSL SSL_read: error:0A000126:SSL routines::unexpected eof while reading, errno 0 - // see discussion https://github.com/openssl/openssl/discussions/22690 -#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF - SSL_CTX_set_options(sslctx, SSL_OP_IGNORE_UNEXPECTED_EOF); -#endif +CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm) { + (void)curl; // ignore unused parameter + (void)parm; // ignore unused parameter + if (add_sslctx_verify_fun) { + SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback); + } + + // workaround for issue: + // OpenSSL SSL_read: error:0A000126:SSL routines::unexpected eof while reading, errno 0 + // see discussion https://github.com/openssl/openssl/discussions/22690 +# ifdef SSL_OP_IGNORE_UNEXPECTED_EOF + SSL_CTX_set_options(sslctx, SSL_OP_IGNORE_UNEXPECTED_EOF); +# endif - return CURLE_OK; + return CURLE_OK; } -#endif /* USE_OPENSSL */ -#endif /* HAVE_SSL */ +# endif /* USE_OPENSSL */ +#endif /* HAVE_SSL */ /* returns a string "HTTP/1.x" or "HTTP/2" */ -static char *string_statuscode (int major, int minor) -{ - static char buf[10]; - - switch (major) { - case 1: - snprintf (buf, sizeof (buf), "HTTP/%d.%d", major, minor); - break; - case 2: - case 3: - snprintf (buf, sizeof (buf), "HTTP/%d", major); - break; - default: - /* assuming here HTTP/N with N>=4 */ - snprintf (buf, sizeof (buf), "HTTP/%d", major); - break; - } - - return buf; +static char *string_statuscode(int major, int minor) { + static char buf[10]; + + switch (major) { + case 1: + snprintf(buf, sizeof(buf), "HTTP/%d.%d", major, minor); + break; + case 2: + case 3: + snprintf(buf, sizeof(buf), "HTTP/%d", major); + break; + default: + /* assuming here HTTP/N with N>=4 */ + snprintf(buf, sizeof(buf), "HTTP/%d", major); + break; + } + + return buf; } /* Checks if the server 'reply' is one of the expected 'statuscodes' */ -static int -expected_statuscode (const char *reply, const char *statuscodes) -{ - char *expected, *code; - int result = 0; - - if ((expected = strdup (statuscodes)) == NULL) - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); - - for (code = strtok (expected, ","); code != NULL; code = strtok (NULL, ",")) - if (strstr (reply, code) != NULL) { - result = 1; - break; - } - - free (expected); - return result; +static int expected_statuscode(const char *reply, const char *statuscodes) { + char *expected, *code; + int result = 0; + + if ((expected = strdup(statuscodes)) == NULL) + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); + + for (code = strtok(expected, ","); code != NULL; code = strtok(NULL, ",")) + if (strstr(reply, code) != NULL) { + result = 1; + break; + } + + free(expected); + return result; } -void -handle_curl_option_return_code (CURLcode res, const char* option) -{ - if (res != CURLE_OK) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Error while setting cURL option '%s': cURL returned %d - %s"), - option, - res, - curl_easy_strerror(res)); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } +void handle_curl_option_return_code(CURLcode res, const char *option) { + if (res != CURLE_OK) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Error while setting cURL option '%s': cURL returned %d - %s"), option, res, + curl_easy_strerror(res)); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } } -int -lookup_host (const char *host, char *buf, size_t buflen) -{ - struct addrinfo hints, *res, *result; - char addrstr[100]; - size_t addrstr_len; - int errcode; - void *ptr = { 0 }; - size_t buflen_remaining = buflen - 1; - - memset (&hints, 0, sizeof (hints)); - hints.ai_family = address_family; - hints.ai_socktype = SOCK_STREAM; - hints.ai_flags |= AI_CANONNAME; - - errcode = getaddrinfo (host, NULL, &hints, &result); - if (errcode != 0) - return errcode; - - strcpy(buf, ""); - res = result; - - while (res) { - switch (res->ai_family) { - case AF_INET: - ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr; - break; - case AF_INET6: - ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr; - break; - } - - inet_ntop (res->ai_family, ptr, addrstr, 100); - if (verbose >= 1) { - printf ("* getaddrinfo IPv%d address: %s\n", - res->ai_family == PF_INET6 ? 6 : 4, addrstr); - } - - // Append all IPs to buf as a comma-separated string - addrstr_len = strlen(addrstr); - if (buflen_remaining > addrstr_len + 1) { - if (buf[0] != '\0') { - strncat(buf, ",", buflen_remaining); - buflen_remaining -= 1; - } - strncat(buf, addrstr, buflen_remaining); - buflen_remaining -= addrstr_len; - } - - res = res->ai_next; - } - - freeaddrinfo(result); - - return 0; +int lookup_host(const char *host, char *buf, size_t buflen) { + struct addrinfo hints, *res, *result; + char addrstr[100]; + size_t addrstr_len; + int errcode; + void *ptr = {0}; + size_t buflen_remaining = buflen - 1; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = address_family; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags |= AI_CANONNAME; + + errcode = getaddrinfo(host, NULL, &hints, &result); + if (errcode != 0) + return errcode; + + strcpy(buf, ""); + res = result; + + while (res) { + switch (res->ai_family) { + case AF_INET: + ptr = &((struct sockaddr_in *)res->ai_addr)->sin_addr; + break; + case AF_INET6: + ptr = &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr; + break; + } + + inet_ntop(res->ai_family, ptr, addrstr, 100); + if (verbose >= 1) { + printf("* getaddrinfo IPv%d address: %s\n", res->ai_family == PF_INET6 ? 6 : 4, addrstr); + } + + // Append all IPs to buf as a comma-separated string + addrstr_len = strlen(addrstr); + if (buflen_remaining > addrstr_len + 1) { + if (buf[0] != '\0') { + strncat(buf, ",", buflen_remaining); + buflen_remaining -= 1; + } + strncat(buf, addrstr, buflen_remaining); + buflen_remaining -= addrstr_len; + } + + res = res->ai_next; + } + + freeaddrinfo(result); + + return 0; } -static void -cleanup (void) -{ - if (status_line_initialized) curlhelp_free_statusline(&status_line); - status_line_initialized = false; - if (curl_easy_initialized) curl_easy_cleanup (curl); - curl_easy_initialized = false; - if (curl_global_initialized) curl_global_cleanup (); - curl_global_initialized = false; - if (body_buf_initialized) curlhelp_freewritebuffer (&body_buf); - body_buf_initialized = false; - if (header_buf_initialized) curlhelp_freewritebuffer (&header_buf); - header_buf_initialized = false; - if (put_buf_initialized) curlhelp_freereadbuffer (&put_buf); - put_buf_initialized = false; +static void cleanup(void) { + if (status_line_initialized) + curlhelp_free_statusline(&status_line); + status_line_initialized = false; + if (curl_easy_initialized) + curl_easy_cleanup(curl); + curl_easy_initialized = false; + if (curl_global_initialized) + curl_global_cleanup(); + curl_global_initialized = false; + if (body_buf_initialized) + curlhelp_freewritebuffer(&body_buf); + body_buf_initialized = false; + if (header_buf_initialized) + curlhelp_freewritebuffer(&header_buf); + header_buf_initialized = false; + if (put_buf_initialized) + curlhelp_freereadbuffer(&put_buf); + put_buf_initialized = false; } -int -check_http (void) -{ - int result = STATE_OK; - int result_ssl = STATE_OK; - int page_len = 0; - int i; - char *force_host_header = NULL; - struct curl_slist *host = NULL; - char addrstr[DEFAULT_BUFFER_SIZE/2]; - char dnscache[DEFAULT_BUFFER_SIZE]; - - /* initialize curl */ - if (curl_global_init (CURL_GLOBAL_DEFAULT) != CURLE_OK) - die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n"); - curl_global_initialized = true; - - if ((curl = curl_easy_init()) == NULL) { - die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n"); - } - curl_easy_initialized = true; - - /* register cleanup function to shut down libcurl properly */ - atexit (cleanup); - - if (verbose >= 1) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_VERBOSE, 1), "CURLOPT_VERBOSE"); - - /* print everything on stdout like check_http would do */ - handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_STDERR, stdout), "CURLOPT_STDERR"); - - if (automatic_decompression) +int check_http(void) { + int result = STATE_OK; + int result_ssl = STATE_OK; + int page_len = 0; + int i; + char *force_host_header = NULL; + struct curl_slist *host = NULL; + char addrstr[DEFAULT_BUFFER_SIZE / 2]; + char dnscache[DEFAULT_BUFFER_SIZE]; + + /* initialize curl */ + if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) + die(STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n"); + curl_global_initialized = true; + + if ((curl = curl_easy_init()) == NULL) { + die(STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n"); + } + curl_easy_initialized = true; + + /* register cleanup function to shut down libcurl properly */ + atexit(cleanup); + + if (verbose >= 1) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_VERBOSE, 1), "CURLOPT_VERBOSE"); + + /* print everything on stdout like check_http would do */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_STDERR, stdout), "CURLOPT_STDERR"); + + if (automatic_decompression) #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6) - handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""), "CURLOPT_ACCEPT_ENCODING"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""), "CURLOPT_ACCEPT_ENCODING"); #else - handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_ENCODING, ""), "CURLOPT_ENCODING"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_ENCODING, ""), "CURLOPT_ENCODING"); #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6) */ - /* initialize buffer for body of the answer */ - if (curlhelp_initwritebuffer(&body_buf) < 0) - die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n"); - body_buf_initialized = true; - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_WRITEFUNCTION"); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEDATA, (void *)&body_buf), "CURLOPT_WRITEDATA"); - - /* initialize buffer for header of the answer */ - if (curlhelp_initwritebuffer( &header_buf ) < 0) - die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for header\n" ); - header_buf_initialized = true; - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HEADERFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_HEADERFUNCTION"); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEHEADER, (void *)&header_buf), "CURLOPT_WRITEHEADER"); - - /* set the error buffer */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, errbuf), "CURLOPT_ERRORBUFFER"); - - /* set timeouts */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, socket_timeout), "CURLOPT_CONNECTTIMEOUT"); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_TIMEOUT, socket_timeout), "CURLOPT_TIMEOUT"); - - /* enable haproxy protocol */ - if (haproxy_protocol) { - handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HAPROXYPROTOCOL, 1L), "CURLOPT_HAPROXYPROTOCOL"); - } - - // 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 - if(use_ssl && host_name != NULL) { - if ( (res=lookup_host (server_address, addrstr, DEFAULT_BUFFER_SIZE/2)) != 0) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Unable to lookup IP address for '%s': getaddrinfo returned %d - %s"), - server_address, - res, - gai_strerror (res)); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } - snprintf (dnscache, DEFAULT_BUFFER_SIZE, "%s:%d:%s", host_name, server_port, addrstr); - host = curl_slist_append(NULL, dnscache); - curl_easy_setopt(curl, CURLOPT_RESOLVE, host); - if (verbose>=1) - printf ("* curl CURLOPT_RESOLVE: %s\n", dnscache); - } - - // If server_address is an IPv6 address it must be surround by square brackets - struct in6_addr tmp_in_addr; - if (inet_pton(AF_INET6, server_address, &tmp_in_addr) == 1) { - char *new_server_address = malloc(strlen(server_address) + 3); - if (new_server_address == NULL) { - die(STATE_UNKNOWN, "HTTP UNKNOWN - Unable to allocate memory\n"); - } - snprintf(new_server_address, strlen(server_address)+3, "[%s]", server_address); - free(server_address); - server_address = new_server_address; - } - - /* compose URL: use the address we want to connect to, set Host: header later */ - snprintf (url, DEFAULT_BUFFER_SIZE, "%s://%s:%d%s", - use_ssl ? "https" : "http", - ( use_ssl & ( host_name != NULL ) ) ? host_name : server_address, - server_port, - server_url - ); - - if (verbose>=1) - printf ("* curl CURLOPT_URL: %s\n", url); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, url), "CURLOPT_URL"); - - /* extract proxy information for legacy proxy https requests */ - if (!strcmp(http_method, "CONNECT") || strstr(server_url, "http") == server_url) { - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXY, server_address), "CURLOPT_PROXY"); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXYPORT, (long)server_port), "CURLOPT_PROXYPORT"); - if (verbose>=2) - printf ("* curl CURLOPT_PROXY: %s:%d\n", server_address, server_port); - http_method = "GET"; - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, server_url), "CURLOPT_URL"); - } - - /* disable body for HEAD request */ - if (http_method && !strcmp (http_method, "HEAD" )) { - no_body = true; - } - - /* set HTTP protocol version */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HTTP_VERSION, curl_http_version), "CURLOPT_HTTP_VERSION"); - - /* set HTTP method */ - if (http_method) { - if (!strcmp(http_method, "POST")) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POST, 1), "CURLOPT_POST"); - else if (!strcmp(http_method, "PUT")) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_UPLOAD, 1), "CURLOPT_UPLOAD"); - else - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CUSTOMREQUEST, http_method), "CURLOPT_CUSTOMREQUEST"); - } - - /* check if Host header is explicitly set in options */ - if (http_opt_headers_count) { - for (i = 0; i < http_opt_headers_count ; i++) { - if (strncmp(http_opt_headers[i], "Host:", 5) == 0) { - force_host_header = http_opt_headers[i]; - } - } - } - - /* set hostname (virtual hosts), not needed if CURLOPT_CONNECT_TO is used, but left in anyway */ - if(host_name != NULL && force_host_header == NULL) { - if((virtual_port != HTTP_PORT && !use_ssl) || (virtual_port != HTTPS_PORT && use_ssl)) { - snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s:%d", host_name, virtual_port); - } else { - snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s", host_name); - } - header_list = curl_slist_append (header_list, http_header); - } - - /* always close connection, be nice to servers */ - snprintf (http_header, DEFAULT_BUFFER_SIZE, "Connection: close"); - header_list = curl_slist_append (header_list, http_header); - - /* attach additional headers supplied by the user */ - /* optionally send any other header tag */ - if (http_opt_headers_count) { - for (i = 0; i < http_opt_headers_count ; i++) { - header_list = curl_slist_append (header_list, http_opt_headers[i]); - } - /* This cannot be free'd here because a redirection will then try to access this and segfault */ - /* Covered in a testcase in tests/check_http.t */ - /* free(http_opt_headers); */ - } - - /* set HTTP headers */ - handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPHEADER, header_list ), "CURLOPT_HTTPHEADER"); + /* initialize buffer for body of the answer */ + if (curlhelp_initwritebuffer(&body_buf) < 0) + die(STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n"); + body_buf_initialized = true; + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), + "CURLOPT_WRITEFUNCTION"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&body_buf), "CURLOPT_WRITEDATA"); + + /* initialize buffer for header of the answer */ + if (curlhelp_initwritebuffer(&header_buf) < 0) + die(STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for header\n"); + header_buf_initialized = true; + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), + "CURLOPT_HEADERFUNCTION"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_WRITEHEADER, (void *)&header_buf), "CURLOPT_WRITEHEADER"); + + /* set the error buffer */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf), "CURLOPT_ERRORBUFFER"); + + /* set timeouts */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, socket_timeout), "CURLOPT_CONNECTTIMEOUT"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_TIMEOUT, socket_timeout), "CURLOPT_TIMEOUT"); + + /* enable haproxy protocol */ + if (haproxy_protocol) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HAPROXYPROTOCOL, 1L), "CURLOPT_HAPROXYPROTOCOL"); + } + + // 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 + if (use_ssl && host_name != NULL) { + if ((res = lookup_host(server_address, addrstr, DEFAULT_BUFFER_SIZE / 2)) != 0) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Unable to lookup IP address for '%s': getaddrinfo returned %d - %s"), server_address, res, + gai_strerror(res)); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + snprintf(dnscache, DEFAULT_BUFFER_SIZE, "%s:%d:%s", host_name, server_port, addrstr); + host = curl_slist_append(NULL, dnscache); + curl_easy_setopt(curl, CURLOPT_RESOLVE, host); + if (verbose >= 1) + printf("* curl CURLOPT_RESOLVE: %s\n", dnscache); + } + + // If server_address is an IPv6 address it must be surround by square brackets + struct in6_addr tmp_in_addr; + if (inet_pton(AF_INET6, server_address, &tmp_in_addr) == 1) { + char *new_server_address = malloc(strlen(server_address) + 3); + if (new_server_address == NULL) { + die(STATE_UNKNOWN, "HTTP UNKNOWN - Unable to allocate memory\n"); + } + snprintf(new_server_address, strlen(server_address) + 3, "[%s]", server_address); + free(server_address); + server_address = new_server_address; + } + + /* compose URL: use the address we want to connect to, set Host: header later */ + snprintf(url, DEFAULT_BUFFER_SIZE, "%s://%s:%d%s", use_ssl ? "https" : "http", + (use_ssl & (host_name != NULL)) ? host_name : server_address, server_port, server_url); + + if (verbose >= 1) + printf("* curl CURLOPT_URL: %s\n", url); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_URL, url), "CURLOPT_URL"); + + /* extract proxy information for legacy proxy https requests */ + if (!strcmp(http_method, "CONNECT") || strstr(server_url, "http") == server_url) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_PROXY, server_address), "CURLOPT_PROXY"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_PROXYPORT, (long)server_port), "CURLOPT_PROXYPORT"); + if (verbose >= 2) + printf("* curl CURLOPT_PROXY: %s:%d\n", server_address, server_port); + http_method = "GET"; + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_URL, server_url), "CURLOPT_URL"); + } + + /* disable body for HEAD request */ + if (http_method && !strcmp(http_method, "HEAD")) { + no_body = true; + } + + /* set HTTP protocol version */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, curl_http_version), "CURLOPT_HTTP_VERSION"); + + /* set HTTP method */ + if (http_method) { + if (!strcmp(http_method, "POST")) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_POST, 1), "CURLOPT_POST"); + else if (!strcmp(http_method, "PUT")) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_UPLOAD, 1), "CURLOPT_UPLOAD"); + else + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method), "CURLOPT_CUSTOMREQUEST"); + } + + /* check if Host header is explicitly set in options */ + if (http_opt_headers_count) { + for (i = 0; i < http_opt_headers_count; i++) { + if (strncmp(http_opt_headers[i], "Host:", 5) == 0) { + force_host_header = http_opt_headers[i]; + } + } + } + + /* set hostname (virtual hosts), not needed if CURLOPT_CONNECT_TO is used, but left in anyway */ + if (host_name != NULL && force_host_header == NULL) { + if ((virtual_port != HTTP_PORT && !use_ssl) || (virtual_port != HTTPS_PORT && use_ssl)) { + snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s:%d", host_name, virtual_port); + } else { + snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s", host_name); + } + header_list = curl_slist_append(header_list, http_header); + } + + /* always close connection, be nice to servers */ + snprintf(http_header, DEFAULT_BUFFER_SIZE, "Connection: close"); + header_list = curl_slist_append(header_list, http_header); + + /* attach additional headers supplied by the user */ + /* optionally send any other header tag */ + if (http_opt_headers_count) { + for (i = 0; i < http_opt_headers_count; i++) { + header_list = curl_slist_append(header_list, http_opt_headers[i]); + } + /* This cannot be free'd here because a redirection will then try to access this and segfault */ + /* Covered in a testcase in tests/check_http.t */ + /* free(http_opt_headers); */ + } + + /* set HTTP headers */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list), "CURLOPT_HTTPHEADER"); #ifdef LIBCURL_FEATURE_SSL - /* set SSL version, warn about insecure or unsupported versions */ - if (use_ssl) { - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLVERSION, ssl_version), "CURLOPT_SSLVERSION"); - } - - /* client certificate and key to present to server (SSL) */ - if (client_cert) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLCERT, client_cert), "CURLOPT_SSLCERT"); - if (client_privkey) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLKEY, client_privkey), "CURLOPT_SSLKEY"); - if (ca_cert) { - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO"); - } - if (ca_cert || verify_peer_and_host) { - /* per default if we have a CA verify both the peer and the - * hostname in the certificate, can be switched off later */ - handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER"); - handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST"); - } else { - /* backward-compatible behaviour, be tolerant in checks - * TODO: depending on more options have aspects we want - * to be less tolerant about ssl verfications - */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0), "CURLOPT_SSL_VERIFYPEER"); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0), "CURLOPT_SSL_VERIFYHOST"); - } - - /* detect SSL library used by libcurl */ - ssl_library = curlhelp_get_ssl_library (); - - /* try hard to get a stack of certificates to verify against */ - if (check_cert) { -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) - /* inform curl to report back certificates */ - switch (ssl_library) { - case CURLHELP_SSL_LIBRARY_OPENSSL: - case CURLHELP_SSL_LIBRARY_LIBRESSL: - /* set callback to extract certificate with OpenSSL context function (works with - * OpenSSL-style libraries only!) */ -#ifdef USE_OPENSSL - /* libcurl and monitoring plugins built with OpenSSL, good */ - add_sslctx_verify_fun = true; - is_openssl_callback = true; -#endif /* USE_OPENSSL */ - /* libcurl is built with OpenSSL, monitoring plugins, so falling - * back to manually extracting certificate information */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); - break; - - case CURLHELP_SSL_LIBRARY_NSS: -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) - /* NSS: support for CERTINFO is implemented since 7.34.0 */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); -#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ - 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)); -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ - break; - - case CURLHELP_SSL_LIBRARY_GNUTLS: -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) - /* GnuTLS: support for CERTINFO is implemented since 7.42.0 */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); -#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */ - 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)); -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */ - break; - - case CURLHELP_SSL_LIBRARY_UNKNOWN: - default: - die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (unknown SSL library '%s', must implement first)\n", curlhelp_get_ssl_library_string (ssl_library)); - break; - } -#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ - /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */ - if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL || ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL) - add_sslctx_verify_fun = true; - else - 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"); -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ - } - -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 10, 6) /* required for CURLOPT_SSL_CTX_FUNCTION */ - // ssl ctx function is not available with all ssl backends - if (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, NULL) != CURLE_UNKNOWN_OPTION) - handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION"); -#endif + /* set SSL version, warn about insecure or unsupported versions */ + if (use_ssl) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSLVERSION, ssl_version), "CURLOPT_SSLVERSION"); + } + + /* client certificate and key to present to server (SSL) */ + if (client_cert) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSLCERT, client_cert), "CURLOPT_SSLCERT"); + if (client_privkey) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSLKEY, client_privkey), "CURLOPT_SSLKEY"); + if (ca_cert) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO"); + } + if (ca_cert || verify_peer_and_host) { + /* per default if we have a CA verify both the peer and the + * hostname in the certificate, can be switched off later */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST"); + } else { + /* backward-compatible behaviour, be tolerant in checks + * TODO: depending on more options have aspects we want + * to be less tolerant about ssl verfications + */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0), "CURLOPT_SSL_VERIFYPEER"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0), "CURLOPT_SSL_VERIFYHOST"); + } + + /* detect SSL library used by libcurl */ + ssl_library = curlhelp_get_ssl_library(); + + /* try hard to get a stack of certificates to verify against */ + if (check_cert) { +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) + /* inform curl to report back certificates */ + switch (ssl_library) { + case CURLHELP_SSL_LIBRARY_OPENSSL: + case CURLHELP_SSL_LIBRARY_LIBRESSL: + /* set callback to extract certificate with OpenSSL context function (works with + * OpenSSL-style libraries only!) */ +# ifdef USE_OPENSSL + /* libcurl and monitoring plugins built with OpenSSL, good */ + add_sslctx_verify_fun = true; + is_openssl_callback = true; +# endif /* USE_OPENSSL */ + /* libcurl is built with OpenSSL, monitoring plugins, so falling + * back to manually extracting certificate information */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); + break; + + case CURLHELP_SSL_LIBRARY_NSS: +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + /* NSS: support for CERTINFO is implemented since 7.34.0 */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); +# else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + 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)); +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + break; + + case CURLHELP_SSL_LIBRARY_GNUTLS: +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) + /* GnuTLS: support for CERTINFO is implemented since 7.42.0 */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); +# else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */ + 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)); +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */ + break; + + case CURLHELP_SSL_LIBRARY_UNKNOWN: + default: + die(STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (unknown SSL library '%s', must implement first)\n", + curlhelp_get_ssl_library_string(ssl_library)); + break; + } +# else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ + /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */ + if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL || ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL) + add_sslctx_verify_fun = true; + else + 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"); +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ + } + +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 10, 6) /* required for CURLOPT_SSL_CTX_FUNCTION */ + // ssl ctx function is not available with all ssl backends + if (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, NULL) != CURLE_UNKNOWN_OPTION) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION"); +# endif #endif /* LIBCURL_FEATURE_SSL */ - /* set default or user-given user agent identification */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERAGENT, user_agent), "CURLOPT_USERAGENT"); - - /* proxy-authentication */ - if (strcmp(proxy_auth, "")) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXYUSERPWD, proxy_auth), "CURLOPT_PROXYUSERPWD"); - - /* authentication */ - if (strcmp(user_auth, "")) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERPWD, user_auth), "CURLOPT_USERPWD"); - - /* TODO: parameter auth method, bitfield of following methods: - * CURLAUTH_BASIC (default) - * CURLAUTH_DIGEST - * CURLAUTH_DIGEST_IE - * CURLAUTH_NEGOTIATE - * CURLAUTH_NTLM - * CURLAUTH_NTLM_WB - * - * convenience tokens for typical sets of methods: - * CURLAUTH_ANYSAFE: most secure, without BASIC - * or CURLAUTH_ANY: most secure, even BASIC if necessary - * - * handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST ), "CURLOPT_HTTPAUTH"); - */ - - /* handle redirections */ - if (onredirect == STATE_DEPENDENT) { - if( followmethod == FOLLOW_LIBCURL ) { - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1), "CURLOPT_FOLLOWLOCATION"); - - /* default -1 is infinite, not good, could lead to zombie plugins! - Setting it to one bigger than maximal limit to handle errors nicely below - */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_MAXREDIRS, max_depth+1), "CURLOPT_MAXREDIRS"); - - /* for now allow only http and https (we are a http(s) check plugin in the end) */ + /* set default or user-given user agent identification */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent), "CURLOPT_USERAGENT"); + + /* proxy-authentication */ + if (strcmp(proxy_auth, "")) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, proxy_auth), "CURLOPT_PROXYUSERPWD"); + + /* authentication */ + if (strcmp(user_auth, "")) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_USERPWD, user_auth), "CURLOPT_USERPWD"); + + /* TODO: parameter auth method, bitfield of following methods: + * CURLAUTH_BASIC (default) + * CURLAUTH_DIGEST + * CURLAUTH_DIGEST_IE + * CURLAUTH_NEGOTIATE + * CURLAUTH_NTLM + * CURLAUTH_NTLM_WB + * + * convenience tokens for typical sets of methods: + * CURLAUTH_ANYSAFE: most secure, without BASIC + * or CURLAUTH_ANY: most secure, even BASIC if necessary + * + * handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST ), "CURLOPT_HTTPAUTH"); + */ + + /* handle redirections */ + if (onredirect == STATE_DEPENDENT) { + if (followmethod == FOLLOW_LIBCURL) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1), "CURLOPT_FOLLOWLOCATION"); + + /* default -1 is infinite, not good, could lead to zombie plugins! + Setting it to one bigger than maximal limit to handle errors nicely below + */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_MAXREDIRS, max_depth + 1), "CURLOPT_MAXREDIRS"); + + /* for now allow only http and https (we are a http(s) check plugin in the end) */ #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 85, 0) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https"), "CURLOPT_REDIR_PROTOCOLS_STR"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https"), + "CURLOPT_REDIR_PROTOCOLS_STR"); #elif LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS), "CURLOPT_REDIRECT_PROTOCOLS"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS), + "CURLOPT_REDIRECT_PROTOCOLS"); #endif - /* TODO: handle the following aspects of redirection, make them - * command line options too later: - CURLOPT_POSTREDIR: method switch - CURLINFO_REDIRECT_URL: custom redirect option - CURLOPT_REDIRECT_PROTOCOLS: allow people to step outside safe protocols - CURLINFO_REDIRECT_COUNT: get the number of redirects, print it, maybe a range option here is nice like for expected page size? - */ - } else { - /* old style redirection is handled below */ - } - } - - /* no-body */ - if (no_body) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_NOBODY, 1), "CURLOPT_NOBODY"); - - /* IPv4 or IPv6 forced DNS resolution */ - if (address_family == AF_UNSPEC) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_WHATEVER)"); - else if (address_family == AF_INET) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V4)"); -#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6) - else if (address_family == AF_INET6) - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V6)"); + /* TODO: handle the following aspects of redirection, make them + * command line options too later: + CURLOPT_POSTREDIR: method switch + CURLINFO_REDIRECT_URL: custom redirect option + CURLOPT_REDIRECT_PROTOCOLS: allow people to step outside safe protocols + CURLINFO_REDIRECT_COUNT: get the number of redirects, print it, maybe a range option here is nice like for expected page size? + */ + } else { + /* old style redirection is handled below */ + } + } + + /* no-body */ + if (no_body) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_NOBODY, 1), "CURLOPT_NOBODY"); + + /* IPv4 or IPv6 forced DNS resolution */ + if (address_family == AF_UNSPEC) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER), + "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_WHATEVER)"); + else if (address_family == AF_INET) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4), + "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V4)"); +#if defined(USE_IPV6) && defined(LIBCURL_FEATURE_IPV6) + else if (address_family == AF_INET6) + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6), + "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V6)"); #endif - /* either send http POST data (any data, not only POST)*/ - if (!strcmp(http_method, "POST") ||!strcmp(http_method, "PUT")) { - /* set content of payload for POST and PUT */ - if (http_content_type) { - snprintf (http_header, DEFAULT_BUFFER_SIZE, "Content-Type: %s", http_content_type); - header_list = curl_slist_append (header_list, http_header); - } - /* NULL indicates "HTTP Continue" in libcurl, provide an empty string - * in case of no POST/PUT data */ - if (!http_post_data) - http_post_data = ""; - if (!strcmp(http_method, "POST")) { - /* POST method, set payload with CURLOPT_POSTFIELDS */ - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POSTFIELDS, http_post_data), "CURLOPT_POSTFIELDS"); - } else if (!strcmp(http_method, "PUT")) { - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READFUNCTION, (curl_read_callback)curlhelp_buffer_read_callback), "CURLOPT_READFUNCTION"); - if (curlhelp_initreadbuffer (&put_buf, http_post_data, strlen (http_post_data)) < 0) - die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating read buffer for PUT\n"); - put_buf_initialized = true; - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READDATA, (void *)&put_buf), "CURLOPT_READDATA"); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_INFILESIZE, (curl_off_t)strlen (http_post_data)), "CURLOPT_INFILESIZE"); - } - } - - /* cookie handling */ - if (cookie_jar_file != NULL) { - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_COOKIEJAR, cookie_jar_file), "CURLOPT_COOKIEJAR"); - handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_COOKIEFILE, cookie_jar_file), "CURLOPT_COOKIEFILE"); - } - - /* do the request */ - res = curl_easy_perform(curl); - - if (verbose>=2 && http_post_data) - printf ("**** REQUEST CONTENT ****\n%s\n", http_post_data); - - /* free header and server IP resolve lists, we don't need it anymore */ - curl_slist_free_all (header_list); header_list = NULL; - curl_slist_free_all (server_ips); server_ips = NULL; - if (host) { - curl_slist_free_all (host); host = NULL; - } - - /* Curl errors, result in critical Nagios state */ - if (res != CURLE_OK) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Invalid HTTP response received from host on port %d: cURL returned %d - %s"), - server_port, - res, - errbuf[0] ? errbuf : curl_easy_strerror(res)); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } - - /* certificate checks */ + /* either send http POST data (any data, not only POST)*/ + if (!strcmp(http_method, "POST") || !strcmp(http_method, "PUT")) { + /* set content of payload for POST and PUT */ + if (http_content_type) { + snprintf(http_header, DEFAULT_BUFFER_SIZE, "Content-Type: %s", http_content_type); + header_list = curl_slist_append(header_list, http_header); + } + /* NULL indicates "HTTP Continue" in libcurl, provide an empty string + * in case of no POST/PUT data */ + if (!http_post_data) + http_post_data = ""; + if (!strcmp(http_method, "POST")) { + /* POST method, set payload with CURLOPT_POSTFIELDS */ + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_POSTFIELDS, http_post_data), "CURLOPT_POSTFIELDS"); + } else if (!strcmp(http_method, "PUT")) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_READFUNCTION, (curl_read_callback)curlhelp_buffer_read_callback), + "CURLOPT_READFUNCTION"); + if (curlhelp_initreadbuffer(&put_buf, http_post_data, strlen(http_post_data)) < 0) + die(STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating read buffer for PUT\n"); + put_buf_initialized = true; + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_READDATA, (void *)&put_buf), "CURLOPT_READDATA"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_INFILESIZE, (curl_off_t)strlen(http_post_data)), + "CURLOPT_INFILESIZE"); + } + } + + /* cookie handling */ + if (cookie_jar_file != NULL) { + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookie_jar_file), "CURLOPT_COOKIEJAR"); + handle_curl_option_return_code(curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookie_jar_file), "CURLOPT_COOKIEFILE"); + } + + /* do the request */ + res = curl_easy_perform(curl); + + if (verbose >= 2 && http_post_data) + printf("**** REQUEST CONTENT ****\n%s\n", http_post_data); + + /* free header and server IP resolve lists, we don't need it anymore */ + curl_slist_free_all(header_list); + header_list = NULL; + curl_slist_free_all(server_ips); + server_ips = NULL; + if (host) { + curl_slist_free_all(host); + host = NULL; + } + + /* Curl errors, result in critical Nagios state */ + if (res != CURLE_OK) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: cURL returned %d - %s"), server_port, + res, errbuf[0] ? errbuf : curl_easy_strerror(res)); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + + /* certificate checks */ #ifdef LIBCURL_FEATURE_SSL - if (use_ssl) { - if (check_cert) { - if (is_openssl_callback) { -#ifdef USE_OPENSSL - /* check certificate with OpenSSL functions, curl has been built against OpenSSL - * and we actually have OpenSSL in the monitoring tools - */ - result_ssl = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); - if (!continue_after_check_cert) { - return result_ssl; - } -#else /* USE_OPENSSL */ - die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL callback used and not linked against OpenSSL\n"); -#endif /* USE_OPENSSL */ - } else { - int i; - struct curl_slist *slist; - - cert_ptr.to_info = NULL; - res = curl_easy_getinfo (curl, CURLINFO_CERTINFO, &cert_ptr.to_info); - if (!res && cert_ptr.to_info) { -#ifdef USE_OPENSSL - /* We have no OpenSSL in libcurl, but we can use OpenSSL for X509 cert parsing - * We only check the first certificate and assume it's the one of the server - */ - const char* raw_cert = NULL; - for (i = 0; i < cert_ptr.to_certinfo->num_of_certs; i++) { - for (slist = cert_ptr.to_certinfo->certinfo[i]; slist; slist = slist->next) { - if (verbose >= 2) - printf ("%d ** %s\n", i, slist->data); - if (strncmp (slist->data, "Cert:", 5) == 0) { - raw_cert = &slist->data[5]; - goto GOT_FIRST_CERT; - } - } - } -GOT_FIRST_CERT: - if (!raw_cert) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Cannot retrieve certificates from CERTINFO information - certificate data was empty")); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } - BIO* cert_BIO = BIO_new (BIO_s_mem()); - BIO_write (cert_BIO, raw_cert, strlen(raw_cert)); - cert = PEM_read_bio_X509 (cert_BIO, NULL, NULL, NULL); - if (!cert) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Cannot read certificate from CERTINFO information - BIO error")); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } - BIO_free (cert_BIO); - result_ssl = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); - if (!continue_after_check_cert) { - return result_ssl; - } -#else /* USE_OPENSSL */ - /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our disposal, - * so we use the libcurl CURLINFO data - */ - result_ssl = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit); - if (!continue_after_check_cert) { - return result_ssl; - } -#endif /* USE_OPENSSL */ - } else { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - _("Cannot retrieve certificates - cURL returned %d - %s"), - res, - curl_easy_strerror(res)); - die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); - } - } - } - } + if (use_ssl) { + if (check_cert) { + if (is_openssl_callback) { +# ifdef USE_OPENSSL + /* check certificate with OpenSSL functions, curl has been built against OpenSSL + * and we actually have OpenSSL in the monitoring tools + */ + result_ssl = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); + if (!continue_after_check_cert) { + return result_ssl; + } +# else /* USE_OPENSSL */ + die(STATE_CRITICAL, + "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL callback used and not linked against OpenSSL\n"); +# endif /* USE_OPENSSL */ + } else { + int i; + struct curl_slist *slist; + + cert_ptr.to_info = NULL; + res = curl_easy_getinfo(curl, CURLINFO_CERTINFO, &cert_ptr.to_info); + if (!res && cert_ptr.to_info) { +# ifdef USE_OPENSSL + /* We have no OpenSSL in libcurl, but we can use OpenSSL for X509 cert parsing + * We only check the first certificate and assume it's the one of the server + */ + const char *raw_cert = NULL; + for (i = 0; i < cert_ptr.to_certinfo->num_of_certs; i++) { + for (slist = cert_ptr.to_certinfo->certinfo[i]; slist; slist = slist->next) { + if (verbose >= 2) + printf("%d ** %s\n", i, slist->data); + if (strncmp(slist->data, "Cert:", 5) == 0) { + raw_cert = &slist->data[5]; + goto GOT_FIRST_CERT; + } + } + } + GOT_FIRST_CERT: + if (!raw_cert) { + snprintf(msg, DEFAULT_BUFFER_SIZE, + _("Cannot retrieve certificates from CERTINFO information - certificate data was empty")); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + BIO *cert_BIO = BIO_new(BIO_s_mem()); + BIO_write(cert_BIO, raw_cert, strlen(raw_cert)); + cert = PEM_read_bio_X509(cert_BIO, NULL, NULL, NULL); + if (!cert) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Cannot read certificate from CERTINFO information - BIO error")); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + BIO_free(cert_BIO); + result_ssl = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); + if (!continue_after_check_cert) { + return result_ssl; + } +# else /* USE_OPENSSL */ + /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our disposal, + * so we use the libcurl CURLINFO data + */ + result_ssl = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit); + if (!continue_after_check_cert) { + return result_ssl; + } +# endif /* USE_OPENSSL */ + } else { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates - cURL returned %d - %s"), res, + curl_easy_strerror(res)); + die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + } + } + } #endif /* LIBCURL_FEATURE_SSL */ - /* we got the data and we executed the request in a given time, so we can append - * performance data to the answer always - */ - handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_TOTAL_TIME, &total_time), "CURLINFO_TOTAL_TIME"); - page_len = get_content_length(&header_buf, &body_buf); - if(show_extended_perfdata) { - handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &time_connect), "CURLINFO_CONNECT_TIME"); - handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &time_appconnect), "CURLINFO_APPCONNECT_TIME"); - handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &time_headers), "CURLINFO_PRETRANSFER_TIME"); - handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &time_firstbyte), "CURLINFO_STARTTRANSFER_TIME"); - snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s %s %s %s %s %s", - perfd_time(total_time), - perfd_size(page_len), - perfd_time_connect(time_connect), - use_ssl ? perfd_time_ssl (time_appconnect-time_connect) : "", - perfd_time_headers(time_headers - time_appconnect), - perfd_time_firstbyte(time_firstbyte - time_headers), - perfd_time_transfer(total_time-time_firstbyte) - ); - } else { - snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s", - perfd_time(total_time), - perfd_size(page_len) - ); - } - - /* return a CRITICAL status if we couldn't read any data */ - if (strlen(header_buf.buf) == 0 && strlen(body_buf.buf) == 0) - die (STATE_CRITICAL, _("HTTP CRITICAL - No header received from host\n")); - - /* get status line of answer, check sanity of HTTP code */ - if (curlhelp_parse_statusline (header_buf.buf, &status_line) < 0) { - snprintf (msg, - DEFAULT_BUFFER_SIZE, - "Unparsable status line in %.3g seconds response time|%s\n", - total_time, - perfstring); - /* we cannot know the major/minor version here for sure as we cannot parse the first line */ - die (STATE_CRITICAL, "HTTP CRITICAL HTTP/x.x %ld unknown - %s", code, msg); - } - status_line_initialized = true; - - /* get result code from cURL */ - handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE"); - if (verbose>=2) - printf ("* curl CURLINFO_RESPONSE_CODE is %ld\n", code); - - /* print status line, header, body if verbose */ - if (verbose >= 2) { - printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header_buf.buf, - (no_body ? " [[ skipped ]]" : body_buf.buf)); - } - - /* make sure the status line matches the response we are looking for */ - if (!expected_statuscode(status_line.first_line, server_expect)) { - if (server_port == HTTP_PORT) - snprintf(msg, - DEFAULT_BUFFER_SIZE, - _("Invalid HTTP response received from host: %s\n"), - status_line.first_line); - else - snprintf(msg, - DEFAULT_BUFFER_SIZE, - _("Invalid HTTP response received from host on port %d: %s\n"), - server_port, - status_line.first_line); - die (STATE_CRITICAL, "HTTP CRITICAL - %s%s%s", msg, - show_body ? "\n" : "", - show_body ? body_buf.buf : ""); - } - - if( server_expect_yn ) { - snprintf(msg, DEFAULT_BUFFER_SIZE, _("Status line output matched \"%s\" - "), server_expect); - if (verbose) - printf ("%s\n",msg); - result = STATE_OK; - } - else { - /* illegal return codes result in a critical state */ - if (code >= 600 || code < 100) { - die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%d, %.40s)\n"), status_line.http_code, status_line.msg); - /* server errors result in a critical state */ - } else if (code >= 500) { - result = STATE_CRITICAL; - /* client errors result in a warning state */ - } else if (code >= 400) { - result = STATE_WARNING; - /* check redirected page if specified */ - } else if (code >= 300) { - if (onredirect == STATE_DEPENDENT) { - if( followmethod == FOLLOW_LIBCURL ) { - code = status_line.http_code; - } else { - /* old check_http style redirection, if we come - * back here, we are in the same status as with - * the libcurl method - */ - redir (&header_buf); - } - } else { - /* this is a specific code in the command line to - * be returned when a redirection is encountered - */ - } - result = max_state_alt (onredirect, result); - /* all other codes are considered ok */ - } else { - result = STATE_OK; - } - } - - /* libcurl redirection internally, handle error states here */ - if( followmethod == FOLLOW_LIBCURL ) { - handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_REDIRECT_COUNT, &redir_depth), "CURLINFO_REDIRECT_COUNT"); - if (verbose >= 2) - printf(_("* curl LIBINFO_REDIRECT_COUNT is %d\n"), redir_depth); - if (redir_depth > max_depth) { - snprintf (msg, DEFAULT_BUFFER_SIZE, "maximum redirection depth %d exceeded in libcurl", - max_depth); - die (STATE_WARNING, "HTTP WARNING - %s", msg); - } - } - - /* check status codes, set exit status accordingly */ - if( status_line.http_code != code ) { - die (STATE_CRITICAL, _("HTTP CRITICAL %s %d %s - different HTTP codes (cUrl has %ld)\n"), - string_statuscode (status_line.http_major, status_line.http_minor), - status_line.http_code, status_line.msg, code); - } - - if (maximum_age >= 0) { - result = max_state_alt(check_document_dates(&header_buf, &msg), result); - } - - /* Page and Header content checks go here */ - - if (strlen (header_expect)) { - if (!strstr (header_buf.buf, header_expect)) { - - strncpy(&output_header_search[0],header_expect,sizeof(output_header_search)); - - if(output_header_search[sizeof(output_header_search)-1]!='\0') { - bcopy("...",&output_header_search[sizeof(output_header_search)-4],4); - } + /* we got the data and we executed the request in a given time, so we can append + * performance data to the answer always + */ + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time), "CURLINFO_TOTAL_TIME"); + page_len = get_content_length(&header_buf, &body_buf); + if (show_extended_perfdata) { + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &time_connect), "CURLINFO_CONNECT_TIME"); + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &time_appconnect), "CURLINFO_APPCONNECT_TIME"); + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &time_headers), "CURLINFO_PRETRANSFER_TIME"); + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &time_firstbyte), + "CURLINFO_STARTTRANSFER_TIME"); + snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s %s %s %s %s %s", perfd_time(total_time), perfd_size(page_len), + perfd_time_connect(time_connect), use_ssl ? perfd_time_ssl(time_appconnect - time_connect) : "", + perfd_time_headers(time_headers - time_appconnect), perfd_time_firstbyte(time_firstbyte - time_headers), + perfd_time_transfer(total_time - time_firstbyte)); + } else { + snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s", perfd_time(total_time), perfd_size(page_len)); + } - char tmp[DEFAULT_BUFFER_SIZE]; + /* return a CRITICAL status if we couldn't read any data */ + if (strlen(header_buf.buf) == 0 && strlen(body_buf.buf) == 0) + die(STATE_CRITICAL, _("HTTP CRITICAL - No header received from host\n")); - snprintf (tmp, - 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); + /* get status line of answer, check sanity of HTTP code */ + if (curlhelp_parse_statusline(header_buf.buf, &status_line) < 0) { + snprintf(msg, DEFAULT_BUFFER_SIZE, "Unparsable status line in %.3g seconds response time|%s\n", total_time, perfstring); + /* we cannot know the major/minor version here for sure as we cannot parse the first line */ + die(STATE_CRITICAL, "HTTP CRITICAL HTTP/x.x %ld unknown - %s", code, msg); + } + status_line_initialized = true; - strcpy(msg, tmp); + /* get result code from cURL */ + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE"); + if (verbose >= 2) + printf("* curl CURLINFO_RESPONSE_CODE is %ld\n", code); + + /* print status line, header, body if verbose */ + if (verbose >= 2) { + printf("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header_buf.buf, (no_body ? " [[ skipped ]]" : body_buf.buf)); + } + + /* make sure the status line matches the response we are looking for */ + if (!expected_statuscode(status_line.first_line, server_expect)) { + if (server_port == HTTP_PORT) + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host: %s\n"), status_line.first_line); + else + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: %s\n"), server_port, + status_line.first_line); + die(STATE_CRITICAL, "HTTP CRITICAL - %s%s%s", msg, show_body ? "\n" : "", show_body ? body_buf.buf : ""); + } + + if (server_expect_yn) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Status line output matched \"%s\" - "), server_expect); + if (verbose) + printf("%s\n", msg); + result = STATE_OK; + } else { + /* illegal return codes result in a critical state */ + if (code >= 600 || code < 100) { + die(STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%d, %.40s)\n"), status_line.http_code, status_line.msg); + /* server errors result in a critical state */ + } else if (code >= 500) { + result = STATE_CRITICAL; + /* client errors result in a warning state */ + } else if (code >= 400) { + result = STATE_WARNING; + /* check redirected page if specified */ + } else if (code >= 300) { + if (onredirect == STATE_DEPENDENT) { + if (followmethod == FOLLOW_LIBCURL) { + code = status_line.http_code; + } else { + /* old check_http style redirection, if we come + * back here, we are in the same status as with + * the libcurl method + */ + redir(&header_buf); + } + } else { + /* this is a specific code in the command line to + * be returned when a redirection is encountered + */ + } + result = max_state_alt(onredirect, result); + /* all other codes are considered ok */ + } else { + result = STATE_OK; + } + } - result = STATE_CRITICAL; - } - } + /* libcurl redirection internally, handle error states here */ + if (followmethod == FOLLOW_LIBCURL) { + handle_curl_option_return_code(curl_easy_getinfo(curl, CURLINFO_REDIRECT_COUNT, &redir_depth), "CURLINFO_REDIRECT_COUNT"); + if (verbose >= 2) + printf(_("* curl LIBINFO_REDIRECT_COUNT is %d\n"), redir_depth); + if (redir_depth > max_depth) { + snprintf(msg, DEFAULT_BUFFER_SIZE, "maximum redirection depth %d exceeded in libcurl", max_depth); + die(STATE_WARNING, "HTTP WARNING - %s", msg); + } + } - if (strlen (string_expect)) { - if (!strstr (body_buf.buf, string_expect)) { + /* check status codes, set exit status accordingly */ + if (status_line.http_code != code) { + die(STATE_CRITICAL, _("HTTP CRITICAL %s %d %s - different HTTP codes (cUrl has %ld)\n"), + string_statuscode(status_line.http_major, status_line.http_minor), status_line.http_code, status_line.msg, code); + } - strncpy(&output_string_search[0],string_expect,sizeof(output_string_search)); + if (maximum_age >= 0) { + result = max_state_alt(check_document_dates(&header_buf, &msg), result); + } - if(output_string_search[sizeof(output_string_search)-1]!='\0') { - bcopy("...",&output_string_search[sizeof(output_string_search)-4],4); - } + /* Page and Header content checks go here */ + + if (strlen(header_expect)) { + if (!strstr(header_buf.buf, header_expect)) { + + strncpy(&output_header_search[0], header_expect, sizeof(output_header_search)); + + if (output_header_search[sizeof(output_header_search) - 1] != '\0') { + bcopy("...", &output_header_search[sizeof(output_header_search) - 4], 4); + } char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, - 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); + snprintf(tmp, 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); strcpy(msg, tmp); result = STATE_CRITICAL; - } - } - - if (strlen (regexp)) { - errcode = regexec (&preg, body_buf.buf, REGS, pmatch, 0); - if ((errcode == 0 && !invert_regex) || (errcode == REG_NOMATCH && invert_regex)) { - /* OK - No-op to avoid changing the logic around it */ - result = max_state_alt(STATE_OK, result); - } - else if ((errcode == REG_NOMATCH && !invert_regex) || (errcode == 0 && invert_regex)) { + } + } + + if (strlen(string_expect)) { + if (!strstr(body_buf.buf, string_expect)) { + + strncpy(&output_string_search[0], string_expect, sizeof(output_string_search)); + + if (output_string_search[sizeof(output_string_search) - 1] != '\0') { + bcopy("...", &output_string_search[sizeof(output_string_search) - 4], 4); + } + + char tmp[DEFAULT_BUFFER_SIZE]; + + snprintf(tmp, 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); + + strcpy(msg, tmp); + + result = STATE_CRITICAL; + } + } + + if (strlen(regexp)) { + errcode = regexec(&preg, body_buf.buf, REGS, pmatch, 0); + if ((errcode == 0 && !invert_regex) || (errcode == REG_NOMATCH && invert_regex)) { + /* OK - No-op to avoid changing the logic around it */ + result = max_state_alt(STATE_OK, result); + } else if ((errcode == REG_NOMATCH && !invert_regex) || (errcode == 0 && invert_regex)) { if (!invert_regex) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%spattern not found, "), msg); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spattern not found, "), msg); strcpy(msg, tmp); } else { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%spattern found, "), msg); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spattern found, "), msg); strcpy(msg, tmp); - } result = state_regex; } else { - regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); + regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER); char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sExecute Error: %s, "), msg, errbuf); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sExecute Error: %s, "), msg, errbuf); strcpy(msg, tmp); result = STATE_UNKNOWN; } - } + } - /* make sure the page is of an appropriate size */ + /* make sure the page is of an appropriate size */ if ((max_page_len > 0) && (page_len > max_page_len)) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%spage size %d too large, "), msg, page_len); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spage size %d too large, "), msg, page_len); strcpy(msg, tmp); @@ -1175,1281 +1118,1239 @@ GOT_FIRST_CERT: } else if ((min_page_len > 0) && (page_len < min_page_len)) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%spage size %d too small, "), msg, page_len); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%spage size %d too small, "), msg, page_len); strcpy(msg, tmp); result = max_state_alt(STATE_WARNING, result); } - /* -w, -c: check warning and critical level */ - result = max_state_alt(get_status(total_time, thlds), result); - - /* Cut-off trailing characters */ - if (strlen(msg) >= 2) { - if(msg[strlen(msg)-2] == ',') - msg[strlen(msg)-2] = '\0'; - else - msg[strlen(msg)-3] = '\0'; - } - - /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */ - die (max_state_alt(result, result_ssl), "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n%s%s", - state_text(result), string_statuscode (status_line.http_major, status_line.http_minor), - status_line.http_code, status_line.msg, - strlen(msg) > 0 ? " - " : "", - msg, page_len, total_time, - (display_html ? "" : ""), - perfstring, - (show_body ? body_buf.buf : ""), - (show_body ? "\n" : "") ); - - return max_state_alt(result, result_ssl); + /* -w, -c: check warning and critical level */ + result = max_state_alt(get_status(total_time, thlds), result); + + /* Cut-off trailing characters */ + if (strlen(msg) >= 2) { + if (msg[strlen(msg) - 2] == ',') + msg[strlen(msg) - 2] = '\0'; + else + msg[strlen(msg) - 3] = '\0'; + } + + /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */ + die(max_state_alt(result, result_ssl), "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n%s%s", state_text(result), + string_statuscode(status_line.http_major, status_line.http_minor), status_line.http_code, status_line.msg, + strlen(msg) > 0 ? " - " : "", msg, page_len, total_time, (display_html ? "" : ""), perfstring, (show_body ? body_buf.buf : ""), + (show_body ? "\n" : "")); + + return max_state_alt(result, result_ssl); } -int -uri_strcmp (const UriTextRangeA range, const char* s) -{ - if (!range.first) return -1; - if ( (size_t)(range.afterLast - range.first) < strlen (s) ) return -1; - return strncmp (s, range.first, min( (size_t)(range.afterLast - range.first), strlen (s))); +int uri_strcmp(const UriTextRangeA range, const char *s) { + if (!range.first) + return -1; + if ((size_t)(range.afterLast - range.first) < strlen(s)) + return -1; + return strncmp(s, range.first, min((size_t)(range.afterLast - range.first), strlen(s))); } -char* -uri_string (const UriTextRangeA range, char* buf, size_t buflen) -{ - if (!range.first) return "(null)"; - strncpy (buf, range.first, max (buflen-1, (size_t)(range.afterLast - range.first))); - buf[max (buflen-1, (size_t)(range.afterLast - range.first))] = '\0'; - buf[range.afterLast - range.first] = '\0'; - return buf; +char *uri_string(const UriTextRangeA range, char *buf, size_t buflen) { + if (!range.first) + return "(null)"; + strncpy(buf, range.first, max(buflen - 1, (size_t)(range.afterLast - range.first))); + buf[max(buflen - 1, (size_t)(range.afterLast - range.first))] = '\0'; + buf[range.afterLast - range.first] = '\0'; + return buf; } -void -redir (curlhelp_write_curlbuf* header_buf) -{ - char *location = NULL; - curlhelp_statusline status_line; - struct phr_header headers[255]; - size_t nof_headers = 255; - size_t msglen; - char buf[DEFAULT_BUFFER_SIZE]; - char ipstr[INET_ADDR_MAX_SIZE]; - int new_port; - char *new_host; - char *new_url; - - int res = phr_parse_response (header_buf->buf, header_buf->buflen, - &status_line.http_major, &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, - headers, &nof_headers, 0); +void redir(curlhelp_write_curlbuf *header_buf) { + char *location = NULL; + curlhelp_statusline status_line; + struct phr_header headers[255]; + size_t nof_headers = 255; + size_t msglen; + char buf[DEFAULT_BUFFER_SIZE]; + char ipstr[INET_ADDR_MAX_SIZE]; + int new_port; + char *new_host; + char *new_url; + + int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major, &status_line.http_minor, + &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0); if (res == -1) { - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); - } - - location = get_header_value (headers, nof_headers, "location"); - - if (verbose >= 2) - printf(_("* Seen redirect location %s\n"), location); - - if (++redir_depth > max_depth) - die (STATE_WARNING, - _("HTTP WARNING - maximum redirection depth %d exceeded - %s%s\n"), - max_depth, location, (display_html ? "" : "")); - - UriParserStateA state; - UriUriA uri; - state.uri = &uri; - if (uriParseUriA (&state, location) != URI_SUCCESS) { - if (state.errorCode == URI_ERROR_SYNTAX) { - die (STATE_UNKNOWN, - _("HTTP UNKNOWN - Could not parse redirect location '%s'%s\n"), - location, (display_html ? "" : "")); - } else if (state.errorCode == URI_ERROR_MALLOC) { - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); - } - } - - if (verbose >= 2) { - printf (_("** scheme: %s\n"), - uri_string (uri.scheme, buf, DEFAULT_BUFFER_SIZE)); - printf (_("** host: %s\n"), - uri_string (uri.hostText, buf, DEFAULT_BUFFER_SIZE)); - printf (_("** port: %s\n"), - uri_string (uri.portText, buf, DEFAULT_BUFFER_SIZE)); - if (uri.hostData.ip4) { - inet_ntop (AF_INET, uri.hostData.ip4->data, ipstr, sizeof (ipstr)); - printf (_("** IPv4: %s\n"), ipstr); - } - if (uri.hostData.ip6) { - inet_ntop (AF_INET, uri.hostData.ip6->data, ipstr, sizeof (ipstr)); - printf (_("** IPv6: %s\n"), ipstr); - } - if (uri.pathHead) { - printf (_("** path: ")); - const UriPathSegmentA* p = uri.pathHead; - for (; p; p = p->next) { - printf ("/%s", uri_string (p->text, buf, DEFAULT_BUFFER_SIZE)); - } - puts (""); - } - if (uri.query.first) { - printf (_("** query: %s\n"), - uri_string (uri.query, buf, DEFAULT_BUFFER_SIZE)); - } - if (uri.fragment.first) { - printf (_("** fragment: %s\n"), - uri_string (uri.fragment, buf, DEFAULT_BUFFER_SIZE)); - } - } - - if (uri.scheme.first) { - if (!uri_strcmp (uri.scheme, "https")) - use_ssl = true; - else - use_ssl = false; - } - - /* we do a sloppy test here only, because uriparser would have failed - * above, if the port would be invalid, we just check for MAX_PORT - */ - if (uri.portText.first) { - new_port = atoi (uri_string (uri.portText, buf, DEFAULT_BUFFER_SIZE)); - } else { - new_port = HTTP_PORT; - if (use_ssl) - new_port = HTTPS_PORT; - } - if (new_port > MAX_PORT) - die (STATE_UNKNOWN, - _("HTTP UNKNOWN - Redirection to port above %d - %s%s\n"), - MAX_PORT, location, display_html ? "" : ""); - - /* by RFC 7231 relative URLs in Location should be taken relative to - * the original URL, so we try to form a new absolute URL here - */ - if (!uri.scheme.first && !uri.hostText.first) { - new_host = strdup (host_name ? host_name : server_address); - new_port = server_port; - if(use_ssl) - uri_string (uri.scheme, "https", DEFAULT_BUFFER_SIZE); - } else { - new_host = strdup (uri_string (uri.hostText, buf, DEFAULT_BUFFER_SIZE)); - } - - /* compose new path */ - /* TODO: handle fragments and query part of URL */ - new_url = (char *)calloc( 1, DEFAULT_BUFFER_SIZE); - if (uri.pathHead) { - const UriPathSegmentA* p = uri.pathHead; - for (; p; p = p->next) { - strncat (new_url, "/", DEFAULT_BUFFER_SIZE); - strncat (new_url, uri_string (p->text, buf, DEFAULT_BUFFER_SIZE), DEFAULT_BUFFER_SIZE-1); - } - } - - if (server_port==new_port && - !strncmp(server_address, new_host, MAX_IPV4_HOSTLENGTH) && - (host_name && !strncmp(host_name, new_host, MAX_IPV4_HOSTLENGTH)) && - !strcmp(server_url, new_url)) - die (STATE_CRITICAL, - _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"), - use_ssl ? "https" : "http", new_host, new_port, new_url, (display_html ? "" : "")); - - /* set new values for redirected request */ - - if (!(followsticky & STICKY_HOST)) { - free (server_address); - server_address = strndup (new_host, MAX_IPV4_HOSTLENGTH); - } - if (!(followsticky & STICKY_PORT)) { - server_port = (unsigned short)new_port; - } - - free (host_name); - host_name = strndup (new_host, MAX_IPV4_HOSTLENGTH); - - /* reset virtual port */ - virtual_port = server_port; - - free(new_host); - free (server_url); - server_url = new_url; - - uriFreeUriMembersA (&uri); - - if (verbose) - printf (_("Redirection to %s://%s:%d%s\n"), use_ssl ? "https" : "http", - host_name ? host_name : server_address, server_port, server_url); - - /* TODO: the hash component MUST be taken from the original URL and - * attached to the URL in Location - */ - - cleanup (); - check_http (); + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); + } + + location = get_header_value(headers, nof_headers, "location"); + + if (verbose >= 2) + printf(_("* Seen redirect location %s\n"), location); + + if (++redir_depth > max_depth) + die(STATE_WARNING, _("HTTP WARNING - maximum redirection depth %d exceeded - %s%s\n"), max_depth, location, + (display_html ? "" : "")); + + UriParserStateA state; + UriUriA uri; + state.uri = &uri; + if (uriParseUriA(&state, location) != URI_SUCCESS) { + if (state.errorCode == URI_ERROR_SYNTAX) { + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not parse redirect location '%s'%s\n"), location, (display_html ? "" : "")); + } else if (state.errorCode == URI_ERROR_MALLOC) { + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); + } + } + + if (verbose >= 2) { + printf(_("** scheme: %s\n"), uri_string(uri.scheme, buf, DEFAULT_BUFFER_SIZE)); + printf(_("** host: %s\n"), uri_string(uri.hostText, buf, DEFAULT_BUFFER_SIZE)); + printf(_("** port: %s\n"), uri_string(uri.portText, buf, DEFAULT_BUFFER_SIZE)); + if (uri.hostData.ip4) { + inet_ntop(AF_INET, uri.hostData.ip4->data, ipstr, sizeof(ipstr)); + printf(_("** IPv4: %s\n"), ipstr); + } + if (uri.hostData.ip6) { + inet_ntop(AF_INET, uri.hostData.ip6->data, ipstr, sizeof(ipstr)); + printf(_("** IPv6: %s\n"), ipstr); + } + if (uri.pathHead) { + printf(_("** path: ")); + const UriPathSegmentA *p = uri.pathHead; + for (; p; p = p->next) { + printf("/%s", uri_string(p->text, buf, DEFAULT_BUFFER_SIZE)); + } + puts(""); + } + if (uri.query.first) { + printf(_("** query: %s\n"), uri_string(uri.query, buf, DEFAULT_BUFFER_SIZE)); + } + if (uri.fragment.first) { + printf(_("** fragment: %s\n"), uri_string(uri.fragment, buf, DEFAULT_BUFFER_SIZE)); + } + } + + if (uri.scheme.first) { + if (!uri_strcmp(uri.scheme, "https")) + use_ssl = true; + else + use_ssl = false; + } + + /* we do a sloppy test here only, because uriparser would have failed + * above, if the port would be invalid, we just check for MAX_PORT + */ + if (uri.portText.first) { + new_port = atoi(uri_string(uri.portText, buf, DEFAULT_BUFFER_SIZE)); + } else { + new_port = HTTP_PORT; + if (use_ssl) + new_port = HTTPS_PORT; + } + if (new_port > MAX_PORT) + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Redirection to port above %d - %s%s\n"), MAX_PORT, location, display_html ? "" : ""); + + /* by RFC 7231 relative URLs in Location should be taken relative to + * the original URL, so we try to form a new absolute URL here + */ + if (!uri.scheme.first && !uri.hostText.first) { + new_host = strdup(host_name ? host_name : server_address); + new_port = server_port; + if (use_ssl) + uri_string(uri.scheme, "https", DEFAULT_BUFFER_SIZE); + } else { + new_host = strdup(uri_string(uri.hostText, buf, DEFAULT_BUFFER_SIZE)); + } + + /* compose new path */ + /* TODO: handle fragments and query part of URL */ + new_url = (char *)calloc(1, DEFAULT_BUFFER_SIZE); + if (uri.pathHead) { + const UriPathSegmentA *p = uri.pathHead; + for (; p; p = p->next) { + strncat(new_url, "/", DEFAULT_BUFFER_SIZE); + strncat(new_url, uri_string(p->text, buf, DEFAULT_BUFFER_SIZE), DEFAULT_BUFFER_SIZE - 1); + } + } + + if (server_port == new_port && !strncmp(server_address, new_host, MAX_IPV4_HOSTLENGTH) && + (host_name && !strncmp(host_name, new_host, MAX_IPV4_HOSTLENGTH)) && !strcmp(server_url, new_url)) + die(STATE_CRITICAL, _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"), use_ssl ? "https" : "http", + new_host, new_port, new_url, (display_html ? "" : "")); + + /* set new values for redirected request */ + + if (!(followsticky & STICKY_HOST)) { + free(server_address); + server_address = strndup(new_host, MAX_IPV4_HOSTLENGTH); + } + if (!(followsticky & STICKY_PORT)) { + server_port = (unsigned short)new_port; + } + + free(host_name); + host_name = strndup(new_host, MAX_IPV4_HOSTLENGTH); + + /* reset virtual port */ + virtual_port = server_port; + + free(new_host); + free(server_url); + server_url = new_url; + + uriFreeUriMembersA(&uri); + + if (verbose) + printf(_("Redirection to %s://%s:%d%s\n"), use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, + server_url); + + /* TODO: the hash component MUST be taken from the original URL and + * attached to the URL in Location + */ + + cleanup(); + check_http(); } /* check whether a file exists */ -void -test_file (char *path) -{ - if (access(path, R_OK) == 0) - return; - usage2 (_("file does not exist or is not readable"), path); +void test_file(char *path) { + if (access(path, R_OK) == 0) + return; + usage2(_("file does not exist or is not readable"), path); } -bool -process_arguments (int argc, char **argv) -{ - char *p; - int c = 1; - char *temp; - - enum { - INVERT_REGEX = CHAR_MAX + 1, - SNI_OPTION, - MAX_REDIRS_OPTION, - CONTINUE_AFTER_CHECK_CERT, - CA_CERT_OPTION, - HTTP_VERSION_OPTION, - AUTOMATIC_DECOMPRESSION, - COOKIE_JAR, - HAPROXY_PROTOCOL, - STATE_REGEX - }; - - int option = 0; - int got_plus = 0; - static struct option longopts[] = { - STD_LONG_OPTS, - {"link", no_argument, 0, 'L'}, - {"nohtml", no_argument, 0, 'n'}, - {"ssl", optional_argument, 0, 'S'}, - {"sni", no_argument, 0, SNI_OPTION}, - {"post", required_argument, 0, 'P'}, - {"method", required_argument, 0, 'j'}, - {"IP-address", required_argument, 0, 'I'}, - {"url", required_argument, 0, 'u'}, - {"port", required_argument, 0, 'p'}, - {"authorization", required_argument, 0, 'a'}, - {"proxy-authorization", required_argument, 0, 'b'}, - {"header-string", required_argument, 0, 'd'}, - {"string", required_argument, 0, 's'}, - {"expect", required_argument, 0, 'e'}, - {"regex", required_argument, 0, 'r'}, - {"ereg", required_argument, 0, 'r'}, - {"eregi", required_argument, 0, 'R'}, - {"linespan", no_argument, 0, 'l'}, - {"onredirect", required_argument, 0, 'f'}, - {"certificate", required_argument, 0, 'C'}, - {"client-cert", required_argument, 0, 'J'}, - {"private-key", required_argument, 0, 'K'}, - {"ca-cert", required_argument, 0, CA_CERT_OPTION}, - {"verify-cert", no_argument, 0, 'D'}, - {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT}, - {"useragent", required_argument, 0, 'A'}, - {"header", required_argument, 0, 'k'}, - {"no-body", no_argument, 0, 'N'}, - {"max-age", required_argument, 0, 'M'}, - {"content-type", required_argument, 0, 'T'}, - {"pagesize", required_argument, 0, 'm'}, - {"invert-regex", no_argument, NULL, INVERT_REGEX}, - {"state-regex", required_argument, 0, STATE_REGEX}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {"extended-perfdata", no_argument, 0, 'E'}, - {"show-body", no_argument, 0, 'B'}, - {"max-redirs", required_argument, 0, MAX_REDIRS_OPTION}, - {"http-version", required_argument, 0, HTTP_VERSION_OPTION}, - {"enable-automatic-decompression", no_argument, 0, AUTOMATIC_DECOMPRESSION}, - {"cookie-jar", required_argument, 0, COOKIE_JAR}, - {"haproxy-protocol", no_argument, 0, HAPROXY_PROTOCOL}, - {0, 0, 0, 0} - }; - - if (argc < 2) - return false; - - /* support check_http compatible arguments */ - for (c = 1; c < argc; c++) { - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - if (strcmp ("-hn", argv[c]) == 0) - strcpy (argv[c], "-H"); - if (strcmp ("-wt", argv[c]) == 0) - strcpy (argv[c], "-w"); - if (strcmp ("-ct", argv[c]) == 0) - strcpy (argv[c], "-c"); - if (strcmp ("-nohtml", argv[c]) == 0) - strcpy (argv[c], "-n"); - } - - server_url = strdup(DEFAULT_SERVER_URL); - - while (1) { - 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); - if (c == -1 || c == EOF || c == 1) - break; - - switch (c) { - case 'h': - print_help(); - exit(STATE_UNKNOWN); - break; - case 'V': - print_revision(progname, NP_VERSION); - print_curl_version(); - exit(STATE_UNKNOWN); - break; - case 'v': - verbose++; - break; - case 't': /* timeout period */ - if (!is_intnonneg (optarg)) - usage2 (_("Timeout interval must be a positive integer"), optarg); - else - socket_timeout = (int)strtol (optarg, NULL, 10); - break; - case 'c': /* critical time threshold */ - critical_thresholds = optarg; - break; - case 'w': /* warning time threshold */ - warning_thresholds = optarg; - break; - case 'H': /* virtual host */ - host_name = strdup (optarg); - if (host_name[0] == '[') { - if ((p = strstr (host_name, "]:")) != NULL) { /* [IPv6]:port */ - virtual_port = atoi (p + 2); - /* cut off the port */ - host_name_length = strlen (host_name) - strlen (p) - 1; - free (host_name); - host_name = strndup (optarg, host_name_length); - } - } else if ((p = strchr (host_name, ':')) != NULL - && strchr (++p, ':') == NULL) { /* IPv4:port or host:port */ - virtual_port = atoi (p); - /* cut off the port */ - host_name_length = strlen (host_name) - strlen (p) - 1; - free (host_name); - host_name = strndup (optarg, host_name_length); - } - break; - case 'I': /* internet address */ - server_address = strdup (optarg); - break; - case 'u': /* URL path */ - server_url = strdup (optarg); - break; - case 'p': /* Server port */ - if (!is_intnonneg (optarg)) - usage2 (_("Invalid port number, expecting a non-negative number"), optarg); - else { - if( strtol(optarg, NULL, 10) > MAX_PORT) - usage2 (_("Invalid port number, supplied port number is too big"), optarg); - server_port = (unsigned short)strtol(optarg, NULL, 10); - specify_port = true; - } - break; - case 'a': /* authorization info */ - strncpy (user_auth, optarg, MAX_INPUT_BUFFER - 1); - user_auth[MAX_INPUT_BUFFER - 1] = 0; - break; - case 'b': /* proxy-authorization info */ - strncpy (proxy_auth, optarg, MAX_INPUT_BUFFER - 1); - proxy_auth[MAX_INPUT_BUFFER - 1] = 0; - break; - case 'P': /* HTTP POST data in URL encoded format; ignored if settings already */ - if (! http_post_data) - http_post_data = strdup (optarg); - if (! http_method) - http_method = strdup("POST"); - break; - case 'j': /* Set HTTP method */ - if (http_method) - free(http_method); - http_method = strdup (optarg); - break; - case 'A': /* useragent */ - strncpy (user_agent, optarg, DEFAULT_BUFFER_SIZE); - user_agent[DEFAULT_BUFFER_SIZE-1] = '\0'; - break; - case 'k': /* Additional headers */ - if (http_opt_headers_count == 0) - http_opt_headers = malloc (sizeof (char *) * (++http_opt_headers_count)); - else - http_opt_headers = realloc (http_opt_headers, sizeof (char *) * (++http_opt_headers_count)); - http_opt_headers[http_opt_headers_count - 1] = optarg; - break; - case 'L': /* show html link */ - display_html = true; - break; - case 'n': /* do not show html link */ - display_html = false; - break; - case 'C': /* Check SSL cert validity */ +bool process_arguments(int argc, char **argv) { + char *p; + int c = 1; + char *temp; + + enum { + INVERT_REGEX = CHAR_MAX + 1, + SNI_OPTION, + MAX_REDIRS_OPTION, + CONTINUE_AFTER_CHECK_CERT, + CA_CERT_OPTION, + HTTP_VERSION_OPTION, + AUTOMATIC_DECOMPRESSION, + COOKIE_JAR, + HAPROXY_PROTOCOL, + STATE_REGEX + }; + + int option = 0; + int got_plus = 0; + static struct option longopts[] = {STD_LONG_OPTS, + {"link", no_argument, 0, 'L'}, + {"nohtml", no_argument, 0, 'n'}, + {"ssl", optional_argument, 0, 'S'}, + {"sni", no_argument, 0, SNI_OPTION}, + {"post", required_argument, 0, 'P'}, + {"method", required_argument, 0, 'j'}, + {"IP-address", required_argument, 0, 'I'}, + {"url", required_argument, 0, 'u'}, + {"port", required_argument, 0, 'p'}, + {"authorization", required_argument, 0, 'a'}, + {"proxy-authorization", required_argument, 0, 'b'}, + {"header-string", required_argument, 0, 'd'}, + {"string", required_argument, 0, 's'}, + {"expect", required_argument, 0, 'e'}, + {"regex", required_argument, 0, 'r'}, + {"ereg", required_argument, 0, 'r'}, + {"eregi", required_argument, 0, 'R'}, + {"linespan", no_argument, 0, 'l'}, + {"onredirect", required_argument, 0, 'f'}, + {"certificate", required_argument, 0, 'C'}, + {"client-cert", required_argument, 0, 'J'}, + {"private-key", required_argument, 0, 'K'}, + {"ca-cert", required_argument, 0, CA_CERT_OPTION}, + {"verify-cert", no_argument, 0, 'D'}, + {"continue-after-certificate", no_argument, 0, CONTINUE_AFTER_CHECK_CERT}, + {"useragent", required_argument, 0, 'A'}, + {"header", required_argument, 0, 'k'}, + {"no-body", no_argument, 0, 'N'}, + {"max-age", required_argument, 0, 'M'}, + {"content-type", required_argument, 0, 'T'}, + {"pagesize", required_argument, 0, 'm'}, + {"invert-regex", no_argument, NULL, INVERT_REGEX}, + {"state-regex", required_argument, 0, STATE_REGEX}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {"extended-perfdata", no_argument, 0, 'E'}, + {"show-body", no_argument, 0, 'B'}, + {"max-redirs", required_argument, 0, MAX_REDIRS_OPTION}, + {"http-version", required_argument, 0, HTTP_VERSION_OPTION}, + {"enable-automatic-decompression", no_argument, 0, AUTOMATIC_DECOMPRESSION}, + {"cookie-jar", required_argument, 0, COOKIE_JAR}, + {"haproxy-protocol", no_argument, 0, HAPROXY_PROTOCOL}, + {0, 0, 0, 0}}; + + if (argc < 2) + return false; + + /* support check_http compatible arguments */ + for (c = 1; c < argc; c++) { + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + if (strcmp("-hn", argv[c]) == 0) + strcpy(argv[c], "-H"); + if (strcmp("-wt", argv[c]) == 0) + strcpy(argv[c], "-w"); + if (strcmp("-ct", argv[c]) == 0) + strcpy(argv[c], "-c"); + if (strcmp("-nohtml", argv[c]) == 0) + strcpy(argv[c], "-n"); + } + + server_url = strdup(DEFAULT_SERVER_URL); + + while (1) { + 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); + if (c == -1 || c == EOF || c == 1) + break; + + switch (c) { + case 'h': + print_help(); + exit(STATE_UNKNOWN); + break; + case 'V': + print_revision(progname, NP_VERSION); + print_curl_version(); + exit(STATE_UNKNOWN); + break; + case 'v': + verbose++; + break; + case 't': /* timeout period */ + if (!is_intnonneg(optarg)) + usage2(_("Timeout interval must be a positive integer"), optarg); + else + socket_timeout = (int)strtol(optarg, NULL, 10); + break; + case 'c': /* critical time threshold */ + critical_thresholds = optarg; + break; + case 'w': /* warning time threshold */ + warning_thresholds = optarg; + break; + case 'H': /* virtual host */ + host_name = strdup(optarg); + if (host_name[0] == '[') { + if ((p = strstr(host_name, "]:")) != NULL) { /* [IPv6]:port */ + virtual_port = atoi(p + 2); + /* cut off the port */ + host_name_length = strlen(host_name) - strlen(p) - 1; + free(host_name); + host_name = strndup(optarg, host_name_length); + } + } else if ((p = strchr(host_name, ':')) != NULL && strchr(++p, ':') == NULL) { /* IPv4:port or host:port */ + virtual_port = atoi(p); + /* cut off the port */ + host_name_length = strlen(host_name) - strlen(p) - 1; + free(host_name); + host_name = strndup(optarg, host_name_length); + } + break; + case 'I': /* internet address */ + server_address = strdup(optarg); + break; + case 'u': /* URL path */ + server_url = strdup(optarg); + break; + case 'p': /* Server port */ + if (!is_intnonneg(optarg)) + usage2(_("Invalid port number, expecting a non-negative number"), optarg); + else { + if (strtol(optarg, NULL, 10) > MAX_PORT) + usage2(_("Invalid port number, supplied port number is too big"), optarg); + server_port = (unsigned short)strtol(optarg, NULL, 10); + specify_port = true; + } + break; + case 'a': /* authorization info */ + strncpy(user_auth, optarg, MAX_INPUT_BUFFER - 1); + user_auth[MAX_INPUT_BUFFER - 1] = 0; + break; + case 'b': /* proxy-authorization info */ + strncpy(proxy_auth, optarg, MAX_INPUT_BUFFER - 1); + proxy_auth[MAX_INPUT_BUFFER - 1] = 0; + break; + case 'P': /* HTTP POST data in URL encoded format; ignored if settings already */ + if (!http_post_data) + http_post_data = strdup(optarg); + if (!http_method) + http_method = strdup("POST"); + break; + case 'j': /* Set HTTP method */ + if (http_method) + free(http_method); + http_method = strdup(optarg); + break; + case 'A': /* useragent */ + strncpy(user_agent, optarg, DEFAULT_BUFFER_SIZE); + user_agent[DEFAULT_BUFFER_SIZE - 1] = '\0'; + break; + case 'k': /* Additional headers */ + if (http_opt_headers_count == 0) + http_opt_headers = malloc(sizeof(char *) * (++http_opt_headers_count)); + else + http_opt_headers = realloc(http_opt_headers, sizeof(char *) * (++http_opt_headers_count)); + http_opt_headers[http_opt_headers_count - 1] = optarg; + break; + case 'L': /* show html link */ + display_html = true; + break; + case 'n': /* do not show html link */ + display_html = false; + break; + case 'C': /* Check SSL cert validity */ #ifdef LIBCURL_FEATURE_SSL - if ((temp=strchr(optarg,','))!=NULL) { - *temp='\0'; - if (!is_intnonneg (optarg)) - usage2 (_("Invalid certificate expiration period"), optarg); - days_till_exp_warn = atoi(optarg); - *temp=','; - temp++; - if (!is_intnonneg (temp)) - usage2 (_("Invalid certificate expiration period"), temp); - days_till_exp_crit = atoi (temp); - } - else { - days_till_exp_crit=0; - if (!is_intnonneg (optarg)) - usage2 (_("Invalid certificate expiration period"), optarg); - days_till_exp_warn = atoi (optarg); - } - check_cert = true; - goto enable_ssl; + if ((temp = strchr(optarg, ',')) != NULL) { + *temp = '\0'; + if (!is_intnonneg(optarg)) + usage2(_("Invalid certificate expiration period"), optarg); + days_till_exp_warn = atoi(optarg); + *temp = ','; + temp++; + if (!is_intnonneg(temp)) + usage2(_("Invalid certificate expiration period"), temp); + days_till_exp_crit = atoi(temp); + } else { + days_till_exp_crit = 0; + if (!is_intnonneg(optarg)) + usage2(_("Invalid certificate expiration period"), optarg); + days_till_exp_warn = atoi(optarg); + } + check_cert = true; + goto enable_ssl; #endif - case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is checked */ + case CONTINUE_AFTER_CHECK_CERT: /* don't stop after the certificate is checked */ #ifdef HAVE_SSL - continue_after_check_cert = true; - break; + continue_after_check_cert = true; + break; #endif - case 'J': /* use client certificate */ + case 'J': /* use client certificate */ #ifdef LIBCURL_FEATURE_SSL - test_file(optarg); - client_cert = optarg; - goto enable_ssl; + test_file(optarg); + client_cert = optarg; + goto enable_ssl; #endif - case 'K': /* use client private key */ + case 'K': /* use client private key */ #ifdef LIBCURL_FEATURE_SSL - test_file(optarg); - client_privkey = optarg; - goto enable_ssl; + test_file(optarg); + client_privkey = optarg; + goto enable_ssl; #endif #ifdef LIBCURL_FEATURE_SSL - case CA_CERT_OPTION: /* use CA chain file */ - test_file(optarg); - ca_cert = optarg; - goto enable_ssl; + case CA_CERT_OPTION: /* use CA chain file */ + test_file(optarg); + ca_cert = optarg; + goto enable_ssl; #endif #ifdef LIBCURL_FEATURE_SSL - case 'D': /* verify peer certificate & host */ - verify_peer_and_host = true; - break; + case 'D': /* verify peer certificate & host */ + verify_peer_and_host = true; + break; #endif - case 'S': /* use SSL */ + case 'S': /* use SSL */ #ifdef LIBCURL_FEATURE_SSL - enable_ssl: - use_ssl = true; - /* ssl_version initialized to CURL_SSLVERSION_DEFAULT as a default. - * Only set if it's non-zero. This helps when we include multiple - * parameters, like -S and -C combinations */ - ssl_version = CURL_SSLVERSION_DEFAULT; - if (c=='S' && optarg != NULL) { - char *plus_ptr = strchr(optarg, '+'); - if (plus_ptr) { - got_plus = 1; - *plus_ptr = '\0'; - } - - if (optarg[0] == '2') - ssl_version = CURL_SSLVERSION_SSLv2; - else if (optarg[0] == '3') - ssl_version = CURL_SSLVERSION_SSLv3; - else if (!strcmp (optarg, "1") || !strcmp (optarg, "1.0")) -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) - ssl_version = CURL_SSLVERSION_TLSv1_0; -#else - ssl_version = CURL_SSLVERSION_DEFAULT; -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ - else if (!strcmp (optarg, "1.1")) -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) - ssl_version = CURL_SSLVERSION_TLSv1_1; -#else - ssl_version = CURL_SSLVERSION_DEFAULT; -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ - else if (!strcmp (optarg, "1.2")) -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) - ssl_version = CURL_SSLVERSION_TLSv1_2; -#else - ssl_version = CURL_SSLVERSION_DEFAULT; -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ - else if (!strcmp (optarg, "1.3")) -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) - ssl_version = CURL_SSLVERSION_TLSv1_3; -#else - ssl_version = CURL_SSLVERSION_DEFAULT; -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) */ - else - usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2, 1.3 (with optional '+' suffix)")); - } -#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) - if (got_plus) { - switch (ssl_version) { - case CURL_SSLVERSION_TLSv1_3: - ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3; - break; - case CURL_SSLVERSION_TLSv1_2: - case CURL_SSLVERSION_TLSv1_1: - case CURL_SSLVERSION_TLSv1_0: - ssl_version |= CURL_SSLVERSION_MAX_DEFAULT; - break; - } - } else { - switch (ssl_version) { - case CURL_SSLVERSION_TLSv1_3: - ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3; - break; - case CURL_SSLVERSION_TLSv1_2: - ssl_version |= CURL_SSLVERSION_MAX_TLSv1_2; - break; - case CURL_SSLVERSION_TLSv1_1: - ssl_version |= CURL_SSLVERSION_MAX_TLSv1_1; - break; - case CURL_SSLVERSION_TLSv1_0: - ssl_version |= CURL_SSLVERSION_MAX_TLSv1_0; - break; - } - } -#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) */ - if (verbose >= 2) - printf(_("* Set SSL/TLS version to %d\n"), ssl_version); - if (!specify_port) - server_port = HTTPS_PORT; - break; -#else /* LIBCURL_FEATURE_SSL */ - /* -C -J and -K fall through to here without SSL */ - usage4 (_("Invalid option - SSL is not available")); - break; - case SNI_OPTION: /* --sni is parsed, but ignored, the default is true with libcurl */ - use_sni = true; - break; + enable_ssl: + use_ssl = true; + /* ssl_version initialized to CURL_SSLVERSION_DEFAULT as a default. + * Only set if it's non-zero. This helps when we include multiple + * parameters, like -S and -C combinations */ + ssl_version = CURL_SSLVERSION_DEFAULT; + if (c == 'S' && optarg != NULL) { + char *plus_ptr = strchr(optarg, '+'); + if (plus_ptr) { + got_plus = 1; + *plus_ptr = '\0'; + } + + if (optarg[0] == '2') + ssl_version = CURL_SSLVERSION_SSLv2; + else if (optarg[0] == '3') + ssl_version = CURL_SSLVERSION_SSLv3; + else if (!strcmp(optarg, "1") || !strcmp(optarg, "1.0")) +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + ssl_version = CURL_SSLVERSION_TLSv1_0; +# else + ssl_version = CURL_SSLVERSION_DEFAULT; +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + else if (!strcmp(optarg, "1.1")) +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + ssl_version = CURL_SSLVERSION_TLSv1_1; +# else + ssl_version = CURL_SSLVERSION_DEFAULT; +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + else if (!strcmp(optarg, "1.2")) +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + ssl_version = CURL_SSLVERSION_TLSv1_2; +# else + ssl_version = CURL_SSLVERSION_DEFAULT; +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + else if (!strcmp(optarg, "1.3")) +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) + ssl_version = CURL_SSLVERSION_TLSv1_3; +# else + ssl_version = CURL_SSLVERSION_DEFAULT; +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) */ + else + usage4(_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2, 1.3 (with optional '+' suffix)")); + } +# if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) + if (got_plus) { + switch (ssl_version) { + case CURL_SSLVERSION_TLSv1_3: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3; + break; + case CURL_SSLVERSION_TLSv1_2: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_0: + ssl_version |= CURL_SSLVERSION_MAX_DEFAULT; + break; + } + } else { + switch (ssl_version) { + case CURL_SSLVERSION_TLSv1_3: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3; + break; + case CURL_SSLVERSION_TLSv1_2: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_2; + break; + case CURL_SSLVERSION_TLSv1_1: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_1; + break; + case CURL_SSLVERSION_TLSv1_0: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_0; + break; + } + } +# endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) */ + if (verbose >= 2) + printf(_("* Set SSL/TLS version to %d\n"), ssl_version); + if (!specify_port) + server_port = HTTPS_PORT; + break; +#else /* LIBCURL_FEATURE_SSL */ + /* -C -J and -K fall through to here without SSL */ + usage4(_("Invalid option - SSL is not available")); + break; + case SNI_OPTION: /* --sni is parsed, but ignored, the default is true with libcurl */ + use_sni = true; + break; #endif /* LIBCURL_FEATURE_SSL */ - case MAX_REDIRS_OPTION: - if (!is_intnonneg (optarg)) - usage2 (_("Invalid max_redirs count"), optarg); - else { - max_depth = atoi (optarg); - } - break; - case 'f': /* onredirect */ - if (!strcmp (optarg, "ok")) - onredirect = STATE_OK; - else if (!strcmp (optarg, "warning")) - onredirect = STATE_WARNING; - else if (!strcmp (optarg, "critical")) - onredirect = STATE_CRITICAL; - else if (!strcmp (optarg, "unknown")) - onredirect = STATE_UNKNOWN; - else if (!strcmp (optarg, "follow")) - onredirect = STATE_DEPENDENT; - else if (!strcmp (optarg, "stickyport")) - onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST|STICKY_PORT; - else if (!strcmp (optarg, "sticky")) - onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST; - else if (!strcmp (optarg, "follow")) - onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_NONE; - else if (!strcmp (optarg, "curl")) - onredirect = STATE_DEPENDENT, followmethod = FOLLOW_LIBCURL; - else usage2 (_("Invalid onredirect option"), optarg); - if (verbose >= 2) - printf(_("* Following redirects set to %s\n"), state_text(onredirect)); - break; - case 'd': /* string or substring */ - strncpy (header_expect, optarg, MAX_INPUT_BUFFER - 1); - header_expect[MAX_INPUT_BUFFER - 1] = 0; - break; - case 's': /* string or substring */ - strncpy (string_expect, optarg, MAX_INPUT_BUFFER - 1); - string_expect[MAX_INPUT_BUFFER - 1] = 0; - break; - case 'e': /* string or substring */ - strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1); - server_expect[MAX_INPUT_BUFFER - 1] = 0; - server_expect_yn = 1; - break; - case 'T': /* Content-type */ - http_content_type = strdup (optarg); - break; - case 'l': /* linespan */ - cflags &= ~REG_NEWLINE; - break; - case 'R': /* regex */ - cflags |= REG_ICASE; + case MAX_REDIRS_OPTION: + if (!is_intnonneg(optarg)) + usage2(_("Invalid max_redirs count"), optarg); + else { + max_depth = atoi(optarg); + } + break; + case 'f': /* onredirect */ + if (!strcmp(optarg, "ok")) + onredirect = STATE_OK; + else if (!strcmp(optarg, "warning")) + onredirect = STATE_WARNING; + else if (!strcmp(optarg, "critical")) + onredirect = STATE_CRITICAL; + else if (!strcmp(optarg, "unknown")) + onredirect = STATE_UNKNOWN; + else if (!strcmp(optarg, "follow")) + onredirect = STATE_DEPENDENT; + else if (!strcmp(optarg, "stickyport")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST | STICKY_PORT; + else if (!strcmp(optarg, "sticky")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST; + else if (!strcmp(optarg, "follow")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_NONE; + else if (!strcmp(optarg, "curl")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_LIBCURL; + else + usage2(_("Invalid onredirect option"), optarg); + if (verbose >= 2) + printf(_("* Following redirects set to %s\n"), state_text(onredirect)); + break; + case 'd': /* string or substring */ + strncpy(header_expect, optarg, MAX_INPUT_BUFFER - 1); + header_expect[MAX_INPUT_BUFFER - 1] = 0; + break; + case 's': /* string or substring */ + strncpy(string_expect, optarg, MAX_INPUT_BUFFER - 1); + string_expect[MAX_INPUT_BUFFER - 1] = 0; + break; + case 'e': /* string or substring */ + strncpy(server_expect, optarg, MAX_INPUT_BUFFER - 1); + server_expect[MAX_INPUT_BUFFER - 1] = 0; + server_expect_yn = 1; + break; + case 'T': /* Content-type */ + http_content_type = strdup(optarg); + break; + case 'l': /* linespan */ + cflags &= ~REG_NEWLINE; + break; + case 'R': /* regex */ + cflags |= REG_ICASE; // fall through - case 'r': /* regex */ - strncpy (regexp, optarg, MAX_RE_SIZE - 1); - regexp[MAX_RE_SIZE - 1] = 0; - errcode = regcomp (&preg, regexp, cflags); - if (errcode != 0) { - (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); - printf (_("Could Not Compile Regular Expression: %s"), errbuf); - return false; - } - break; - case INVERT_REGEX: - invert_regex = true; - break; - case STATE_REGEX: - if (!strcasecmp (optarg, "critical")) - state_regex = STATE_CRITICAL; - else if (!strcasecmp (optarg, "warning")) - state_regex = STATE_WARNING; - else usage2 (_("Invalid state-regex option"), optarg); - break; - case '4': - address_family = AF_INET; - break; - case '6': -#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6) - address_family = AF_INET6; + case 'r': /* regex */ + strncpy(regexp, optarg, MAX_RE_SIZE - 1); + regexp[MAX_RE_SIZE - 1] = 0; + errcode = regcomp(&preg, regexp, cflags); + if (errcode != 0) { + (void)regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER); + printf(_("Could Not Compile Regular Expression: %s"), errbuf); + return false; + } + break; + case INVERT_REGEX: + invert_regex = true; + break; + case STATE_REGEX: + if (!strcasecmp(optarg, "critical")) + state_regex = STATE_CRITICAL; + else if (!strcasecmp(optarg, "warning")) + state_regex = STATE_WARNING; + else + usage2(_("Invalid state-regex option"), optarg); + break; + case '4': + address_family = AF_INET; + break; + case '6': +#if defined(USE_IPV6) && defined(LIBCURL_FEATURE_IPV6) + address_family = AF_INET6; #else - usage4 (_("IPv6 support not available")); + usage4(_("IPv6 support not available")); #endif - break; - case 'm': /* min_page_length */ - { - char *tmp; - if (strchr(optarg, ':') != (char *)NULL) { - /* range, so get two values, min:max */ - tmp = strtok(optarg, ":"); - if (tmp == NULL) { - printf("Bad format: try \"-m min:max\"\n"); - exit (STATE_WARNING); - } else - min_page_len = atoi(tmp); - - tmp = strtok(NULL, ":"); - if (tmp == NULL) { - printf("Bad format: try \"-m min:max\"\n"); - exit (STATE_WARNING); - } else - max_page_len = atoi(tmp); - } else - min_page_len = atoi (optarg); - break; - } - case 'N': /* no-body */ - no_body = true; - break; - case 'M': /* max-age */ - { - int L = strlen(optarg); - if (L && optarg[L-1] == 'm') - maximum_age = atoi (optarg) * 60; - else if (L && optarg[L-1] == 'h') - maximum_age = atoi (optarg) * 60 * 60; - else if (L && optarg[L-1] == 'd') - maximum_age = atoi (optarg) * 60 * 60 * 24; - else if (L && (optarg[L-1] == 's' || - isdigit (optarg[L-1]))) - maximum_age = atoi (optarg); - else { - fprintf (stderr, "unparsable max-age: %s\n", optarg); - exit (STATE_WARNING); - } - if (verbose >= 2) - printf ("* Maximal age of document set to %d seconds\n", maximum_age); - } - break; - case 'E': /* show extended perfdata */ - show_extended_perfdata = true; - break; - case 'B': /* print body content after status line */ - show_body = true; - break; - case HTTP_VERSION_OPTION: - curl_http_version = CURL_HTTP_VERSION_NONE; - if (strcmp (optarg, "1.0") == 0) { - curl_http_version = CURL_HTTP_VERSION_1_0; - } else if (strcmp (optarg, "1.1") == 0) { - curl_http_version = CURL_HTTP_VERSION_1_1; - } else if ((strcmp (optarg, "2.0") == 0) || (strcmp (optarg, "2") == 0)) { + break; + case 'm': /* min_page_length */ + { + char *tmp; + if (strchr(optarg, ':') != (char *)NULL) { + /* range, so get two values, min:max */ + tmp = strtok(optarg, ":"); + if (tmp == NULL) { + printf("Bad format: try \"-m min:max\"\n"); + exit(STATE_WARNING); + } else + min_page_len = atoi(tmp); + + tmp = strtok(NULL, ":"); + if (tmp == NULL) { + printf("Bad format: try \"-m min:max\"\n"); + exit(STATE_WARNING); + } else + max_page_len = atoi(tmp); + } else + min_page_len = atoi(optarg); + break; + } + case 'N': /* no-body */ + no_body = true; + break; + case 'M': /* max-age */ + { + int L = strlen(optarg); + if (L && optarg[L - 1] == 'm') + maximum_age = atoi(optarg) * 60; + else if (L && optarg[L - 1] == 'h') + maximum_age = atoi(optarg) * 60 * 60; + else if (L && optarg[L - 1] == 'd') + maximum_age = atoi(optarg) * 60 * 60 * 24; + else if (L && (optarg[L - 1] == 's' || isdigit(optarg[L - 1]))) + maximum_age = atoi(optarg); + else { + fprintf(stderr, "unparsable max-age: %s\n", optarg); + exit(STATE_WARNING); + } + if (verbose >= 2) + printf("* Maximal age of document set to %d seconds\n", maximum_age); + } break; + case 'E': /* show extended perfdata */ + show_extended_perfdata = true; + break; + case 'B': /* print body content after status line */ + show_body = true; + break; + case HTTP_VERSION_OPTION: + curl_http_version = CURL_HTTP_VERSION_NONE; + if (strcmp(optarg, "1.0") == 0) { + curl_http_version = CURL_HTTP_VERSION_1_0; + } else if (strcmp(optarg, "1.1") == 0) { + curl_http_version = CURL_HTTP_VERSION_1_1; + } else if ((strcmp(optarg, "2.0") == 0) || (strcmp(optarg, "2") == 0)) { #if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0) - curl_http_version = CURL_HTTP_VERSION_2_0; + curl_http_version = CURL_HTTP_VERSION_2_0; #else - curl_http_version = CURL_HTTP_VERSION_NONE; + curl_http_version = CURL_HTTP_VERSION_NONE; #endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0) */ - } else { - fprintf (stderr, "unknown http-version parameter: %s\n", optarg); - exit (STATE_WARNING); - } - break; - case AUTOMATIC_DECOMPRESSION: - automatic_decompression = true; - break; - case COOKIE_JAR: - cookie_jar_file = optarg; - break; - case HAPROXY_PROTOCOL: - haproxy_protocol = true; - break; - case '?': - /* print short usage statement if args not parsable */ - usage5 (); - break; - } - } - - c = optind; - - if (server_address == NULL && c < argc) - server_address = strdup (argv[c++]); - - if (host_name == NULL && c < argc) - host_name = strdup (argv[c++]); - - if (server_address == NULL) { - if (host_name == NULL) - usage4 (_("You must specify a server address or host name")); - else - server_address = strdup (host_name); - } - - set_thresholds(&thlds, warning_thresholds, critical_thresholds); - - if (critical_thresholds && thlds->critical->end>(double)socket_timeout) - socket_timeout = (int)thlds->critical->end + 1; - if (verbose >= 2) - printf ("* Socket timeout set to %ld seconds\n", socket_timeout); - - if (http_method == NULL) - http_method = strdup ("GET"); - - if (client_cert && !client_privkey) - usage4 (_("If you use a client certificate you must also specify a private key file")); - - if (virtual_port == 0) - virtual_port = server_port; - else { - if ((use_ssl && server_port == HTTPS_PORT) || (!use_ssl && server_port == HTTP_PORT)) - if(!specify_port) - server_port = virtual_port; - } - - return true; + } else { + fprintf(stderr, "unknown http-version parameter: %s\n", optarg); + exit(STATE_WARNING); + } + break; + case AUTOMATIC_DECOMPRESSION: + automatic_decompression = true; + break; + case COOKIE_JAR: + cookie_jar_file = optarg; + break; + case HAPROXY_PROTOCOL: + haproxy_protocol = true; + break; + case '?': + /* print short usage statement if args not parsable */ + usage5(); + break; + } + } + + c = optind; + + if (server_address == NULL && c < argc) + server_address = strdup(argv[c++]); + + if (host_name == NULL && c < argc) + host_name = strdup(argv[c++]); + + if (server_address == NULL) { + if (host_name == NULL) + usage4(_("You must specify a server address or host name")); + else + server_address = strdup(host_name); + } + + set_thresholds(&thlds, warning_thresholds, critical_thresholds); + + if (critical_thresholds && thlds->critical->end > (double)socket_timeout) + socket_timeout = (int)thlds->critical->end + 1; + if (verbose >= 2) + printf("* Socket timeout set to %ld seconds\n", socket_timeout); + + if (http_method == NULL) + http_method = strdup("GET"); + + if (client_cert && !client_privkey) + usage4(_("If you use a client certificate you must also specify a private key file")); + + if (virtual_port == 0) + virtual_port = server_port; + else { + if ((use_ssl && server_port == HTTPS_PORT) || (!use_ssl && server_port == HTTP_PORT)) + if (!specify_port) + server_port = virtual_port; + } + + return true; } -char *perfd_time (double elapsed_time) -{ - return fperfdata ("time", elapsed_time, "s", - thlds->warning?true:false, thlds->warning?thlds->warning->end:0, - thlds->critical?true:false, thlds->critical?thlds->critical->end:0, - true, 0, true, socket_timeout); +char *perfd_time(double elapsed_time) { + return fperfdata("time", elapsed_time, "s", thlds->warning ? true : false, thlds->warning ? thlds->warning->end : 0, + thlds->critical ? true : false, thlds->critical ? thlds->critical->end : 0, true, 0, true, socket_timeout); } -char *perfd_time_connect (double elapsed_time_connect) -{ - return fperfdata ("time_connect", elapsed_time_connect, "s", false, 0, false, 0, false, 0, true, socket_timeout); +char *perfd_time_connect(double elapsed_time_connect) { + return fperfdata("time_connect", elapsed_time_connect, "s", false, 0, false, 0, false, 0, true, socket_timeout); } -char *perfd_time_ssl (double elapsed_time_ssl) -{ - return fperfdata ("time_ssl", elapsed_time_ssl, "s", false, 0, false, 0, false, 0, true, socket_timeout); +char *perfd_time_ssl(double elapsed_time_ssl) { + return fperfdata("time_ssl", elapsed_time_ssl, "s", false, 0, false, 0, false, 0, true, socket_timeout); } -char *perfd_time_headers (double elapsed_time_headers) -{ - return fperfdata ("time_headers", elapsed_time_headers, "s", false, 0, false, 0, false, 0, true, socket_timeout); +char *perfd_time_headers(double elapsed_time_headers) { + return fperfdata("time_headers", elapsed_time_headers, "s", false, 0, false, 0, false, 0, true, socket_timeout); } -char *perfd_time_firstbyte (double elapsed_time_firstbyte) -{ - return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", false, 0, false, 0, false, 0, true, socket_timeout); +char *perfd_time_firstbyte(double elapsed_time_firstbyte) { + return fperfdata("time_firstbyte", elapsed_time_firstbyte, "s", false, 0, false, 0, false, 0, true, socket_timeout); } -char *perfd_time_transfer (double elapsed_time_transfer) -{ - return fperfdata ("time_transfer", elapsed_time_transfer, "s", false, 0, false, 0, false, 0, true, socket_timeout); +char *perfd_time_transfer(double elapsed_time_transfer) { + return fperfdata("time_transfer", elapsed_time_transfer, "s", false, 0, false, 0, false, 0, true, socket_timeout); } -char *perfd_size (int page_len) -{ - return perfdata ("size", page_len, "B", - (min_page_len>0?true:false), min_page_len, - (min_page_len>0?true:false), 0, - true, 0, false, 0); +char *perfd_size(int page_len) { + return perfdata("size", page_len, "B", (min_page_len > 0 ? true : false), min_page_len, (min_page_len > 0 ? true : false), 0, true, 0, + false, 0); } -void -print_help (void) -{ - print_revision (progname, NP_VERSION); +void print_help(void) { + print_revision(progname, NP_VERSION); - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); - printf ("%s\n", _("This plugin tests the HTTP service on the specified host. It can test")); - printf ("%s\n", _("normal (http) and secure (https) servers, follow redirects, search for")); - printf ("%s\n", _("strings and regular expressions, check connection times, and report on")); - printf ("%s\n", _("certificate expiration times.")); - printf ("\n"); - printf ("%s\n", _("It makes use of libcurl to do so. It tries to be as compatible to check_http")); - printf ("%s\n", _("as possible.")); + printf("%s\n", _("This plugin tests the HTTP service on the specified host. It can test")); + printf("%s\n", _("normal (http) and secure (https) servers, follow redirects, search for")); + printf("%s\n", _("strings and regular expressions, check connection times, and report on")); + printf("%s\n", _("certificate expiration times.")); + printf("\n"); + printf("%s\n", _("It makes use of libcurl to do so. It tries to be as compatible to check_http")); + printf("%s\n", _("as possible.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (_("NOTE: One or both of -H and -I must be specified")); + printf(_("NOTE: One or both of -H and -I must be specified")); - printf ("\n"); + printf("\n"); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (" %s\n", "-H, --hostname=ADDRESS"); - printf (" %s\n", _("Host name argument for servers using host headers (virtual host)")); - printf (" %s\n", _("Append a port to include it in the header (eg: example.com:5000)")); - printf (" %s\n", "-I, --IP-address=ADDRESS"); - printf (" %s\n", _("IP address or name (use numeric address if possible to bypass DNS lookup).")); - printf (" %s\n", "-p, --port=INTEGER"); - printf (" %s", _("Port number (default: ")); - printf ("%d)\n", HTTP_PORT); + printf(" %s\n", "-H, --hostname=ADDRESS"); + printf(" %s\n", _("Host name argument for servers using host headers (virtual host)")); + printf(" %s\n", _("Append a port to include it in the header (eg: example.com:5000)")); + printf(" %s\n", "-I, --IP-address=ADDRESS"); + printf(" %s\n", _("IP address or name (use numeric address if possible to bypass DNS lookup).")); + printf(" %s\n", "-p, --port=INTEGER"); + printf(" %s", _("Port number (default: ")); + printf("%d)\n", HTTP_PORT); - printf (UT_IPv46); + printf(UT_IPv46); #ifdef LIBCURL_FEATURE_SSL - printf (" %s\n", "-S, --ssl=VERSION[+]"); - printf (" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is optional, and prevents")); - printf (" %s\n", _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,")); - printf (" %s\n", _("1.2 = TLSv1.2, 1.3 = TLSv1.3). With a '+' suffix, newer versions are also accepted.")); - printf (" %s\n", _("Note: SSLv2 and SSLv3 are deprecated and are usually disabled in libcurl")); - printf (" %s\n", "--sni"); - printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); -#if LIBCURL_VERSION_NUM >= 0x071801 - printf (" %s\n", _("Note: --sni is the default in libcurl as SSLv2 and SSLV3 are deprecated and")); - printf (" %s\n", _(" SNI only really works since TLSv1.0")); -#else - printf (" %s\n", _("Note: SNI is not supported in libcurl before 7.18.1")); -#endif - printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); - printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443.")); - printf (" %s\n", _("A STATE_WARNING is returned if the certificate has a validity less than the")); - printf (" %s\n", _("first agument's value. If there is a second argument and the certificate's")); - printf (" %s\n", _("validity is less than its value, a STATE_CRITICAL is returned.")); - printf (" %s\n", _("(When this option is used the URL is not checked by default. You can use")); - printf (" %s\n", _(" --continue-after-certificate to override this behavior)")); - printf (" %s\n", "--continue-after-certificate"); - printf (" %s\n", _("Allows the HTTP check to continue after performing the certificate check.")); - printf (" %s\n", _("Does nothing unless -C is used.")); - printf (" %s\n", "-J, --client-cert=FILE"); - printf (" %s\n", _("Name of file that contains the client certificate (PEM format)")); - printf (" %s\n", _("to be used in establishing the SSL session")); - printf (" %s\n", "-K, --private-key=FILE"); - printf (" %s\n", _("Name of file containing the private key (PEM format)")); - printf (" %s\n", _("matching the client certificate")); - printf (" %s\n", "--ca-cert=FILE"); - printf (" %s\n", _("CA certificate file to verify peer against")); - printf (" %s\n", "-D, --verify-cert"); - printf (" %s\n", _("Verify the peer's SSL certificate and hostname")); + printf(" %s\n", "-S, --ssl=VERSION[+]"); + printf(" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is optional, and prevents")); + printf(" %s\n", _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,")); + printf(" %s\n", _("1.2 = TLSv1.2, 1.3 = TLSv1.3). With a '+' suffix, newer versions are also accepted.")); + printf(" %s\n", _("Note: SSLv2 and SSLv3 are deprecated and are usually disabled in libcurl")); + printf(" %s\n", "--sni"); + printf(" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); +# if LIBCURL_VERSION_NUM >= 0x071801 + printf(" %s\n", _("Note: --sni is the default in libcurl as SSLv2 and SSLV3 are deprecated and")); + printf(" %s\n", _(" SNI only really works since TLSv1.0")); +# else + printf(" %s\n", _("Note: SNI is not supported in libcurl before 7.18.1")); +# endif + printf(" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); + printf(" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443.")); + printf(" %s\n", _("A STATE_WARNING is returned if the certificate has a validity less than the")); + printf(" %s\n", _("first agument's value. If there is a second argument and the certificate's")); + printf(" %s\n", _("validity is less than its value, a STATE_CRITICAL is returned.")); + printf(" %s\n", _("(When this option is used the URL is not checked by default. You can use")); + printf(" %s\n", _(" --continue-after-certificate to override this behavior)")); + printf(" %s\n", "--continue-after-certificate"); + printf(" %s\n", _("Allows the HTTP check to continue after performing the certificate check.")); + printf(" %s\n", _("Does nothing unless -C is used.")); + printf(" %s\n", "-J, --client-cert=FILE"); + printf(" %s\n", _("Name of file that contains the client certificate (PEM format)")); + printf(" %s\n", _("to be used in establishing the SSL session")); + printf(" %s\n", "-K, --private-key=FILE"); + printf(" %s\n", _("Name of file containing the private key (PEM format)")); + printf(" %s\n", _("matching the client certificate")); + printf(" %s\n", "--ca-cert=FILE"); + printf(" %s\n", _("CA certificate file to verify peer against")); + printf(" %s\n", "-D, --verify-cert"); + printf(" %s\n", _("Verify the peer's SSL certificate and hostname")); #endif - printf (" %s\n", "-e, --expect=STRING"); - printf (" %s\n", _("Comma-delimited list of strings, at least one of them is expected in")); - printf (" %s", _("the first (status) line of the server response (default: ")); - printf ("%s)\n", HTTP_EXPECT); - printf (" %s\n", _("If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)")); - printf (" %s\n", "-d, --header-string=STRING"); - printf (" %s\n", _("String to expect in the response headers")); - printf (" %s\n", "-s, --string=STRING"); - printf (" %s\n", _("String to expect in the content")); - printf (" %s\n", "-u, --url=PATH"); - printf (" %s\n", _("URL to GET or POST (default: /)")); - printf (" %s\n", "-P, --post=STRING"); - printf (" %s\n", _("URL decoded http POST data")); - printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)"); - printf (" %s\n", _("Set HTTP method.")); - printf (" %s\n", "-N, --no-body"); - printf (" %s\n", _("Don't wait for document body: stop reading after headers.")); - printf (" %s\n", _("(Note that this still does an HTTP GET or POST, not a HEAD.)")); - printf (" %s\n", "-M, --max-age=SECONDS"); - printf (" %s\n", _("Warn if document is more than SECONDS old. the number can also be of")); - printf (" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or \"10d\" for days.")); - printf (" %s\n", "-T, --content-type=STRING"); - printf (" %s\n", _("specify Content-Type header media type when POSTing\n")); - printf (" %s\n", "-l, --linespan"); - printf (" %s\n", _("Allow regex to span newlines (must precede -r or -R)")); - printf (" %s\n", "-r, --regex, --ereg=STRING"); - printf (" %s\n", _("Search page for regex STRING")); - printf (" %s\n", "-R, --eregi=STRING"); - printf (" %s\n", _("Search page for case-insensitive regex STRING")); - printf (" %s\n", "--invert-regex"); - printf (" %s\n", _("Return STATE if found, OK if not (STATE is CRITICAL, per default)")); - printf (" %s\n", _("can be changed with --state--regex)")); - printf (" %s\n", "--state-regex=STATE"); - printf (" %s\n", _("Return STATE if regex is found, OK if not. STATE can be one of \"critical\",\"warning\"")); - printf (" %s\n", "-a, --authorization=AUTH_PAIR"); - printf (" %s\n", _("Username:password on sites with basic authentication")); - printf (" %s\n", "-b, --proxy-authorization=AUTH_PAIR"); - printf (" %s\n", _("Username:password on proxy-servers with basic authentication")); - printf (" %s\n", "-A, --useragent=STRING"); - printf (" %s\n", _("String to be sent in http header as \"User Agent\"")); - printf (" %s\n", "-k, --header=STRING"); - printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers")); - printf (" %s\n", "-E, --extended-perfdata"); - printf (" %s\n", _("Print additional performance data")); - printf (" %s\n", "-B, --show-body"); - printf (" %s\n", _("Print body content below status line")); - printf (" %s\n", "-L, --link"); - printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)")); - printf (" %s\n", "-f, --onredirect="); - printf (" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the")); - printf (" %s\n", _("specified IP address. stickyport also ensures port stays the same.")); - printf (" %s\n", _("follow uses the old redirection algorithm of check_http.")); - printf (" %s\n", _("curl uses CURL_FOLLOWLOCATION built into libcurl.")); - printf (" %s\n", "--max-redirs=INTEGER"); - printf (" %s", _("Maximal number of redirects (default: ")); - printf ("%d)\n", DEFAULT_MAX_REDIRS); - printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); - printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)")); - printf ("\n"); - printf (" %s\n", "--http-version=VERSION"); - printf (" %s\n", _("Connect via specific HTTP protocol.")); - printf (" %s\n", _("1.0 = HTTP/1.0, 1.1 = HTTP/1.1, 2.0 = HTTP/2 (HTTP/2 will fail without -S)")); - printf (" %s\n", "--enable-automatic-decompression"); - printf (" %s\n", _("Enable automatic decompression of body (CURLOPT_ACCEPT_ENCODING).")); - printf(" %s\n", "--haproxy-protocol"); - printf(" %s\n", _("Send HAProxy proxy protocol v1 header (CURLOPT_HAPROXYPROTOCOL).")); - printf (" %s\n", "--cookie-jar=FILE"); - printf (" %s\n", _("Store cookies in the cookie jar and send them out when requested.")); - printf ("\n"); - - printf (UT_WARN_CRIT); - - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - - printf (UT_VERBOSE); - - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("This plugin will attempt to open an HTTP connection with the host.")); - printf (" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL")); - printf (" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect response")); - printf (" %s\n", _("messages from the host result in STATE_WARNING return values. If you are")); - printf (" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN")); - printf (" %s\n", _("(fully qualified domain name) as the [host_name] argument.")); + printf(" %s\n", "-e, --expect=STRING"); + printf(" %s\n", _("Comma-delimited list of strings, at least one of them is expected in")); + printf(" %s", _("the first (status) line of the server response (default: ")); + printf("%s)\n", HTTP_EXPECT); + printf(" %s\n", _("If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)")); + printf(" %s\n", "-d, --header-string=STRING"); + printf(" %s\n", _("String to expect in the response headers")); + printf(" %s\n", "-s, --string=STRING"); + printf(" %s\n", _("String to expect in the content")); + printf(" %s\n", "-u, --url=PATH"); + printf(" %s\n", _("URL to GET or POST (default: /)")); + printf(" %s\n", "-P, --post=STRING"); + printf(" %s\n", _("URL decoded http POST data")); + printf(" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)"); + printf(" %s\n", _("Set HTTP method.")); + printf(" %s\n", "-N, --no-body"); + printf(" %s\n", _("Don't wait for document body: stop reading after headers.")); + printf(" %s\n", _("(Note that this still does an HTTP GET or POST, not a HEAD.)")); + printf(" %s\n", "-M, --max-age=SECONDS"); + printf(" %s\n", _("Warn if document is more than SECONDS old. the number can also be of")); + printf(" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or \"10d\" for days.")); + printf(" %s\n", "-T, --content-type=STRING"); + printf(" %s\n", _("specify Content-Type header media type when POSTing\n")); + printf(" %s\n", "-l, --linespan"); + printf(" %s\n", _("Allow regex to span newlines (must precede -r or -R)")); + printf(" %s\n", "-r, --regex, --ereg=STRING"); + printf(" %s\n", _("Search page for regex STRING")); + printf(" %s\n", "-R, --eregi=STRING"); + printf(" %s\n", _("Search page for case-insensitive regex STRING")); + printf(" %s\n", "--invert-regex"); + printf(" %s\n", _("Return STATE if found, OK if not (STATE is CRITICAL, per default)")); + printf(" %s\n", _("can be changed with --state--regex)")); + printf(" %s\n", "--state-regex=STATE"); + printf(" %s\n", _("Return STATE if regex is found, OK if not. STATE can be one of \"critical\",\"warning\"")); + printf(" %s\n", "-a, --authorization=AUTH_PAIR"); + printf(" %s\n", _("Username:password on sites with basic authentication")); + printf(" %s\n", "-b, --proxy-authorization=AUTH_PAIR"); + printf(" %s\n", _("Username:password on proxy-servers with basic authentication")); + printf(" %s\n", "-A, --useragent=STRING"); + printf(" %s\n", _("String to be sent in http header as \"User Agent\"")); + printf(" %s\n", "-k, --header=STRING"); + printf(" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers")); + printf(" %s\n", "-E, --extended-perfdata"); + printf(" %s\n", _("Print additional performance data")); + printf(" %s\n", "-B, --show-body"); + printf(" %s\n", _("Print body content below status line")); + printf(" %s\n", "-L, --link"); + printf(" %s\n", _("Wrap output in HTML link (obsoleted by urlize)")); + printf(" %s\n", "-f, --onredirect="); + printf(" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the")); + printf(" %s\n", _("specified IP address. stickyport also ensures port stays the same.")); + printf(" %s\n", _("follow uses the old redirection algorithm of check_http.")); + printf(" %s\n", _("curl uses CURL_FOLLOWLOCATION built into libcurl.")); + printf(" %s\n", "--max-redirs=INTEGER"); + printf(" %s", _("Maximal number of redirects (default: ")); + printf("%d)\n", DEFAULT_MAX_REDIRS); + printf(" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); + printf(" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)")); + printf("\n"); + printf(" %s\n", "--http-version=VERSION"); + printf(" %s\n", _("Connect via specific HTTP protocol.")); + printf(" %s\n", _("1.0 = HTTP/1.0, 1.1 = HTTP/1.1, 2.0 = HTTP/2 (HTTP/2 will fail without -S)")); + printf(" %s\n", "--enable-automatic-decompression"); + printf(" %s\n", _("Enable automatic decompression of body (CURLOPT_ACCEPT_ENCODING).")); + printf(" %s\n", "--haproxy-protocol"); + printf(" %s\n", _("Send HAProxy proxy protocol v1 header (CURLOPT_HAPROXYPROTOCOL).")); + printf(" %s\n", "--cookie-jar=FILE"); + printf(" %s\n", _("Store cookies in the cookie jar and send them out when requested.")); + printf("\n"); + + printf(UT_WARN_CRIT); + + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + + printf(UT_VERBOSE); + + printf("\n"); + printf("%s\n", _("Notes:")); + printf(" %s\n", _("This plugin will attempt to open an HTTP connection with the host.")); + printf(" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL")); + printf(" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect response")); + printf(" %s\n", _("messages from the host result in STATE_WARNING return values. If you are")); + printf(" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN")); + printf(" %s\n", _("(fully qualified domain name) as the [host_name] argument.")); #ifdef LIBCURL_FEATURE_SSL - printf ("\n"); - printf (" %s\n", _("This plugin can also check whether an SSL enabled web server is able to")); - printf (" %s\n", _("serve content (optionally within a specified time) or whether the X509 ")); - printf (" %s\n", _("certificate is still valid for the specified number of days.")); - printf ("\n"); - printf (" %s\n", _("Please note that this plugin does not check if the presented server")); - printf (" %s\n", _("certificate matches the hostname of the server, or if the certificate")); - printf (" %s\n", _("has a valid chain of trust to one of the locally installed CAs.")); - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n\n", "CHECK CONTENT: check_curl -w 5 -c 10 --ssl -H www.verisign.com"); - printf (" %s\n", _("When the 'www.verisign.com' server returns its content within 5 seconds,")); - printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); - printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); - printf (" %s\n", _("a STATE_CRITICAL will be returned.")); - printf ("\n"); - printf (" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 14"); - printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,")); - printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than")); - printf (" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when")); - printf (" %s\n\n", _("the certificate is expired.")); - printf ("\n"); - printf (" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 30,14"); - printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 30 days,")); - printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than")); - printf (" %s\n", _("30 days, but more than 14 days, a STATE_WARNING is returned.")); - printf (" %s\n", _("A STATE_CRITICAL will be returned when certificate expires in less than 14 days")); + printf("\n"); + printf(" %s\n", _("This plugin can also check whether an SSL enabled web server is able to")); + printf(" %s\n", _("serve content (optionally within a specified time) or whether the X509 ")); + printf(" %s\n", _("certificate is still valid for the specified number of days.")); + printf("\n"); + printf(" %s\n", _("Please note that this plugin does not check if the presented server")); + printf(" %s\n", _("certificate matches the hostname of the server, or if the certificate")); + printf(" %s\n", _("has a valid chain of trust to one of the locally installed CAs.")); + printf("\n"); + printf("%s\n", _("Examples:")); + printf(" %s\n\n", "CHECK CONTENT: check_curl -w 5 -c 10 --ssl -H www.verisign.com"); + printf(" %s\n", _("When the 'www.verisign.com' server returns its content within 5 seconds,")); + printf(" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); + printf(" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); + printf(" %s\n", _("a STATE_CRITICAL will be returned.")); + printf("\n"); + printf(" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 14"); + printf(" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,")); + printf(" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than")); + printf(" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when")); + printf(" %s\n\n", _("the certificate is expired.")); + printf("\n"); + printf(" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 30,14"); + printf(" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 30 days,")); + printf(" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than")); + printf(" %s\n", _("30 days, but more than 14 days, a STATE_WARNING is returned.")); + printf(" %s\n", _("A STATE_CRITICAL will be returned when certificate expires in less than 14 days")); #endif - printf ("\n %s\n", "CHECK WEBSERVER CONTENT VIA PROXY:"); - printf (" %s\n", _("It is recommended to use an environment proxy like:")); - printf (" %s\n", _("http_proxy=http://192.168.100.35:3128 ./check_curl -H www.monitoring-plugins.org")); - printf (" %s\n", _("legacy proxy requests in check_http style still work:")); - printf (" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u http://www.monitoring-plugins.org/ -H www.monitoring-plugins.org")); + printf("\n %s\n", "CHECK WEBSERVER CONTENT VIA PROXY:"); + printf(" %s\n", _("It is recommended to use an environment proxy like:")); + printf(" %s\n", _("http_proxy=http://192.168.100.35:3128 ./check_curl -H www.monitoring-plugins.org")); + printf(" %s\n", _("legacy proxy requests in check_http style still work:")); + printf(" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u http://www.monitoring-plugins.org/ -H www.monitoring-plugins.org")); #ifdef LIBCURL_FEATURE_SSL - printf ("\n %s\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: "); - printf (" %s\n", _("It is recommended to use an environment proxy like:")); - printf (" %s\n", _("https_proxy=http://192.168.100.35:3128 ./check_curl -H www.verisign.com -S")); - printf (" %s\n", _("legacy proxy requests in check_http style still work:")); - printf (" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u https://www.verisign.com/ -S -j CONNECT -H www.verisign.com ")); - printf (" %s\n", _("all these options are needed: -I -p -u -S(sl) -j CONNECT -H ")); - printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); - printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); - printf (" %s\n", _("a STATE_CRITICAL will be returned.")); + printf("\n %s\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: "); + printf(" %s\n", _("It is recommended to use an environment proxy like:")); + printf(" %s\n", _("https_proxy=http://192.168.100.35:3128 ./check_curl -H www.verisign.com -S")); + printf(" %s\n", _("legacy proxy requests in check_http style still work:")); + printf(" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u https://www.verisign.com/ -S -j CONNECT -H www.verisign.com ")); + printf(" %s\n", _("all these options are needed: -I -p -u -S(sl) -j CONNECT -H ")); + printf(" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); + printf(" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); + printf(" %s\n", _("a STATE_CRITICAL will be returned.")); #endif - printf (UT_SUPPORT); - + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s -H | -I [-u ] [-p ]\n",progname); - printf (" [-J ] [-K ] [--ca-cert ] [-D]\n"); - printf (" [-w ] [-c ] [-t ] [-L] [-E] [-a auth]\n"); - printf (" [-b proxy_auth] [-f ]\n"); - printf (" [-e ] [-d string] [-s string] [-l] [-r | -R ]\n"); - printf (" [-P string] [-m :] [-4|-6] [-N] [-M ]\n"); - printf (" [-A string] [-k string] [-S ] [--sni] [--haproxy-protocol]\n"); - printf (" [-T ] [-j method]\n"); - printf (" [--http-version=] [--enable-automatic-decompression]\n"); - printf (" [--cookie-jar=\n"); - printf (" %s -H | -I -C [,]\n",progname); - printf (" [-p ] [-t ] [-4|-6] [--sni]\n"); - printf ("\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s -H | -I [-u ] [-p ]\n", progname); + printf(" [-J ] [-K ] [--ca-cert ] [-D]\n"); + printf(" [-w ] [-c ] [-t ] [-L] [-E] [-a auth]\n"); + printf(" [-b proxy_auth] [-f ]\n"); + printf(" [-e ] [-d string] [-s string] [-l] [-r | -R ]\n"); + printf(" [-P string] [-m :] [-4|-6] [-N] [-M ]\n"); + printf(" [-A string] [-k string] [-S ] [--sni] [--haproxy-protocol]\n"); + printf(" [-T ] [-j method]\n"); + printf(" [--http-version=] [--enable-automatic-decompression]\n"); + printf(" [--cookie-jar=\n"); + printf(" %s -H | -I -C [,]\n", progname); + printf(" [-p ] [-t ] [-4|-6] [--sni]\n"); + printf("\n"); #ifdef LIBCURL_FEATURE_SSL - printf ("%s\n", _("In the first form, make an HTTP request.")); - printf ("%s\n\n", _("In the second form, connect to the server and check the TLS certificate.")); + printf("%s\n", _("In the first form, make an HTTP request.")); + printf("%s\n\n", _("In the second form, connect to the server and check the TLS certificate.")); #endif } -void -print_curl_version (void) -{ - printf( "%s\n", curl_version()); -} +void print_curl_version(void) { printf("%s\n", curl_version()); } -int -curlhelp_initwritebuffer (curlhelp_write_curlbuf *buf) -{ - buf->bufsize = DEFAULT_BUFFER_SIZE; - buf->buflen = 0; - buf->buf = (char *)malloc ((size_t)buf->bufsize); - if (buf->buf == NULL) return -1; - return 0; +int curlhelp_initwritebuffer(curlhelp_write_curlbuf *buf) { + buf->bufsize = DEFAULT_BUFFER_SIZE; + buf->buflen = 0; + buf->buf = (char *)malloc((size_t)buf->bufsize); + if (buf->buf == NULL) + return -1; + return 0; } -size_t curlhelp_buffer_write_callback (void *buffer, size_t size, size_t nmemb, void *stream) -{ - curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream; +size_t curlhelp_buffer_write_callback(void *buffer, size_t size, size_t nmemb, void *stream) { + curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream; - while (buf->bufsize < buf->buflen + size * nmemb + 1) { - buf->bufsize = buf->bufsize * 2; - buf->buf = (char *)realloc (buf->buf, buf->bufsize); - if (buf->buf == NULL) { - fprintf(stderr, "malloc failed (%d) %s\n", errno, strerror(errno)); - return -1; - } - } + while (buf->bufsize < buf->buflen + size * nmemb + 1) { + buf->bufsize = buf->bufsize * 2; + buf->buf = (char *)realloc(buf->buf, buf->bufsize); + if (buf->buf == NULL) { + fprintf(stderr, "malloc failed (%d) %s\n", errno, strerror(errno)); + return -1; + } + } - memcpy (buf->buf + buf->buflen, buffer, size * nmemb); - buf->buflen += size * nmemb; - buf->buf[buf->buflen] = '\0'; + memcpy(buf->buf + buf->buflen, buffer, size * nmemb); + buf->buflen += size * nmemb; + buf->buf[buf->buflen] = '\0'; - return (int)(size * nmemb); + return (int)(size * nmemb); } -size_t curlhelp_buffer_read_callback(void *buffer, size_t size, size_t nmemb, void *stream) -{ - curlhelp_read_curlbuf *buf = (curlhelp_read_curlbuf *)stream; +size_t curlhelp_buffer_read_callback(void *buffer, size_t size, size_t nmemb, void *stream) { + curlhelp_read_curlbuf *buf = (curlhelp_read_curlbuf *)stream; - size_t n = min (nmemb * size, buf->buflen - buf->pos); + size_t n = min(nmemb * size, buf->buflen - buf->pos); - memcpy (buffer, buf->buf + buf->pos, n); - buf->pos += n; + memcpy(buffer, buf->buf + buf->pos, n); + buf->pos += n; - return (int)n; + return (int)n; } -void -curlhelp_freewritebuffer (curlhelp_write_curlbuf *buf) -{ - free (buf->buf); - buf->buf = NULL; +void curlhelp_freewritebuffer(curlhelp_write_curlbuf *buf) { + free(buf->buf); + buf->buf = NULL; } -int -curlhelp_initreadbuffer (curlhelp_read_curlbuf *buf, const char *data, size_t datalen) -{ - buf->buflen = datalen; - buf->buf = (char *)malloc ((size_t)buf->buflen); - if (buf->buf == NULL) return -1; - memcpy (buf->buf, data, datalen); - buf->pos = 0; - return 0; +int curlhelp_initreadbuffer(curlhelp_read_curlbuf *buf, const char *data, size_t datalen) { + buf->buflen = datalen; + buf->buf = (char *)malloc((size_t)buf->buflen); + if (buf->buf == NULL) + return -1; + memcpy(buf->buf, data, datalen); + buf->pos = 0; + return 0; } -void -curlhelp_freereadbuffer (curlhelp_read_curlbuf *buf) -{ - free (buf->buf); - buf->buf = NULL; +void curlhelp_freereadbuffer(curlhelp_read_curlbuf *buf) { + free(buf->buf); + buf->buf = NULL; } /* TODO: where to put this, it's actually part of sstrings2 (logically)? */ -const char* -strrstr2(const char *haystack, const char *needle) -{ - int counter; - size_t len; - const char *prev_pos; - const char *pos; - - if (haystack == NULL || needle == NULL) - return NULL; - - if (haystack[0] == '\0' || needle[0] == '\0') - return NULL; - - counter = 0; - prev_pos = NULL; - pos = haystack; - len = strlen (needle); - for (;;) { - pos = strstr (pos, needle); - if (pos == NULL) { - if (counter == 0) - return NULL; - else - return prev_pos; - } - counter++; - prev_pos = pos; - pos += len; - if (*pos == '\0') return prev_pos; - } +const char *strrstr2(const char *haystack, const char *needle) { + int counter; + size_t len; + const char *prev_pos; + const char *pos; + + if (haystack == NULL || needle == NULL) + return NULL; + + if (haystack[0] == '\0' || needle[0] == '\0') + return NULL; + + counter = 0; + prev_pos = NULL; + pos = haystack; + len = strlen(needle); + for (;;) { + pos = strstr(pos, needle); + if (pos == NULL) { + if (counter == 0) + return NULL; + else + return prev_pos; + } + counter++; + prev_pos = pos; + pos += len; + if (*pos == '\0') + return prev_pos; + } } -int -curlhelp_parse_statusline (const char *buf, curlhelp_statusline *status_line) -{ - char *first_line_end; - char *p; - size_t first_line_len; - char *pp; - const char *start; - char *first_line_buf; - - /* find last start of a new header */ - start = strrstr2 (buf, "\r\nHTTP/"); - if (start != NULL) { - start += 2; - buf = start; - } - - first_line_end = strstr(buf, "\r\n"); - if (first_line_end == NULL) return -1; - - first_line_len = (size_t)(first_line_end - buf); - status_line->first_line = (char *)malloc (first_line_len + 1); - if (status_line->first_line == NULL) return -1; - memcpy (status_line->first_line, buf, first_line_len); - status_line->first_line[first_line_len] = '\0'; - first_line_buf = strdup( status_line->first_line ); - - /* protocol and version: "HTTP/x.x" SP or "HTTP/2" SP */ - - p = strtok(first_line_buf, "/"); - if( p == NULL ) { free( first_line_buf ); return -1; } - if( strcmp( p, "HTTP" ) != 0 ) { free( first_line_buf ); return -1; } - - p = strtok( NULL, " " ); - if( p == NULL ) { free( first_line_buf ); return -1; } - if( strchr( p, '.' ) != NULL ) { - - /* HTTP 1.x case */ - strtok( p, "." ); - status_line->http_major = (int)strtol( p, &pp, 10 ); - if( *pp != '\0' ) { free( first_line_buf ); return -1; } - strtok( NULL, " " ); - status_line->http_minor = (int)strtol( p, &pp, 10 ); - if( *pp != '\0' ) { free( first_line_buf ); return -1; } - p += 4; /* 1.x SP */ - } else { - /* HTTP 2 case */ - status_line->http_major = (int)strtol( p, &pp, 10 ); - status_line->http_minor = 0; - p += 2; /* 2 SP */ - } - - /* status code: "404" or "404.1", then SP */ - - p = strtok( p, " " ); - if( p == NULL ) { free( first_line_buf ); return -1; } - if( strchr( p, '.' ) != NULL ) { - char *ppp; - ppp = strtok( p, "." ); - status_line->http_code = (int)strtol( ppp, &pp, 10 ); - if( *pp != '\0' ) { free( first_line_buf ); return -1; } - ppp = strtok( NULL, "" ); - status_line->http_subcode = (int)strtol( ppp, &pp, 10 ); - if( *pp != '\0' ) { free( first_line_buf ); return -1; } - p += 6; /* 400.1 SP */ - } else { - status_line->http_code = (int)strtol( p, &pp, 10 ); - status_line->http_subcode = -1; - if( *pp != '\0' ) { free( first_line_buf ); return -1; } - p += 4; /* 400 SP */ - } - - /* Human readable message: "Not Found" CRLF */ - - p = strtok( p, "" ); - if( p == NULL ) { status_line->msg = ""; return 0; } - status_line->msg = status_line->first_line + ( p - first_line_buf ); - free( first_line_buf ); - - return 0; -} +int curlhelp_parse_statusline(const char *buf, curlhelp_statusline *status_line) { + char *first_line_end; + char *p; + size_t first_line_len; + char *pp; + const char *start; + char *first_line_buf; + + /* find last start of a new header */ + start = strrstr2(buf, "\r\nHTTP/"); + if (start != NULL) { + start += 2; + buf = start; + } + + first_line_end = strstr(buf, "\r\n"); + if (first_line_end == NULL) + return -1; + + first_line_len = (size_t)(first_line_end - buf); + status_line->first_line = (char *)malloc(first_line_len + 1); + if (status_line->first_line == NULL) + return -1; + memcpy(status_line->first_line, buf, first_line_len); + status_line->first_line[first_line_len] = '\0'; + first_line_buf = strdup(status_line->first_line); + + /* protocol and version: "HTTP/x.x" SP or "HTTP/2" SP */ + + p = strtok(first_line_buf, "/"); + if (p == NULL) { + free(first_line_buf); + return -1; + } + if (strcmp(p, "HTTP") != 0) { + free(first_line_buf); + return -1; + } + + p = strtok(NULL, " "); + if (p == NULL) { + free(first_line_buf); + return -1; + } + if (strchr(p, '.') != NULL) { + + /* HTTP 1.x case */ + strtok(p, "."); + status_line->http_major = (int)strtol(p, &pp, 10); + if (*pp != '\0') { + free(first_line_buf); + return -1; + } + strtok(NULL, " "); + status_line->http_minor = (int)strtol(p, &pp, 10); + if (*pp != '\0') { + free(first_line_buf); + return -1; + } + p += 4; /* 1.x SP */ + } else { + /* HTTP 2 case */ + status_line->http_major = (int)strtol(p, &pp, 10); + status_line->http_minor = 0; + p += 2; /* 2 SP */ + } -void -curlhelp_free_statusline (curlhelp_statusline *status_line) -{ - free (status_line->first_line); + /* status code: "404" or "404.1", then SP */ + + p = strtok(p, " "); + if (p == NULL) { + free(first_line_buf); + return -1; + } + if (strchr(p, '.') != NULL) { + char *ppp; + ppp = strtok(p, "."); + status_line->http_code = (int)strtol(ppp, &pp, 10); + if (*pp != '\0') { + free(first_line_buf); + return -1; + } + ppp = strtok(NULL, ""); + status_line->http_subcode = (int)strtol(ppp, &pp, 10); + if (*pp != '\0') { + free(first_line_buf); + return -1; + } + p += 6; /* 400.1 SP */ + } else { + status_line->http_code = (int)strtol(p, &pp, 10); + status_line->http_subcode = -1; + if (*pp != '\0') { + free(first_line_buf); + return -1; + } + p += 4; /* 400 SP */ + } + + /* Human readable message: "Not Found" CRLF */ + + p = strtok(p, ""); + if (p == NULL) { + status_line->msg = ""; + return 0; + } + status_line->msg = status_line->first_line + (p - first_line_buf); + free(first_line_buf); + + return 0; } -void -remove_newlines (char *s) -{ - char *p; +void curlhelp_free_statusline(curlhelp_statusline *status_line) { free(status_line->first_line); } - for (p = s; *p != '\0'; p++) - if (*p == '\r' || *p == '\n') - *p = ' '; +void remove_newlines(char *s) { + char *p; + + for (p = s; *p != '\0'; p++) + if (*p == '\r' || *p == '\n') + *p = ' '; } -char * -get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header) -{ - for(size_t i = 0; i < nof_headers; i++ ) { - if(headers[i].name != NULL && strncasecmp( header, headers[i].name, max( headers[i].name_len, 4 ) ) == 0 ) { - return strndup( headers[i].value, headers[i].value_len ); - } - } - return NULL; +char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header) { + for (size_t i = 0; i < nof_headers; i++) { + if (headers[i].name != NULL && strncasecmp(header, headers[i].name, max(headers[i].name_len, 4)) == 0) { + return strndup(headers[i].value, headers[i].value_len); + } + } + return NULL; } -int -check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFAULT_BUFFER_SIZE]) -{ - char *server_date = NULL; - char *document_date = NULL; - int date_result = STATE_OK; - curlhelp_statusline status_line; - struct phr_header headers[255]; - size_t nof_headers = 255; - size_t msglen; - - int res = phr_parse_response (header_buf->buf, header_buf->buflen, - &status_line.http_major, &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, - headers, &nof_headers, 0); +int check_document_dates(const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFAULT_BUFFER_SIZE]) { + char *server_date = NULL; + char *document_date = NULL; + int date_result = STATE_OK; + curlhelp_statusline status_line; + struct phr_header headers[255]; + size_t nof_headers = 255; + size_t msglen; + + int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major, &status_line.http_minor, + &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0); if (res == -1) { - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); } - server_date = get_header_value (headers, nof_headers, "date"); - document_date = get_header_value (headers, nof_headers, "last-modified"); + server_date = get_header_value(headers, nof_headers, "date"); + document_date = get_header_value(headers, nof_headers, "last-modified"); if (!server_date || !*server_date) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sServer date unknown, "), *msg); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sServer date unknown, "), *msg); strcpy(*msg, tmp); date_result = max_state_alt(STATE_UNKNOWN, date_result); @@ -2457,34 +2358,34 @@ check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFA } else if (!document_date || !*document_date) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sDocument modification date unknown, "), *msg); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sDocument modification date unknown, "), *msg); strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); - } else { - time_t srv_data = curl_getdate (server_date, NULL); - time_t doc_data = curl_getdate (document_date, NULL); - if (verbose >= 2) - printf ("* server date: '%s' (%d), doc_date: '%s' (%d)\n", server_date, (int)srv_data, document_date, (int)doc_data); + } else { + time_t srv_data = curl_getdate(server_date, NULL); + time_t doc_data = curl_getdate(document_date, NULL); + if (verbose >= 2) + printf("* server date: '%s' (%d), doc_date: '%s' (%d)\n", server_date, (int)srv_data, document_date, (int)doc_data); if (srv_data <= 0) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sServer date \"%100s\" unparsable, "), *msg, server_date); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sServer date \"%100s\" unparsable, "), *msg, server_date); strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); } else if (doc_data <= 0) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date); strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); } else if (doc_data > srv_data + 30) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data); strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); @@ -2493,14 +2394,14 @@ check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFA if (n > (60 * 60 * 24 * 2)) { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24)); - strcpy(*msg, tmp); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sLast modified %.1f days ago, "), *msg, ((float)n) / (60 * 60 * 24)); + strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); } else { char tmp[DEFAULT_BUFFER_SIZE]; - snprintf (tmp, DEFAULT_BUFFER_SIZE, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60); + snprintf(tmp, DEFAULT_BUFFER_SIZE, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60); strcpy(*msg, tmp); date_result = max_state_alt(STATE_CRITICAL, date_result); @@ -2508,132 +2409,128 @@ check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFA } } - if (server_date) free (server_date); - if (document_date) free (document_date); + if (server_date) + free(server_date); + if (document_date) + free(document_date); - return date_result; + return date_result; } +int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf) { + size_t content_length = 0; + struct phr_header headers[255]; + size_t nof_headers = 255; + size_t msglen; + char *content_length_s = NULL; + curlhelp_statusline status_line; -int -get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_write_curlbuf* body_buf) -{ - size_t content_length = 0; - struct phr_header headers[255]; - size_t nof_headers = 255; - size_t msglen; - char *content_length_s = NULL; - curlhelp_statusline status_line; - - int res = phr_parse_response (header_buf->buf, header_buf->buflen, - &status_line.http_major, &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, - headers, &nof_headers, 0); + int res = phr_parse_response(header_buf->buf, header_buf->buflen, &status_line.http_major, &status_line.http_minor, + &status_line.http_code, &status_line.msg, &msglen, headers, &nof_headers, 0); if (res == -1) { - die (STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); + die(STATE_UNKNOWN, _("HTTP UNKNOWN - Failed to parse Response\n")); } - content_length_s = get_header_value (headers, nof_headers, "content-length"); - if (!content_length_s) { - return header_buf->buflen + body_buf->buflen; - } - content_length_s += strspn (content_length_s, " \t"); - content_length = atoi (content_length_s); - if (content_length != body_buf->buflen) { - /* TODO: should we warn if the actual and the reported body length don't match? */ - } + content_length_s = get_header_value(headers, nof_headers, "content-length"); + if (!content_length_s) { + return header_buf->buflen + body_buf->buflen; + } + content_length_s += strspn(content_length_s, " \t"); + content_length = atoi(content_length_s); + if (content_length != body_buf->buflen) { + /* TODO: should we warn if the actual and the reported body length don't match? */ + } - if (content_length_s) free (content_length_s); + if (content_length_s) + free(content_length_s); - return header_buf->buflen + body_buf->buflen; + return header_buf->buflen + body_buf->buflen; } /* TODO: is there a better way in libcurl to check for the SSL library? */ -curlhelp_ssl_library -curlhelp_get_ssl_library () -{ - curl_version_info_data* version_data; - char *ssl_version; - char *library; - curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; - - version_data = curl_version_info (CURLVERSION_NOW); - if (version_data == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN; - - ssl_version = strdup (version_data->ssl_version); - if (ssl_version == NULL ) return CURLHELP_SSL_LIBRARY_UNKNOWN; - - library = strtok (ssl_version, "/"); - if (library == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN; - - if (strcmp (library, "OpenSSL") == 0) - ssl_library = CURLHELP_SSL_LIBRARY_OPENSSL; - else if (strcmp (library, "LibreSSL") == 0) - ssl_library = CURLHELP_SSL_LIBRARY_LIBRESSL; - else if (strcmp (library, "GnuTLS") == 0) - ssl_library = CURLHELP_SSL_LIBRARY_GNUTLS; - else if (strcmp (library, "NSS") == 0) - ssl_library = CURLHELP_SSL_LIBRARY_NSS; - - if (verbose >= 2) - printf ("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library, ssl_library); - - free (ssl_version); - - return ssl_library; +curlhelp_ssl_library curlhelp_get_ssl_library() { + curl_version_info_data *version_data; + char *ssl_version; + char *library; + curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; + + version_data = curl_version_info(CURLVERSION_NOW); + if (version_data == NULL) + return CURLHELP_SSL_LIBRARY_UNKNOWN; + + ssl_version = strdup(version_data->ssl_version); + if (ssl_version == NULL) + return CURLHELP_SSL_LIBRARY_UNKNOWN; + + library = strtok(ssl_version, "/"); + if (library == NULL) + return CURLHELP_SSL_LIBRARY_UNKNOWN; + + if (strcmp(library, "OpenSSL") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_OPENSSL; + else if (strcmp(library, "LibreSSL") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_LIBRESSL; + else if (strcmp(library, "GnuTLS") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_GNUTLS; + else if (strcmp(library, "NSS") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_NSS; + + if (verbose >= 2) + printf("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library, ssl_library); + + free(ssl_version); + + return ssl_library; } -const char* -curlhelp_get_ssl_library_string (curlhelp_ssl_library ssl_library) -{ - switch (ssl_library) { - case CURLHELP_SSL_LIBRARY_OPENSSL: - return "OpenSSL"; - case CURLHELP_SSL_LIBRARY_LIBRESSL: - return "LibreSSL"; - case CURLHELP_SSL_LIBRARY_GNUTLS: - return "GnuTLS"; - case CURLHELP_SSL_LIBRARY_NSS: - return "NSS"; - case CURLHELP_SSL_LIBRARY_UNKNOWN: - default: - return "unknown"; - } +const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library ssl_library) { + switch (ssl_library) { + case CURLHELP_SSL_LIBRARY_OPENSSL: + return "OpenSSL"; + case CURLHELP_SSL_LIBRARY_LIBRESSL: + return "LibreSSL"; + case CURLHELP_SSL_LIBRARY_GNUTLS: + return "GnuTLS"; + case CURLHELP_SSL_LIBRARY_NSS: + return "NSS"; + case CURLHELP_SSL_LIBRARY_UNKNOWN: + default: + return "unknown"; + } } #ifdef LIBCURL_FEATURE_SSL -#ifndef USE_OPENSSL -time_t -parse_cert_date (const char *s) -{ - struct tm tm; - time_t date; - char *res; - - if (!s) return -1; - - /* Jan 17 14:25:12 2020 GMT */ - res = strptime (s, "%Y-%m-%d %H:%M:%S GMT", &tm); - /* Sep 11 12:00:00 2020 GMT */ - if (res == NULL) strptime (s, "%Y %m %d %H:%M:%S GMT", &tm); - date = mktime (&tm); - - return date; +# ifndef USE_OPENSSL +time_t parse_cert_date(const char *s) { + struct tm tm; + time_t date; + char *res; + + if (!s) + return -1; + + /* Jan 17 14:25:12 2020 GMT */ + res = strptime(s, "%Y-%m-%d %H:%M:%S GMT", &tm); + /* Sep 11 12:00:00 2020 GMT */ + if (res == NULL) + strptime(s, "%Y %m %d %H:%M:%S GMT", &tm); + date = mktime(&tm); + + return date; } /* TODO: this needs cleanup in the sslutils.c, maybe we the #else case to * OpenSSL could be this function */ -int -net_noopenssl_check_certificate (cert_ptr_union* cert_ptr, int days_till_exp_warn, int days_till_exp_crit) -{ - int i; - struct curl_slist* slist; - int cname_found = 0; - char* start_date_str = NULL; - char* end_date_str = NULL; - time_t start_date; - time_t end_date; +int net_noopenssl_check_certificate(cert_ptr_union *cert_ptr, int days_till_exp_warn, int days_till_exp_crit) { + int i; + struct curl_slist *slist; + int cname_found = 0; + char *start_date_str = NULL; + char *end_date_str = NULL; + time_t start_date; + time_t end_date; char *tz; float time_left; int days_left; @@ -2641,66 +2538,64 @@ net_noopenssl_check_certificate (cert_ptr_union* cert_ptr, int days_till_exp_war char timestamp[50] = ""; int status = STATE_UNKNOWN; - if (verbose >= 2) - printf ("**** REQUEST CERTIFICATES ****\n"); - - for (i = 0; i < cert_ptr->to_certinfo->num_of_certs; i++) { - for (slist = cert_ptr->to_certinfo->certinfo[i]; slist; slist = slist->next) { - /* find first common name in subject, - * TODO: check alternative subjects for - * TODO: have a decent parser here and not a hack - * multi-host certificate, check wildcards - */ - if (strncasecmp (slist->data, "Subject:", 8) == 0) { - int d = 3; - char* p = strstr (slist->data, "CN="); - if (p == NULL) { - d = 5; - p = strstr (slist->data, "CN = "); - } - if (p != NULL) { - if (strncmp (host_name, p+d, strlen (host_name)) == 0) { - cname_found = 1; - } - } - } else if (strncasecmp (slist->data, "Start Date:", 11) == 0) { - start_date_str = &slist->data[11]; - } else if (strncasecmp (slist->data, "Expire Date:", 12) == 0) { - end_date_str = &slist->data[12]; - } else if (strncasecmp (slist->data, "Cert:", 5) == 0) { - goto HAVE_FIRST_CERT; - } - if (verbose >= 2) - printf ("%d ** %s\n", i, slist->data); - } - } + if (verbose >= 2) + printf("**** REQUEST CERTIFICATES ****\n"); + + for (i = 0; i < cert_ptr->to_certinfo->num_of_certs; i++) { + for (slist = cert_ptr->to_certinfo->certinfo[i]; slist; slist = slist->next) { + /* find first common name in subject, + * TODO: check alternative subjects for + * TODO: have a decent parser here and not a hack + * multi-host certificate, check wildcards + */ + if (strncasecmp(slist->data, "Subject:", 8) == 0) { + int d = 3; + char *p = strstr(slist->data, "CN="); + if (p == NULL) { + d = 5; + p = strstr(slist->data, "CN = "); + } + if (p != NULL) { + if (strncmp(host_name, p + d, strlen(host_name)) == 0) { + cname_found = 1; + } + } + } else if (strncasecmp(slist->data, "Start Date:", 11) == 0) { + start_date_str = &slist->data[11]; + } else if (strncasecmp(slist->data, "Expire Date:", 12) == 0) { + end_date_str = &slist->data[12]; + } else if (strncasecmp(slist->data, "Cert:", 5) == 0) { + goto HAVE_FIRST_CERT; + } + if (verbose >= 2) + printf("%d ** %s\n", i, slist->data); + } + } HAVE_FIRST_CERT: - if (verbose >= 2) - printf ("**** REQUEST CERTIFICATES ****\n"); + if (verbose >= 2) + printf("**** REQUEST CERTIFICATES ****\n"); - if (!cname_found) { - printf("%s\n",_("CRITICAL - Cannot retrieve certificate subject.")); + if (!cname_found) { + printf("%s\n", _("CRITICAL - Cannot retrieve certificate subject.")); return STATE_CRITICAL; - } - - start_date = parse_cert_date (start_date_str); - if (start_date <= 0) { - snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Start Date' in certificate: '%s'"), - start_date_str); - puts (msg); - return STATE_WARNING; - } - - end_date = parse_cert_date (end_date_str); - if (end_date <= 0) { - snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Expire Date' in certificate: '%s'"), - start_date_str); - puts (msg); - return STATE_WARNING; - } - - time_left = difftime (end_date, time(NULL)); + } + + start_date = parse_cert_date(start_date_str); + if (start_date <= 0) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Start Date' in certificate: '%s'"), start_date_str); + puts(msg); + return STATE_WARNING; + } + + end_date = parse_cert_date(end_date_str); + if (end_date <= 0) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Expire Date' in certificate: '%s'"), start_date_str); + puts(msg); + return STATE_WARNING; + } + + time_left = difftime(end_date, time(NULL)); days_left = time_left / 86400; tz = getenv("TZ"); setenv("TZ", "GMT", 1); @@ -2713,30 +2608,31 @@ HAVE_FIRST_CERT: tzset(); if (days_left > 0 && days_left <= days_till_exp_warn) { - printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, days_left, timestamp); + printf(_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", + host_name, days_left, timestamp); if (days_left > days_till_exp_crit) status = STATE_WARNING; else status = STATE_CRITICAL; } else if (days_left == 0 && time_left > 0) { if (time_left >= 3600) - time_remaining = (int) time_left / 3600; + time_remaining = (int)time_left / 3600; else - time_remaining = (int) time_left / 60; + time_remaining = (int)time_left / 60; - printf (_("%s - Certificate '%s' expires in %u %s (%s)\n"), - (days_left>days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name, time_remaining, - time_left >= 3600 ? "hours" : "minutes", timestamp); + printf(_("%s - Certificate '%s' expires in %u %s (%s)\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name, + time_remaining, time_left >= 3600 ? "hours" : "minutes", timestamp); - if ( days_left > days_till_exp_crit) + if (days_left > days_till_exp_crit) status = STATE_WARNING; else status = STATE_CRITICAL; } else if (time_left < 0) { printf(_("CRITICAL - Certificate '%s' expired on %s.\n"), host_name, timestamp); - status=STATE_CRITICAL; + status = STATE_CRITICAL; } else if (days_left == 0) { - printf (_("%s - Certificate '%s' just expired (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, timestamp); + printf(_("%s - Certificate '%s' just expired (%s).\n"), (days_left > days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name, + timestamp); if (days_left > days_till_exp_crit) status = STATE_WARNING; else @@ -2747,5 +2643,5 @@ HAVE_FIRST_CERT: } return status; } -#endif /* USE_OPENSSL */ -#endif /* LIBCURL_FEATURE_SSL */ +# endif /* USE_OPENSSL */ +#endif /* LIBCURL_FEATURE_SSL */ -- cgit v1.2.3-74-g34f1 From 367c4f89c1417aba29d2421e157817994a049f87 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 02:59:49 +0100 Subject: check_curl: Update copyright --- plugins/check_curl.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 8936110f..8277f5e2 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -3,7 +3,7 @@ * Monitoring check_curl plugin * * License: GPL - * Copyright (c) 1999-2019 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -34,7 +34,7 @@ *****************************************************************************/ const char *progname = "check_curl"; -const char *copyright = "2006-2019"; +const char *copyright = "2006-2024"; const char *email = "devel@monitoring-plugins.org"; #include -- cgit v1.2.3-74-g34f1 From 7334812a929768aa310557ae823b91df79b32f51 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:05:43 +0100 Subject: check_curl: do not export local variables and remove unused ones --- plugins/check_curl.c | 247 ++++++++++++++++++++++++--------------------------- 1 file changed, 118 insertions(+), 129 deletions(-) diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 8277f5e2..06fc6d6f 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -128,141 +128,138 @@ enum { MAX_RE_SIZE = 1024 }; #include "regex.h" -regex_t preg; -regmatch_t pmatch[REGS]; -char regexp[MAX_RE_SIZE]; -int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE; -int errcode; -bool invert_regex = false; -int state_regex = STATE_CRITICAL; - -char *server_address = NULL; -char *host_name = NULL; -char *server_url = 0; -char server_ip[DEFAULT_BUFFER_SIZE]; -struct curl_slist *server_ips = NULL; -bool specify_port = false; -unsigned short server_port = HTTP_PORT; -unsigned short virtual_port = 0; -int host_name_length; -char output_header_search[30] = ""; -char output_string_search[30] = ""; -char *warning_thresholds = NULL; -char *critical_thresholds = NULL; -int days_till_exp_warn, days_till_exp_crit; -thresholds *thlds; -char user_agent[DEFAULT_BUFFER_SIZE]; -int verbose = 0; -bool show_extended_perfdata = false; -bool show_body = false; -int min_page_len = 0; -int max_page_len = 0; -int redir_depth = 0; -int max_depth = DEFAULT_MAX_REDIRS; -char *http_method = NULL; -char *http_post_data = NULL; -char *http_content_type = NULL; -CURL *curl; -bool curl_global_initialized = false; -bool curl_easy_initialized = false; -struct curl_slist *header_list = NULL; -bool body_buf_initialized = false; -curlhelp_write_curlbuf body_buf; -bool header_buf_initialized = false; -curlhelp_write_curlbuf header_buf; -bool status_line_initialized = false; -curlhelp_statusline status_line; -bool put_buf_initialized = false; -curlhelp_read_curlbuf put_buf; -char http_header[DEFAULT_BUFFER_SIZE]; -long code; -long socket_timeout = DEFAULT_SOCKET_TIMEOUT; -double total_time; -double time_connect; -double time_appconnect; -double time_headers; -double time_firstbyte; -char errbuf[MAX_INPUT_BUFFER]; -CURLcode res; -char url[DEFAULT_BUFFER_SIZE]; -char msg[DEFAULT_BUFFER_SIZE]; -char perfstring[DEFAULT_BUFFER_SIZE]; -char header_expect[MAX_INPUT_BUFFER] = ""; -char string_expect[MAX_INPUT_BUFFER] = ""; -char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT; -int server_expect_yn = 0; -char user_auth[MAX_INPUT_BUFFER] = ""; -char proxy_auth[MAX_INPUT_BUFFER] = ""; -char **http_opt_headers; -int http_opt_headers_count = 0; -bool display_html = false; -int onredirect = STATE_OK; -int followmethod = FOLLOW_HTTP_CURL; -int followsticky = STICKY_NONE; -bool use_ssl = false; -bool use_sni = true; -bool check_cert = false; -bool continue_after_check_cert = false; +static regex_t preg; +static regmatch_t pmatch[REGS]; +static char regexp[MAX_RE_SIZE]; +static int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE; +static int errcode; +static bool invert_regex = false; +static int state_regex = STATE_CRITICAL; + +static char *server_address = NULL; +static char *host_name = NULL; +static char *server_url = 0; +static struct curl_slist *server_ips = NULL; +static bool specify_port = false; +static unsigned short server_port = HTTP_PORT; +static unsigned short virtual_port = 0; +static int host_name_length; +static char output_header_search[30] = ""; +static char output_string_search[30] = ""; +static char *warning_thresholds = NULL; +static char *critical_thresholds = NULL; +static int days_till_exp_warn, days_till_exp_crit; +static thresholds *thlds; +static char user_agent[DEFAULT_BUFFER_SIZE]; +static int verbose = 0; +static bool show_extended_perfdata = false; +static bool show_body = false; +static int min_page_len = 0; +static int max_page_len = 0; +static int redir_depth = 0; +static int max_depth = DEFAULT_MAX_REDIRS; +static char *http_method = NULL; +static char *http_post_data = NULL; +static char *http_content_type = NULL; +static CURL *curl; +static bool curl_global_initialized = false; +static bool curl_easy_initialized = false; +static struct curl_slist *header_list = NULL; +static bool body_buf_initialized = false; +static curlhelp_write_curlbuf body_buf; +static bool header_buf_initialized = false; +static curlhelp_write_curlbuf header_buf; +static bool status_line_initialized = false; +static curlhelp_statusline status_line; +static bool put_buf_initialized = false; +static curlhelp_read_curlbuf put_buf; +static char http_header[DEFAULT_BUFFER_SIZE]; +static long code; +static long socket_timeout = DEFAULT_SOCKET_TIMEOUT; +static double total_time; +static double time_connect; +static double time_appconnect; +static double time_headers; +static double time_firstbyte; +static char errbuf[MAX_INPUT_BUFFER]; +static CURLcode res; +static char url[DEFAULT_BUFFER_SIZE]; +static char msg[DEFAULT_BUFFER_SIZE]; +static char perfstring[DEFAULT_BUFFER_SIZE]; +static char header_expect[MAX_INPUT_BUFFER] = ""; +static char string_expect[MAX_INPUT_BUFFER] = ""; +static char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT; +static int server_expect_yn = 0; +static char user_auth[MAX_INPUT_BUFFER] = ""; +static char proxy_auth[MAX_INPUT_BUFFER] = ""; +static char **http_opt_headers; +static int http_opt_headers_count = 0; +static bool display_html = false; +static int onredirect = STATE_OK; +static int followmethod = FOLLOW_HTTP_CURL; +static int followsticky = STICKY_NONE; +static bool use_ssl = false; +static bool check_cert = false; +static bool continue_after_check_cert = false; typedef union { struct curl_slist *to_info; struct curl_certinfo *to_certinfo; } cert_ptr_union; -cert_ptr_union cert_ptr; -int ssl_version = CURL_SSLVERSION_DEFAULT; -char *client_cert = NULL; -char *client_privkey = NULL; -char *ca_cert = NULL; -bool verify_peer_and_host = false; -bool is_openssl_callback = false; -bool add_sslctx_verify_fun = false; +static cert_ptr_union cert_ptr; +static int ssl_version = CURL_SSLVERSION_DEFAULT; +static char *client_cert = NULL; +static char *client_privkey = NULL; +static char *ca_cert = NULL; +static bool verify_peer_and_host = false; +static bool is_openssl_callback = false; +static bool add_sslctx_verify_fun = false; #if defined(HAVE_SSL) && defined(USE_OPENSSL) -X509 *cert = NULL; +static X509 *cert = NULL; #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ -bool no_body = false; -int maximum_age = -1; -int address_family = AF_UNSPEC; -curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; -int curl_http_version = CURL_HTTP_VERSION_NONE; -bool automatic_decompression = false; -char *cookie_jar_file = NULL; -bool haproxy_protocol = false; - -bool process_arguments(int, char **); -void handle_curl_option_return_code(CURLcode res, const char *option); -int check_http(void); -void redir(curlhelp_write_curlbuf *); -char *perfd_time(double microsec); -char *perfd_time_connect(double microsec); -char *perfd_time_ssl(double microsec); -char *perfd_time_firstbyte(double microsec); -char *perfd_time_headers(double microsec); -char *perfd_time_transfer(double microsec); -char *perfd_size(int page_len); -void print_help(void); +static bool no_body = false; +static int maximum_age = -1; +static int address_family = AF_UNSPEC; +static curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; +static int curl_http_version = CURL_HTTP_VERSION_NONE; +static bool automatic_decompression = false; +static char *cookie_jar_file = NULL; +static bool haproxy_protocol = false; + +static bool process_arguments(int, char **); +static void handle_curl_option_return_code(CURLcode res, const char *option); +static int check_http(void); +static void redir(curlhelp_write_curlbuf *); +static char *perfd_time(double microsec); +static char *perfd_time_connect(double microsec); +static char *perfd_time_ssl(double microsec); +static char *perfd_time_firstbyte(double microsec); +static char *perfd_time_headers(double microsec); +static char *perfd_time_transfer(double microsec); +static char *perfd_size(int page_len); +static void print_help(void); void print_usage(void); -void print_curl_version(void); -int curlhelp_initwritebuffer(curlhelp_write_curlbuf *); -size_t curlhelp_buffer_write_callback(void *, size_t, size_t, void *); -void curlhelp_freewritebuffer(curlhelp_write_curlbuf *); -int curlhelp_initreadbuffer(curlhelp_read_curlbuf *, const char *, size_t); -size_t curlhelp_buffer_read_callback(void *, size_t, size_t, void *); -void curlhelp_freereadbuffer(curlhelp_read_curlbuf *); -curlhelp_ssl_library curlhelp_get_ssl_library(); -const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library); +static void print_curl_version(void); +static int curlhelp_initwritebuffer(curlhelp_write_curlbuf *); +static size_t curlhelp_buffer_write_callback(void *, size_t, size_t, void *); +static void curlhelp_freewritebuffer(curlhelp_write_curlbuf *); +static int curlhelp_initreadbuffer(curlhelp_read_curlbuf *, const char *, size_t); +static size_t curlhelp_buffer_read_callback(void *, size_t, size_t, void *); +static void curlhelp_freereadbuffer(curlhelp_read_curlbuf *); +static curlhelp_ssl_library curlhelp_get_ssl_library(); +static const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library); int net_noopenssl_check_certificate(cert_ptr_union *, int, int); -int curlhelp_parse_statusline(const char *, curlhelp_statusline *); -void curlhelp_free_statusline(curlhelp_statusline *); -char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header); -int check_document_dates(const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); -int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf); +static int curlhelp_parse_statusline(const char *, curlhelp_statusline *); +static void curlhelp_free_statusline(curlhelp_statusline *); +static char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header); +static int check_document_dates(const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); +static int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf); #if defined(HAVE_SSL) && defined(USE_OPENSSL) int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit); #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ -void remove_newlines(char *); -void test_file(char *); +static void test_file(char *); int main(int argc, char **argv) { int result = STATE_UNKNOWN; @@ -2311,14 +2308,6 @@ int curlhelp_parse_statusline(const char *buf, curlhelp_statusline *status_line) void curlhelp_free_statusline(curlhelp_statusline *status_line) { free(status_line->first_line); } -void remove_newlines(char *s) { - char *p; - - for (p = s; *p != '\0'; p++) - if (*p == '\r' || *p == '\n') - *p = ' '; -} - char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header) { for (size_t i = 0; i < nof_headers; i++) { if (headers[i].name != NULL && strncasecmp(header, headers[i].name, max(headers[i].name_len, 4)) == 0) { -- cgit v1.2.3-74-g34f1 From fde8e9c77b094ccec536d05c634d9d8f1f0e3abc Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:10:57 +0100 Subject: check_curl: Linter fixes --- plugins/check_curl.c | 55 ++++++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/plugins/check_curl.c b/plugins/check_curl.c index 06fc6d6f..1d27da28 100644 --- a/plugins/check_curl.c +++ b/plugins/check_curl.c @@ -225,41 +225,41 @@ static bool automatic_decompression = false; static char *cookie_jar_file = NULL; static bool haproxy_protocol = false; -static bool process_arguments(int, char **); +static bool process_arguments(int /*argc*/, char ** /*argv*/); static void handle_curl_option_return_code(CURLcode res, const char *option); static int check_http(void); -static void redir(curlhelp_write_curlbuf *); -static char *perfd_time(double microsec); -static char *perfd_time_connect(double microsec); -static char *perfd_time_ssl(double microsec); -static char *perfd_time_firstbyte(double microsec); -static char *perfd_time_headers(double microsec); -static char *perfd_time_transfer(double microsec); +static void redir(curlhelp_write_curlbuf * /*header_buf*/); +static char *perfd_time(double elapsed_time); +static char *perfd_time_connect(double elapsed_time_connect); +static char *perfd_time_ssl(double elapsed_time_ssl); +static char *perfd_time_firstbyte(double elapsed_time_firstbyte); +static char *perfd_time_headers(double elapsed_time_headers); +static char *perfd_time_transfer(double elapsed_time_transfer); static char *perfd_size(int page_len); static void print_help(void); void print_usage(void); static void print_curl_version(void); -static int curlhelp_initwritebuffer(curlhelp_write_curlbuf *); -static size_t curlhelp_buffer_write_callback(void *, size_t, size_t, void *); -static void curlhelp_freewritebuffer(curlhelp_write_curlbuf *); -static int curlhelp_initreadbuffer(curlhelp_read_curlbuf *, const char *, size_t); -static size_t curlhelp_buffer_read_callback(void *, size_t, size_t, void *); -static void curlhelp_freereadbuffer(curlhelp_read_curlbuf *); -static curlhelp_ssl_library curlhelp_get_ssl_library(); -static const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library); +static int curlhelp_initwritebuffer(curlhelp_write_curlbuf * /*buf*/); +static size_t curlhelp_buffer_write_callback(void * /*buffer*/, size_t /*size*/, size_t /*nmemb*/, void * /*stream*/); +static void curlhelp_freewritebuffer(curlhelp_write_curlbuf * /*buf*/); +static int curlhelp_initreadbuffer(curlhelp_read_curlbuf * /*buf*/, const char * /*data*/, size_t /*datalen*/); +static size_t curlhelp_buffer_read_callback(void * /*buffer*/, size_t /*size*/, size_t /*nmemb*/, void * /*stream*/); +static void curlhelp_freereadbuffer(curlhelp_read_curlbuf * /*buf*/); +static curlhelp_ssl_library curlhelp_get_ssl_library(void); +static const char *curlhelp_get_ssl_library_string(curlhelp_ssl_library /*ssl_library*/); int net_noopenssl_check_certificate(cert_ptr_union *, int, int); -static int curlhelp_parse_statusline(const char *, curlhelp_statusline *); -static void curlhelp_free_statusline(curlhelp_statusline *); -static char *get_header_value(const struct phr_header *headers, const size_t nof_headers, const char *header); -static int check_document_dates(const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); +static int curlhelp_parse_statusline(const char * /*buf*/, curlhelp_statusline * /*status_line*/); +static void curlhelp_free_statusline(curlhelp_statusline * /*status_line*/); +static char *get_header_value(const struct phr_header *headers, size_t nof_headers, const char *header); +static int check_document_dates(const curlhelp_write_curlbuf * /*header_buf*/, char (*msg)[DEFAULT_BUFFER_SIZE]); static int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_write_curlbuf *body_buf); #if defined(HAVE_SSL) && defined(USE_OPENSSL) int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit); #endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ -static void test_file(char *); +static void test_file(char * /*path*/); int main(int argc, char **argv) { int result = STATE_UNKNOWN; @@ -301,7 +301,8 @@ int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) { # endif if (verbose >= 2) { puts("* SSL verify callback with certificate:"); - X509_NAME *subject, *issuer; + X509_NAME *subject; + X509_NAME *issuer; printf("* issuer:\n"); issuer = X509_get_issuer_name(cert); X509_NAME_print_ex_fp(stdout, issuer, 5, XN_FLAG_MULTILINE); @@ -356,7 +357,8 @@ static char *string_statuscode(int major, int minor) { /* Checks if the server 'reply' is one of the expected 'statuscodes' */ static int expected_statuscode(const char *reply, const char *statuscodes) { - char *expected, *code; + char *expected; + char *code; int result = 0; if ((expected = strdup(statuscodes)) == NULL) @@ -523,7 +525,7 @@ int check_http(void) { // use the host_name later on to make SNI happy if (use_ssl && host_name != NULL) { if ((res = lookup_host(server_address, addrstr, DEFAULT_BUFFER_SIZE / 2)) != 0) { - snprintf(msg, DEFAULT_BUFFER_SIZE, _("Unable to lookup IP address for '%s': getaddrinfo returned %d - %s"), server_address, res, + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Unable to lookup IP address for '%s': getaddrinfo returned %d - %d"), server_address, res, gai_strerror(res)); die(STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); } @@ -2183,8 +2185,7 @@ const char *strrstr2(const char *haystack, const char *needle) { if (pos == NULL) { if (counter == 0) return NULL; - else - return prev_pos; + return prev_pos; } counter++; prev_pos = pos; @@ -2438,7 +2439,7 @@ int get_content_length(const curlhelp_write_curlbuf *header_buf, const curlhelp_ } /* TODO: is there a better way in libcurl to check for the SSL library? */ -curlhelp_ssl_library curlhelp_get_ssl_library() { +curlhelp_ssl_library curlhelp_get_ssl_library(void) { curl_version_info_data *version_data; char *ssl_version; char *library; -- cgit v1.2.3-74-g34f1 From c413037aa8041daccb61d4bef77e34553e3c5fb7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:11:54 +0100 Subject: check_dbi: clang-format --- plugins/check_dbi.c | 784 ++++++++++++++++++++++++---------------------------- 1 file changed, 363 insertions(+), 421 deletions(-) diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c index 29c85206..0c0ed6d7 100644 --- a/plugins/check_dbi.c +++ b/plugins/check_dbi.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_dbi plugin -* -* License: GPL -* Copyright (c) 2011 Monitoring Plugins Development Team -* Author: Sebastian 'tokkee' Harl -* -* Description: -* -* This file contains the check_dbi plugin -* -* Runs an arbitrary (SQL) command and checks the result. -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_dbi plugin + * + * License: GPL + * Copyright (c) 2011 Monitoring Plugins Development Team + * Author: Sebastian 'tokkee' Harl + * + * Description: + * + * This file contains the check_dbi plugin + * + * Runs an arbitrary (SQL) command and checks the result. + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_dbi"; const char *copyright = "2011"; @@ -43,7 +43,7 @@ const char *email = "devel@monitoring-plugins.org"; /* required for NAN */ #ifndef _ISOC99_SOURCE -#define _ISOC99_SOURCE +# define _ISOC99_SOURCE #endif #include @@ -92,20 +92,18 @@ int np_dbi_options_num = 0; char *np_dbi_database = NULL; char *np_dbi_query = NULL; -int process_arguments (int, char **); -int validate_arguments (void); -void print_usage (void); -void print_help (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_usage(void); +void print_help(void); -double timediff (struct timeval, struct timeval); +double timediff(struct timeval, struct timeval); -void np_dbi_print_error (dbi_conn, char *, ...); +void np_dbi_print_error(dbi_conn, char *, ...); -int do_query (dbi_conn, const char **, double *, double *); +int do_query(dbi_conn, const char **, double *, double *); -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int status = STATE_UNKNOWN; dbi_driver driver; @@ -122,59 +120,58 @@ main (int argc, char **argv) int i; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv = np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); /* Set signal handling and alarm */ - if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) { - usage4 (_("Cannot catch SIGALRM")); + if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) { + usage4(_("Cannot catch SIGALRM")); } - alarm (timeout_interval); + alarm(timeout_interval); if (verbose > 2) - printf ("Initializing DBI\n"); + printf("Initializing DBI\n"); - dbi_inst *instance_p = { 0 }; + dbi_inst *instance_p = {0}; if (dbi_initialize_r(NULL, instance_p) < 0) { - printf ("UNKNOWN - failed to initialize DBI; possibly you don't have any drivers installed.\n"); + printf("UNKNOWN - failed to initialize DBI; possibly you don't have any drivers installed.\n"); return STATE_UNKNOWN; } if (instance_p == NULL) { - printf ("UNKNOWN - failed to initialize DBI.\n"); + printf("UNKNOWN - failed to initialize DBI.\n"); return STATE_UNKNOWN; } if (verbose) - printf ("Opening DBI driver '%s'\n", np_dbi_driver); + printf("Opening DBI driver '%s'\n", np_dbi_driver); driver = dbi_driver_open_r(np_dbi_driver, instance_p); - if (! driver) { - printf ("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n", - np_dbi_driver); + if (!driver) { + printf("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n", np_dbi_driver); - printf ("Known drivers:\n"); + printf("Known drivers:\n"); for (driver = dbi_driver_list_r(NULL, instance_p); driver; driver = dbi_driver_list_r(driver, instance_p)) { - printf (" - %s\n", dbi_driver_get_name (driver)); + printf(" - %s\n", dbi_driver_get_name(driver)); } return STATE_UNKNOWN; } /* make a connection to the database */ - gettimeofday (&start_timeval, NULL); + gettimeofday(&start_timeval, NULL); - conn = dbi_conn_open (driver); - if (! conn) { - printf ("UNKNOWN - failed top open connection object.\n"); - dbi_conn_close (conn); + conn = dbi_conn_open(driver); + if (!conn) { + printf("UNKNOWN - failed top open connection object.\n"); + dbi_conn_close(conn); return STATE_UNKNOWN; } @@ -182,210 +179,189 @@ main (int argc, char **argv) const char *opt; if (verbose > 1) - printf ("Setting DBI driver option '%s' to '%s'\n", - np_dbi_options[i].key, np_dbi_options[i].value); + printf("Setting DBI driver option '%s' to '%s'\n", np_dbi_options[i].key, np_dbi_options[i].value); - if (! dbi_conn_set_option (conn, np_dbi_options[i].key, np_dbi_options[i].value)) + if (!dbi_conn_set_option(conn, np_dbi_options[i].key, np_dbi_options[i].value)) continue; /* else: status != 0 */ - np_dbi_print_error (conn, "UNKNOWN - failed to set option '%s' to '%s'", - np_dbi_options[i].key, np_dbi_options[i].value); - printf ("Known driver options:\n"); + np_dbi_print_error(conn, "UNKNOWN - failed to set option '%s' to '%s'", np_dbi_options[i].key, np_dbi_options[i].value); + printf("Known driver options:\n"); - for (opt = dbi_conn_get_option_list (conn, NULL); opt; - opt = dbi_conn_get_option_list (conn, opt)) { - printf (" - %s\n", opt); + for (opt = dbi_conn_get_option_list(conn, NULL); opt; opt = dbi_conn_get_option_list(conn, opt)) { + printf(" - %s\n", opt); } - dbi_conn_close (conn); + dbi_conn_close(conn); return STATE_UNKNOWN; } if (host) { if (verbose > 1) - printf ("Setting DBI driver option 'host' to '%s'\n", host); - dbi_conn_set_option (conn, "host", host); + printf("Setting DBI driver option 'host' to '%s'\n", host); + dbi_conn_set_option(conn, "host", host); } if (verbose) { const char *dbname, *host; - dbname = dbi_conn_get_option (conn, "dbname"); - host = dbi_conn_get_option (conn, "host"); + dbname = dbi_conn_get_option(conn, "dbname"); + host = dbi_conn_get_option(conn, "host"); - if (! dbname) + if (!dbname) dbname = ""; - if (! host) + if (!host) host = ""; - printf ("Connecting to database '%s' at host '%s'\n", - dbname, host); + printf("Connecting to database '%s' at host '%s'\n", dbname, host); } - if (dbi_conn_connect (conn) < 0) { - np_dbi_print_error (conn, "UNKNOWN - failed to connect to database"); + if (dbi_conn_connect(conn) < 0) { + np_dbi_print_error(conn, "UNKNOWN - failed to connect to database"); return STATE_UNKNOWN; } - gettimeofday (&end_timeval, NULL); - conn_time = timediff (start_timeval, end_timeval); + gettimeofday(&end_timeval, NULL); + conn_time = timediff(start_timeval, end_timeval); - server_version = dbi_conn_get_engine_version (conn); + server_version = dbi_conn_get_engine_version(conn); if (verbose) - printf ("Connected to server version %u\n", server_version); + printf("Connected to server version %u\n", server_version); if (metric == METRIC_SERVER_VERSION) - status = get_status (server_version, dbi_thresholds); + status = get_status(server_version, dbi_thresholds); if (verbose) - printf ("Time elapsed: %f\n", conn_time); + printf("Time elapsed: %f\n", conn_time); if (metric == METRIC_CONN_TIME) - status = get_status (conn_time, dbi_thresholds); + status = get_status(conn_time, dbi_thresholds); /* select a database */ if (np_dbi_database) { if (verbose > 1) - printf ("Selecting database '%s'\n", np_dbi_database); + printf("Selecting database '%s'\n", np_dbi_database); - if (dbi_conn_select_db (conn, np_dbi_database)) { - np_dbi_print_error (conn, "UNKNOWN - failed to select database '%s'", - np_dbi_database); + if (dbi_conn_select_db(conn, np_dbi_database)) { + np_dbi_print_error(conn, "UNKNOWN - failed to select database '%s'", np_dbi_database); return STATE_UNKNOWN; } } if (np_dbi_query) { /* execute query */ - status = do_query (conn, &query_val_str, &query_val, &query_time); + status = do_query(conn, &query_val_str, &query_val, &query_time); if (status != STATE_OK) /* do_query prints an error message in this case */ return status; if (metric == METRIC_QUERY_RESULT) { if (expect) { - if ((! query_val_str) || strcmp (query_val_str, expect)) + if ((!query_val_str) || strcmp(query_val_str, expect)) status = STATE_CRITICAL; else status = STATE_OK; - } - else if (expect_re_str) { + } else if (expect_re_str) { int err; - err = regexec (&expect_re, query_val_str, 0, NULL, /* flags = */ 0); - if (! err) + err = regexec(&expect_re, query_val_str, 0, NULL, /* flags = */ 0); + if (!err) status = STATE_OK; else if (err == REG_NOMATCH) status = STATE_CRITICAL; else { char errmsg[1024]; - regerror (err, &expect_re, errmsg, sizeof (errmsg)); - printf ("ERROR - failed to execute regular expression: %s\n", - errmsg); + regerror(err, &expect_re, errmsg, sizeof(errmsg)); + printf("ERROR - failed to execute regular expression: %s\n", errmsg); status = STATE_CRITICAL; } - } - else - status = get_status (query_val, dbi_thresholds); - } - else if (metric == METRIC_QUERY_TIME) - status = get_status (query_time, dbi_thresholds); + } else + status = get_status(query_val, dbi_thresholds); + } else if (metric == METRIC_QUERY_TIME) + status = get_status(query_time, dbi_thresholds); } if (verbose) printf("Closing connection\n"); - dbi_conn_close (conn); + dbi_conn_close(conn); /* In case of METRIC_QUERY_RESULT, isnan(query_val) indicates an error * which should have been reported and handled (abort) before * ... unless we expected a string to be returned */ - assert ((metric != METRIC_QUERY_RESULT) || (! isnan (query_val)) - || (type == TYPE_STRING)); + assert((metric != METRIC_QUERY_RESULT) || (!isnan(query_val)) || (type == TYPE_STRING)); - assert ((type != TYPE_STRING) || (expect || expect_re_str)); + assert((type != TYPE_STRING) || (expect || expect_re_str)); - printf ("%s - connection time: %fs", state_text (status), conn_time); + printf("%s - connection time: %fs", state_text(status), conn_time); if (np_dbi_query) { if (type == TYPE_STRING) { - assert (expect || expect_re_str); - printf (", '%s' returned '%s' in %fs", np_dbi_query, - query_val_str ? query_val_str : "", query_time); + assert(expect || expect_re_str); + printf(", '%s' returned '%s' in %fs", np_dbi_query, query_val_str ? query_val_str : "", query_time); if (status != STATE_OK) { if (expect) - printf (" (expected '%s')", expect); + printf(" (expected '%s')", expect); else if (expect_re_str) - printf (" (expected regex /%s/%s)", expect_re_str, - ((expect_re_cflags & REG_ICASE) ? "i" : "")); + printf(" (expected regex /%s/%s)", expect_re_str, ((expect_re_cflags & REG_ICASE) ? "i" : "")); } - } - else if (isnan (query_val)) - printf (", '%s' query execution time: %fs", np_dbi_query, query_time); + } else if (isnan(query_val)) + printf(", '%s' query execution time: %fs", np_dbi_query, query_time); else - printf (", '%s' returned %f in %fs", np_dbi_query, query_val, query_time); + printf(", '%s' returned %f in %fs", np_dbi_query, query_val, query_time); } - printf (" | conntime=%fs;%s;%s;0; server_version=%u;%s;%s;0;", conn_time, - ((metric == METRIC_CONN_TIME) && warning_range) ? warning_range : "", - ((metric == METRIC_CONN_TIME) && critical_range) ? critical_range : "", - server_version, - ((metric == METRIC_SERVER_VERSION) && warning_range) ? warning_range : "", - ((metric == METRIC_SERVER_VERSION) && critical_range) ? critical_range : ""); + printf(" | conntime=%fs;%s;%s;0; server_version=%u;%s;%s;0;", conn_time, + ((metric == METRIC_CONN_TIME) && warning_range) ? warning_range : "", + ((metric == METRIC_CONN_TIME) && critical_range) ? critical_range : "", server_version, + ((metric == METRIC_SERVER_VERSION) && warning_range) ? warning_range : "", + ((metric == METRIC_SERVER_VERSION) && critical_range) ? critical_range : ""); if (np_dbi_query) { - if (! isnan (query_val)) /* this is also true when -e is used */ - printf (" query=%f;%s;%s;;", query_val, - ((metric == METRIC_QUERY_RESULT) && warning_range) ? warning_range : "", - ((metric == METRIC_QUERY_RESULT) && critical_range) ? critical_range : ""); - printf (" querytime=%fs;%s;%s;0;", query_time, - ((metric == METRIC_QUERY_TIME) && warning_range) ? warning_range : "", - ((metric == METRIC_QUERY_TIME) && critical_range) ? critical_range : ""); + if (!isnan(query_val)) /* this is also true when -e is used */ + printf(" query=%f;%s;%s;;", query_val, ((metric == METRIC_QUERY_RESULT) && warning_range) ? warning_range : "", + ((metric == METRIC_QUERY_RESULT) && critical_range) ? critical_range : ""); + printf(" querytime=%fs;%s;%s;0;", query_time, ((metric == METRIC_QUERY_TIME) && warning_range) ? warning_range : "", + ((metric == METRIC_QUERY_TIME) && critical_range) ? critical_range : ""); } - printf ("\n"); + printf("\n"); return status; } /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; int option = 0; - static struct option longopts[] = { - STD_LONG_OPTS, - - {"expect", required_argument, 0, 'e'}, - {"regex", required_argument, 0, 'r'}, - {"regexi", required_argument, 0, 'R'}, - {"metric", required_argument, 0, 'm'}, - {"driver", required_argument, 0, 'd'}, - {"option", required_argument, 0, 'o'}, - {"query", required_argument, 0, 'q'}, - {"database", required_argument, 0, 'D'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {STD_LONG_OPTS, + + {"expect", required_argument, 0, 'e'}, + {"regex", required_argument, 0, 'r'}, + {"regexi", required_argument, 0, 'R'}, + {"metric", required_argument, 0, 'm'}, + {"driver", required_argument, 0, 'd'}, + {"option", required_argument, 0, 'o'}, + {"query", required_argument, 0, 'q'}, + {"database", required_argument, 0, 'D'}, + {0, 0, 0, 0}}; while (1) { - c = getopt_long (argc, argv, "Vvht:c:w:e:r:R:m:H:d:o:q:D:", - longopts, &option); + c = getopt_long(argc, argv, "Vvht:c:w:e:r:R:m:H:d:o:q:D:", longopts, &option); if (c == EOF) break; switch (c) { - case '?': /* usage */ - usage5 (); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - - case 'c': /* critical range */ + case '?': /* usage */ + usage5(); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + + case 'c': /* critical range */ critical_range = optarg; type = TYPE_NUMERIC; break; - case 'w': /* warning range */ + case 'w': /* warning range */ warning_range = optarg; type = TYPE_NUMERIC; break; @@ -396,47 +372,45 @@ process_arguments (int argc, char **argv) case 'R': expect_re_cflags = REG_ICASE; /* fall through */ - case 'r': - { - int err; + case 'r': { + int err; - expect_re_cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; - expect_re_str = optarg; - type = TYPE_STRING; + expect_re_cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; + expect_re_str = optarg; + type = TYPE_STRING; - err = regcomp (&expect_re, expect_re_str, expect_re_cflags); - if (err) { - char errmsg[1024]; - regerror (err, &expect_re, errmsg, sizeof (errmsg)); - printf ("ERROR - failed to compile regular expression: %s\n", - errmsg); - return ERROR; - } - break; + err = regcomp(&expect_re, expect_re_str, expect_re_cflags); + if (err) { + char errmsg[1024]; + regerror(err, &expect_re, errmsg, sizeof(errmsg)); + printf("ERROR - failed to compile regular expression: %s\n", errmsg); + return ERROR; } + break; + } case 'm': - if (! strcasecmp (optarg, "CONN_TIME")) + if (!strcasecmp(optarg, "CONN_TIME")) metric = METRIC_CONN_TIME; - else if (! strcasecmp (optarg, "SERVER_VERSION")) + else if (!strcasecmp(optarg, "SERVER_VERSION")) metric = METRIC_SERVER_VERSION; - else if (! strcasecmp (optarg, "QUERY_RESULT")) + else if (!strcasecmp(optarg, "QUERY_RESULT")) metric = METRIC_QUERY_RESULT; - else if (! strcasecmp (optarg, "QUERY_TIME")) + else if (!strcasecmp(optarg, "QUERY_TIME")) metric = METRIC_QUERY_TIME; else - usage2 (_("Invalid metric"), optarg); + usage2(_("Invalid metric"), optarg); break; - case 't': /* timeout */ - if (!is_intnonneg (optarg)) - usage2 (_("Timeout interval must be a positive integer"), optarg); + case 't': /* timeout */ + if (!is_intnonneg(optarg)) + usage2(_("Timeout interval must be a positive integer"), optarg); else - timeout_interval = atoi (optarg); + timeout_interval = atoi(optarg); break; - case 'H': /* host */ - if (!is_host (optarg)) - usage2 (_("Invalid hostname/address"), optarg); + case 'H': /* host */ + if (!is_host(optarg)) + usage2(_("Invalid hostname/address"), optarg); else host = optarg; break; @@ -447,36 +421,33 @@ process_arguments (int argc, char **argv) case 'd': np_dbi_driver = optarg; break; - case 'o': - { - driver_option_t *new; + case 'o': { + driver_option_t *new; - char *k, *v; + char *k, *v; - k = optarg; - v = strchr (k, (int)'='); + k = optarg; + v = strchr(k, (int)'='); - if (! v) - usage2 (_("Option must be '='"), optarg); + if (!v) + usage2(_("Option must be '='"), optarg); - *v = '\0'; - ++v; + *v = '\0'; + ++v; - new = realloc (np_dbi_options, - (np_dbi_options_num + 1) * sizeof (*new)); - if (! new) { - printf ("UNKNOWN - failed to reallocate memory\n"); - exit (STATE_UNKNOWN); - } + new = realloc(np_dbi_options, (np_dbi_options_num + 1) * sizeof(*new)); + if (!new) { + printf("UNKNOWN - failed to reallocate memory\n"); + exit(STATE_UNKNOWN); + } - np_dbi_options = new; - new = np_dbi_options + np_dbi_options_num; - ++np_dbi_options_num; + np_dbi_options = new; + new = np_dbi_options + np_dbi_options_num; + ++np_dbi_options_num; - new->key = k; - new->value = v; - } - break; + new->key = k; + new->value = v; + } break; case 'q': np_dbi_query = optarg; break; @@ -486,341 +457,312 @@ process_arguments (int argc, char **argv) } } - set_thresholds (&dbi_thresholds, warning_range, critical_range); + set_thresholds(&dbi_thresholds, warning_range, critical_range); - return validate_arguments (); + return validate_arguments(); } -int -validate_arguments () -{ - if (! np_dbi_driver) - usage ("Must specify a DBI driver"); +int validate_arguments() { + if (!np_dbi_driver) + usage("Must specify a DBI driver"); - if (((metric == METRIC_QUERY_RESULT) || (metric == METRIC_QUERY_TIME)) - && (! np_dbi_query)) - usage ("Must specify a query to execute (metric == QUERY_RESULT)"); + if (((metric == METRIC_QUERY_RESULT) || (metric == METRIC_QUERY_TIME)) && (!np_dbi_query)) + usage("Must specify a query to execute (metric == QUERY_RESULT)"); - if ((metric != METRIC_CONN_TIME) - && (metric != METRIC_SERVER_VERSION) - && (metric != METRIC_QUERY_RESULT) - && (metric != METRIC_QUERY_TIME)) - usage ("Invalid metric specified"); + if ((metric != METRIC_CONN_TIME) && (metric != METRIC_SERVER_VERSION) && (metric != METRIC_QUERY_RESULT) && + (metric != METRIC_QUERY_TIME)) + usage("Invalid metric specified"); if (expect && (warning_range || critical_range || expect_re_str)) - usage ("Do not mix -e and -w/-c/-r/-R"); + usage("Do not mix -e and -w/-c/-r/-R"); if (expect_re_str && (warning_range || critical_range || expect)) - usage ("Do not mix -r/-R and -w/-c/-e"); + usage("Do not mix -r/-R and -w/-c/-e"); if (expect && (metric != METRIC_QUERY_RESULT)) - usage ("Option -e requires metric QUERY_RESULT"); + usage("Option -e requires metric QUERY_RESULT"); if (expect_re_str && (metric != METRIC_QUERY_RESULT)) - usage ("Options -r/-R require metric QUERY_RESULT"); + usage("Options -r/-R require metric QUERY_RESULT"); return OK; } -void -print_help (void) -{ - print_revision (progname, NP_VERSION); +void print_help(void) { + print_revision(progname, NP_VERSION); - printf (COPYRIGHT, copyright, email); + printf(COPYRIGHT, copyright, email); - printf (_("This program connects to an (SQL) database using DBI and checks the\n" - "specified metric against threshold levels. The default metric is\n" - "the result of the specified query.\n")); + printf(_("This program connects to an (SQL) database using DBI and checks the\n" + "specified metric against threshold levels. The default metric is\n" + "the result of the specified query.\n")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); + printf(UT_HELP_VRSN); /* include this conditionally to avoid 'zero-length printf format string' * compiler warnings */ #ifdef NP_EXTRA_OPTS - printf (UT_EXTRA_OPTS); + printf(UT_EXTRA_OPTS); #endif - printf ("\n"); - - printf (" %s\n", "-d, --driver=STRING"); - printf (" %s\n", _("DBI driver to use")); - printf (" %s\n", "-o, --option=STRING"); - printf (" %s\n", _("DBI driver options")); - printf (" %s\n", "-q, --query=STRING"); - printf (" %s\n", _("query to execute")); - printf ("\n"); - - printf (UT_WARN_CRIT_RANGE); - printf (" %s\n", "-e, --expect=STRING"); - printf (" %s\n", _("String to expect as query result")); - printf (" %s\n", _("Do not mix with -w, -c, -r, or -R!")); - printf (" %s\n", "-r, --regex=REGEX"); - printf (" %s\n", _("Extended POSIX regular expression to check query result against")); - printf (" %s\n", _("Do not mix with -w, -c, -e, or -R!")); - printf (" %s\n", "-R, --regexi=REGEX"); - printf (" %s\n", _("Case-insensitive extended POSIX regex to check query result against")); - printf (" %s\n", _("Do not mix with -w, -c, -e, or -r!")); - printf (" %s\n", "-m, --metric=METRIC"); - printf (" %s\n", _("Metric to check thresholds against. Available metrics:")); - printf (" CONN_TIME - %s\n", _("time used for setting up the database connection")); - printf (" QUERY_RESULT - %s\n", _("result (first column of first row) of the query")); - printf (" QUERY_TIME - %s\n", _("time used to execute the query")); - printf (" %s\n", _("(ignore the query result)")); - printf ("\n"); - - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - - printf (UT_VERBOSE); - - printf ("\n"); - printf (" %s\n", _("A DBI driver (-d option) is required. If the specified metric operates")); - printf (" %s\n\n", _("on a query, one has to be specified (-q option).")); - - printf (" %s\n", _("This plugin connects to an (SQL) database using libdbi and, optionally,")); - printf (" %s\n", _("executes the specified query. The first column of the first row of the")); - printf (" %s\n", _("result will be parsed and, in QUERY_RESULT mode, compared with the")); - printf (" %s\n", _("warning and critical ranges. The result from the query has to be numeric")); - printf (" %s\n\n", _("(strings representing numbers are fine).")); - - printf (" %s\n", _("The number and type of required DBI driver options depends on the actual")); - printf (" %s\n", _("driver. See its documentation at http://libdbi-drivers.sourceforge.net/")); - printf (" %s\n\n", _("for details.")); - - printf (" %s\n", _("Examples:")); - printf (" check_dbi -d pgsql -o username=postgres -m QUERY_RESULT \\\n"); - printf (" -q 'SELECT COUNT(*) FROM pg_stat_activity' -w 5 -c 10\n"); - printf (" Warning if more than five connections; critical if more than ten.\n\n"); - - printf (" check_dbi -d mysql -H localhost -o username=user -o password=secret \\\n"); - printf (" -q 'SELECT COUNT(*) FROM logged_in_users -w 5:20 -c 0:50\n"); - printf (" Warning if less than 5 or more than 20 users are logged in; critical\n"); - printf (" if more than 50 users.\n\n"); - - printf (" check_dbi -d firebird -o username=user -o password=secret -o dbname=foo \\\n"); - printf (" -m CONN_TIME -w 0.5 -c 2\n"); - printf (" Warning if connecting to the database takes more than half of a second;\n"); - printf (" critical if it takes more than 2 seconds.\n\n"); - - printf (" check_dbi -d mysql -H localhost -o username=user \\\n"); - printf (" -q 'SELECT concat(@@version, \" \", @@version_comment)' \\\n"); - printf (" -r '^5\\.[01].*MySQL Enterprise Server'\n"); - printf (" Critical if the database server is not a MySQL enterprise server in either\n"); - printf (" version 5.0.x or 5.1.x.\n\n"); - - printf (" check_dbi -d pgsql -u username=user -m SERVER_VERSION \\\n"); - printf (" -w 090000:090099 -c 090000:090199\n"); - printf (" Warn if the PostgreSQL server version is not 9.0.x; critical if the version\n"); - printf (" is less than 9.x or higher than 9.1.x.\n"); - - printf (UT_SUPPORT); + printf("\n"); + + printf(" %s\n", "-d, --driver=STRING"); + printf(" %s\n", _("DBI driver to use")); + printf(" %s\n", "-o, --option=STRING"); + printf(" %s\n", _("DBI driver options")); + printf(" %s\n", "-q, --query=STRING"); + printf(" %s\n", _("query to execute")); + printf("\n"); + + printf(UT_WARN_CRIT_RANGE); + printf(" %s\n", "-e, --expect=STRING"); + printf(" %s\n", _("String to expect as query result")); + printf(" %s\n", _("Do not mix with -w, -c, -r, or -R!")); + printf(" %s\n", "-r, --regex=REGEX"); + printf(" %s\n", _("Extended POSIX regular expression to check query result against")); + printf(" %s\n", _("Do not mix with -w, -c, -e, or -R!")); + printf(" %s\n", "-R, --regexi=REGEX"); + printf(" %s\n", _("Case-insensitive extended POSIX regex to check query result against")); + printf(" %s\n", _("Do not mix with -w, -c, -e, or -r!")); + printf(" %s\n", "-m, --metric=METRIC"); + printf(" %s\n", _("Metric to check thresholds against. Available metrics:")); + printf(" CONN_TIME - %s\n", _("time used for setting up the database connection")); + printf(" QUERY_RESULT - %s\n", _("result (first column of first row) of the query")); + printf(" QUERY_TIME - %s\n", _("time used to execute the query")); + printf(" %s\n", _("(ignore the query result)")); + printf("\n"); + + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + + printf(UT_VERBOSE); + + printf("\n"); + printf(" %s\n", _("A DBI driver (-d option) is required. If the specified metric operates")); + printf(" %s\n\n", _("on a query, one has to be specified (-q option).")); + + printf(" %s\n", _("This plugin connects to an (SQL) database using libdbi and, optionally,")); + printf(" %s\n", _("executes the specified query. The first column of the first row of the")); + printf(" %s\n", _("result will be parsed and, in QUERY_RESULT mode, compared with the")); + printf(" %s\n", _("warning and critical ranges. The result from the query has to be numeric")); + printf(" %s\n\n", _("(strings representing numbers are fine).")); + + printf(" %s\n", _("The number and type of required DBI driver options depends on the actual")); + printf(" %s\n", _("driver. See its documentation at http://libdbi-drivers.sourceforge.net/")); + printf(" %s\n\n", _("for details.")); + + printf(" %s\n", _("Examples:")); + printf(" check_dbi -d pgsql -o username=postgres -m QUERY_RESULT \\\n"); + printf(" -q 'SELECT COUNT(*) FROM pg_stat_activity' -w 5 -c 10\n"); + printf(" Warning if more than five connections; critical if more than ten.\n\n"); + + printf(" check_dbi -d mysql -H localhost -o username=user -o password=secret \\\n"); + printf(" -q 'SELECT COUNT(*) FROM logged_in_users -w 5:20 -c 0:50\n"); + printf(" Warning if less than 5 or more than 20 users are logged in; critical\n"); + printf(" if more than 50 users.\n\n"); + + printf(" check_dbi -d firebird -o username=user -o password=secret -o dbname=foo \\\n"); + printf(" -m CONN_TIME -w 0.5 -c 2\n"); + printf(" Warning if connecting to the database takes more than half of a second;\n"); + printf(" critical if it takes more than 2 seconds.\n\n"); + + printf(" check_dbi -d mysql -H localhost -o username=user \\\n"); + printf(" -q 'SELECT concat(@@version, \" \", @@version_comment)' \\\n"); + printf(" -r '^5\\.[01].*MySQL Enterprise Server'\n"); + printf(" Critical if the database server is not a MySQL enterprise server in either\n"); + printf(" version 5.0.x or 5.1.x.\n\n"); + + printf(" check_dbi -d pgsql -u username=user -m SERVER_VERSION \\\n"); + printf(" -w 090000:090099 -c 090000:090199\n"); + printf(" Warn if the PostgreSQL server version is not 9.0.x; critical if the version\n"); + printf(" is less than 9.x or higher than 9.1.x.\n"); + + printf(UT_SUPPORT); } -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -d [-o [...]] [-q ]\n", progname); - printf (" [-H ] [-c ] [-w ] [-m ]\n"); - printf (" [-e ] [-r|-R ]\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -d [-o [...]] [-q ]\n", progname); + printf(" [-H ] [-c ] [-w ] [-m ]\n"); + printf(" [-e ] [-r|-R ]\n"); } -#define CHECK_IGNORE_ERROR(s) \ - do { \ - if (metric != METRIC_QUERY_RESULT) \ - return (s); \ +#define CHECK_IGNORE_ERROR(s) \ + do { \ + if (metric != METRIC_QUERY_RESULT) \ + return (s); \ } while (0) -const char * -get_field_str (dbi_conn conn, dbi_result res, unsigned short field_type) -{ +const char *get_field_str(dbi_conn conn, dbi_result res, unsigned short field_type) { const char *str; if (field_type != DBI_TYPE_STRING) { - printf ("CRITICAL - result value is not a string\n"); + printf("CRITICAL - result value is not a string\n"); return NULL; } - str = dbi_result_get_string_idx (res, 1); - if ((! str) || (strcmp (str, "ERROR") == 0)) { - CHECK_IGNORE_ERROR (NULL); - np_dbi_print_error (conn, "CRITICAL - failed to fetch string value"); + str = dbi_result_get_string_idx(res, 1); + if ((!str) || (strcmp(str, "ERROR") == 0)) { + CHECK_IGNORE_ERROR(NULL); + np_dbi_print_error(conn, "CRITICAL - failed to fetch string value"); return NULL; } if ((verbose && (type == TYPE_STRING)) || (verbose > 2)) - printf ("Query returned string '%s'\n", str); + printf("Query returned string '%s'\n", str); return str; } -double -get_field (dbi_conn conn, dbi_result res, unsigned short *field_type) -{ +double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type) { double val = NAN; if (*field_type == DBI_TYPE_INTEGER) { - val = (double)dbi_result_get_longlong_idx (res, 1); - } - else if (*field_type == DBI_TYPE_DECIMAL) { - val = dbi_result_get_double_idx (res, 1); - } - else if (*field_type == DBI_TYPE_STRING) { + val = (double)dbi_result_get_longlong_idx(res, 1); + } else if (*field_type == DBI_TYPE_DECIMAL) { + val = dbi_result_get_double_idx(res, 1); + } else if (*field_type == DBI_TYPE_STRING) { const char *val_str; char *endptr = NULL; - val_str = get_field_str (conn, res, *field_type); - if (! val_str) { - CHECK_IGNORE_ERROR (NAN); + val_str = get_field_str(conn, res, *field_type); + if (!val_str) { + CHECK_IGNORE_ERROR(NAN); *field_type = DBI_TYPE_ERROR; return NAN; } - val = strtod (val_str, &endptr); + val = strtod(val_str, &endptr); if (endptr == val_str) { - CHECK_IGNORE_ERROR (NAN); - printf ("CRITICAL - result value is not a numeric: %s\n", val_str); + CHECK_IGNORE_ERROR(NAN); + printf("CRITICAL - result value is not a numeric: %s\n", val_str); *field_type = DBI_TYPE_ERROR; return NAN; - } - else if ((endptr != NULL) && (*endptr != '\0')) { + } else if ((endptr != NULL) && (*endptr != '\0')) { if (verbose) - printf ("Garbage after value: %s\n", endptr); + printf("Garbage after value: %s\n", endptr); } - } - else { - CHECK_IGNORE_ERROR (NAN); - printf ("CRITICAL - cannot parse value of type %s (%i)\n", - (*field_type == DBI_TYPE_BINARY) - ? "BINARY" - : (*field_type == DBI_TYPE_DATETIME) - ? "DATETIME" - : "", - *field_type); + } else { + CHECK_IGNORE_ERROR(NAN); + printf("CRITICAL - cannot parse value of type %s (%i)\n", + (*field_type == DBI_TYPE_BINARY) ? "BINARY" + : (*field_type == DBI_TYPE_DATETIME) ? "DATETIME" + : "", + *field_type); *field_type = DBI_TYPE_ERROR; return NAN; } return val; } -double -get_query_result (dbi_conn conn, dbi_result res, const char **res_val_str, double *res_val) -{ +double get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str, double *res_val) { unsigned short field_type; double val = NAN; - if (dbi_result_get_numrows (res) == DBI_ROW_ERROR) { - CHECK_IGNORE_ERROR (STATE_OK); - np_dbi_print_error (conn, "CRITICAL - failed to fetch rows"); + if (dbi_result_get_numrows(res) == DBI_ROW_ERROR) { + CHECK_IGNORE_ERROR(STATE_OK); + np_dbi_print_error(conn, "CRITICAL - failed to fetch rows"); return STATE_CRITICAL; } - if (dbi_result_get_numrows (res) < 1) { - CHECK_IGNORE_ERROR (STATE_OK); - printf ("WARNING - no rows returned\n"); + if (dbi_result_get_numrows(res) < 1) { + CHECK_IGNORE_ERROR(STATE_OK); + printf("WARNING - no rows returned\n"); return STATE_WARNING; } - if (dbi_result_get_numfields (res) == DBI_FIELD_ERROR) { - CHECK_IGNORE_ERROR (STATE_OK); - np_dbi_print_error (conn, "CRITICAL - failed to fetch fields"); + if (dbi_result_get_numfields(res) == DBI_FIELD_ERROR) { + CHECK_IGNORE_ERROR(STATE_OK); + np_dbi_print_error(conn, "CRITICAL - failed to fetch fields"); return STATE_CRITICAL; } - if (dbi_result_get_numfields (res) < 1) { - CHECK_IGNORE_ERROR (STATE_OK); - printf ("WARNING - no fields returned\n"); + if (dbi_result_get_numfields(res) < 1) { + CHECK_IGNORE_ERROR(STATE_OK); + printf("WARNING - no fields returned\n"); return STATE_WARNING; } - if (dbi_result_first_row (res) != 1) { - CHECK_IGNORE_ERROR (STATE_OK); - np_dbi_print_error (conn, "CRITICAL - failed to fetch first row"); + if (dbi_result_first_row(res) != 1) { + CHECK_IGNORE_ERROR(STATE_OK); + np_dbi_print_error(conn, "CRITICAL - failed to fetch first row"); return STATE_CRITICAL; } - field_type = dbi_result_get_field_type_idx (res, 1); + field_type = dbi_result_get_field_type_idx(res, 1); if (field_type != DBI_TYPE_ERROR) { if (type == TYPE_STRING) /* the value will be freed in dbi_result_free */ - *res_val_str = strdup (get_field_str (conn, res, field_type)); + *res_val_str = strdup(get_field_str(conn, res, field_type)); else - val = get_field (conn, res, &field_type); + val = get_field(conn, res, &field_type); } *res_val = val; if (field_type == DBI_TYPE_ERROR) { - CHECK_IGNORE_ERROR (STATE_OK); - np_dbi_print_error (conn, "CRITICAL - failed to fetch data"); + CHECK_IGNORE_ERROR(STATE_OK); + np_dbi_print_error(conn, "CRITICAL - failed to fetch data"); return STATE_CRITICAL; } - dbi_result_free (res); + dbi_result_free(res); return STATE_OK; } #undef CHECK_IGNORE_ERROR -int -do_query (dbi_conn conn, const char **res_val_str, double *res_val, double *res_time) -{ +int do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *res_time) { dbi_result res; struct timeval timeval_start, timeval_end; int status = STATE_OK; - assert (np_dbi_query); + assert(np_dbi_query); if (verbose) - printf ("Executing query '%s'\n", np_dbi_query); + printf("Executing query '%s'\n", np_dbi_query); - gettimeofday (&timeval_start, NULL); + gettimeofday(&timeval_start, NULL); - res = dbi_conn_query (conn, np_dbi_query); - if (! res) { - np_dbi_print_error (conn, "CRITICAL - failed to execute query '%s'", np_dbi_query); + res = dbi_conn_query(conn, np_dbi_query); + if (!res) { + np_dbi_print_error(conn, "CRITICAL - failed to execute query '%s'", np_dbi_query); return STATE_CRITICAL; } - status = get_query_result (conn, res, res_val_str, res_val); + status = get_query_result(conn, res, res_val_str, res_val); - gettimeofday (&timeval_end, NULL); - *res_time = timediff (timeval_start, timeval_end); + gettimeofday(&timeval_end, NULL); + *res_time = timediff(timeval_start, timeval_end); if (verbose) - printf ("Time elapsed: %f\n", *res_time); + printf("Time elapsed: %f\n", *res_time); return status; } -double -timediff (struct timeval start, struct timeval end) -{ +double timediff(struct timeval start, struct timeval end) { double diff; while (start.tv_usec > end.tv_usec) { --end.tv_sec; end.tv_usec += 1000000; } - diff = (double)(end.tv_sec - start.tv_sec) - + (double)(end.tv_usec - start.tv_usec) / 1000000.0; + diff = (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.0; return diff; } -void -np_dbi_print_error (dbi_conn conn, char *fmt, ...) -{ +void np_dbi_print_error(dbi_conn conn, char *fmt, ...) { const char *errmsg = NULL; va_list ap; - va_start (ap, fmt); + va_start(ap, fmt); - dbi_conn_error (conn, &errmsg); - vprintf (fmt, ap); - printf (": %s\n", errmsg); + dbi_conn_error(conn, &errmsg); + vprintf(fmt, ap); + printf(": %s\n", errmsg); - va_end (ap); + va_end(ap); } - -- cgit v1.2.3-74-g34f1 From 267c6689813d6acac60a8cb4dce1e58055f8471d Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:13:07 +0100 Subject: check_dbi: Update copyright --- plugins/check_dbi.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c index 0c0ed6d7..cb7c8818 100644 --- a/plugins/check_dbi.c +++ b/plugins/check_dbi.c @@ -3,8 +3,8 @@ * Monitoring check_dbi plugin * * License: GPL - * Copyright (c) 2011 Monitoring Plugins Development Team - * Author: Sebastian 'tokkee' Harl + * Copyright (c) 2011-2024 Monitoring Plugins Development Team + * Original Author: Sebastian 'tokkee' Harl * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_dbi"; -const char *copyright = "2011"; +const char *copyright = "2011-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From 981f1d562990d96001a88ea1227bc047561879c7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:15:12 +0100 Subject: check_dbi: do not export local symbols --- plugins/check_dbi.c | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c index cb7c8818..e8964482 100644 --- a/plugins/check_dbi.c +++ b/plugins/check_dbi.c @@ -70,38 +70,38 @@ typedef struct { char *value; } driver_option_t; -char *host = NULL; -int verbose = 0; +static char *host = NULL; +static int verbose = 0; -char *warning_range = NULL; -char *critical_range = NULL; -thresholds *dbi_thresholds = NULL; +static char *warning_range = NULL; +static char *critical_range = NULL; +static thresholds *dbi_thresholds = NULL; -char *expect = NULL; +static char *expect = NULL; -regex_t expect_re; -char *expect_re_str = NULL; -int expect_re_cflags = 0; +static regex_t expect_re; +static char *expect_re_str = NULL; +static int expect_re_cflags = 0; -np_dbi_metric_t metric = METRIC_QUERY_RESULT; -np_dbi_type_t type = TYPE_NUMERIC; +static np_dbi_metric_t metric = METRIC_QUERY_RESULT; +static np_dbi_type_t type = TYPE_NUMERIC; -char *np_dbi_driver = NULL; -driver_option_t *np_dbi_options = NULL; -int np_dbi_options_num = 0; -char *np_dbi_database = NULL; -char *np_dbi_query = NULL; +static char *np_dbi_driver = NULL; +static driver_option_t *np_dbi_options = NULL; +static int np_dbi_options_num = 0; +static char *np_dbi_database = NULL; +static char *np_dbi_query = NULL; -int process_arguments(int, char **); -int validate_arguments(void); +static int process_arguments(int, char **); +static int validate_arguments(void); void print_usage(void); -void print_help(void); +static void print_help(void); -double timediff(struct timeval, struct timeval); +static double timediff(struct timeval, struct timeval); -void np_dbi_print_error(dbi_conn, char *, ...); +static void np_dbi_print_error(dbi_conn, char *, ...); -int do_query(dbi_conn, const char **, double *, double *); +static int do_query(dbi_conn, const char **, double *, double *); int main(int argc, char **argv) { int status = STATE_UNKNOWN; -- cgit v1.2.3-74-g34f1 From 79d7f401612d390d3a4975139da524043bdc43a7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:17:20 +0100 Subject: check_dbi: linter fixes --- plugins/check_dbi.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c index e8964482..96575672 100644 --- a/plugins/check_dbi.c +++ b/plugins/check_dbi.c @@ -111,7 +111,8 @@ int main(int argc, char **argv) { unsigned int server_version; - struct timeval start_timeval, end_timeval; + struct timeval start_timeval; + struct timeval end_timeval; double conn_time = 0.0; double query_time = 0.0; @@ -202,7 +203,8 @@ int main(int argc, char **argv) { } if (verbose) { - const char *dbname, *host; + const char *dbname; + const char *host; dbname = dbi_conn_get_option(conn, "dbname"); host = dbi_conn_get_option(conn, "host"); @@ -424,7 +426,8 @@ int process_arguments(int argc, char **argv) { case 'o': { driver_option_t *new; - char *k, *v; + char *k; + char *v; k = optarg; v = strchr(k, (int)'='); @@ -462,7 +465,7 @@ int process_arguments(int argc, char **argv) { return validate_arguments(); } -int validate_arguments() { +int validate_arguments(void) { if (!np_dbi_driver) usage("Must specify a DBI driver"); @@ -639,7 +642,8 @@ double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type) { printf("CRITICAL - result value is not a numeric: %s\n", val_str); *field_type = DBI_TYPE_ERROR; return NAN; - } else if ((endptr != NULL) && (*endptr != '\0')) { + } + if ((endptr != NULL) && (*endptr != '\0')) { if (verbose) printf("Garbage after value: %s\n", endptr); } @@ -716,7 +720,8 @@ double get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str, int do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *res_time) { dbi_result res; - struct timeval timeval_start, timeval_end; + struct timeval timeval_start; + struct timeval timeval_end; int status = STATE_OK; assert(np_dbi_query); -- cgit v1.2.3-74-g34f1 From 904d1ef78dabae2e9fb1f57dfb7d43ecdf294fd3 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:19:50 +0100 Subject: check_dig: clang-format --- plugins/check_dig.c | 622 +++++++++++++++++++++++++--------------------------- 1 file changed, 297 insertions(+), 325 deletions(-) diff --git a/plugins/check_dig.c b/plugins/check_dig.c index be7a6101..37e0e243 100644 --- a/plugins/check_dig.c +++ b/plugins/check_dig.c @@ -1,30 +1,30 @@ /***************************************************************************** -* -* Monitoring check_dig plugin -* -* License: GPL -* Copyright (c) 2002-2008 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_dig plugin -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_dig plugin + * + * License: GPL + * Copyright (c) 2002-2008 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_dig plugin + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ /* Hackers note: * There are typecasts to (char *) from _("foo bar") in this file. @@ -41,13 +41,13 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "runcmd.h" -int process_arguments (int, char **); -int validate_arguments (void); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_help(void); +void print_usage(void); -#define UNDEFINED 0 -#define DEFAULT_PORT 53 +#define UNDEFINED 0 +#define DEFAULT_PORT 53 #define DEFAULT_TRIES 2 char *query_address = NULL; @@ -63,318 +63,290 @@ double warning_interval = UNDEFINED; double critical_interval = UNDEFINED; struct timeval tv; -int -main (int argc, char **argv) -{ - char *command_line; - output chld_out, chld_err; - char *msg = NULL; - size_t i; - char *t; - long microsec; - double elapsed_time; - int result = STATE_UNKNOWN; - int timeout_interval_dig; - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - /* Set signal handling and alarm */ - if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) - usage_va(_("Cannot catch SIGALRM")); - - /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); - - if (process_arguments (argc, argv) == ERROR) - usage_va(_("Could not parse arguments")); - - /* dig applies the timeout to each try, so we need to work around this */ - timeout_interval_dig = timeout_interval / number_tries + number_tries; - - /* get the command to run */ - xasprintf (&command_line, "%s %s %s -p %d @%s %s %s +retry=%d +time=%d", - PATH_TO_DIG, dig_args, query_transport, server_port, dns_server, query_address, record_type, number_tries, timeout_interval_dig); - - alarm (timeout_interval); - gettimeofday (&tv, NULL); - - if (verbose) { - printf ("%s\n", command_line); - if(expected_address != NULL) { - printf (_("Looking for: '%s'\n"), expected_address); - } else { - printf (_("Looking for: '%s'\n"), query_address); - } - } - - /* run the command */ - if(np_runcmd(command_line, &chld_out, &chld_err, 0) != 0) { - result = STATE_WARNING; - msg = (char *)_("dig returned an error status"); - } - - for(i = 0; i < chld_out.lines; i++) { - /* the server is responding, we just got the host name... */ - if (strstr (chld_out.line[i], ";; ANSWER SECTION:")) { - - /* loop through the whole 'ANSWER SECTION' */ - for(; i < chld_out.lines; i++) { - /* get the host address */ - if (verbose) - printf ("%s\n", chld_out.line[i]); - - if (strcasestr (chld_out.line[i], (expected_address == NULL ? query_address : expected_address)) != NULL) { - msg = chld_out.line[i]; - result = STATE_OK; - - /* Translate output TAB -> SPACE */ - t = msg; - while ((t = strchr(t, '\t')) != NULL) *t = ' '; - break; - } - } - - if (result == STATE_UNKNOWN) { - msg = (char *)_("Server not found in ANSWER SECTION"); - result = STATE_WARNING; - } - - /* we found the answer section, so break out of the loop */ - break; - } - } - - if (result == STATE_UNKNOWN) { - msg = (char *)_("No ANSWER SECTION found"); - result = STATE_CRITICAL; - } - - /* If we get anything on STDERR, at least set warning */ - if(chld_err.buflen > 0) { - result = max_state(result, STATE_WARNING); - if(!msg) for(i = 0; i < chld_err.lines; i++) { - msg = strchr(chld_err.line[0], ':'); - if(msg) { - msg++; - break; - } - } - } - - microsec = deltime (tv); - elapsed_time = (double)microsec / 1.0e6; - - if (critical_interval > UNDEFINED && elapsed_time > critical_interval) - result = STATE_CRITICAL; - - else if (warning_interval > UNDEFINED && elapsed_time > warning_interval) - result = STATE_WARNING; - - printf ("DNS %s - %.3f seconds response time (%s)|%s\n", - state_text (result), elapsed_time, - msg ? msg : _("Probably a non-existent host/domain"), - fperfdata("time", elapsed_time, "s", - (warning_interval>UNDEFINED ? true:false), - warning_interval, - (critical_interval>UNDEFINED ? true:false), - critical_interval, - true, 0, false, 0)); - return result; +int main(int argc, char **argv) { + char *command_line; + output chld_out, chld_err; + char *msg = NULL; + size_t i; + char *t; + long microsec; + double elapsed_time; + int result = STATE_UNKNOWN; + int timeout_interval_dig; + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + /* Set signal handling and alarm */ + if (signal(SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) + usage_va(_("Cannot catch SIGALRM")); + + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); + + if (process_arguments(argc, argv) == ERROR) + usage_va(_("Could not parse arguments")); + + /* dig applies the timeout to each try, so we need to work around this */ + timeout_interval_dig = timeout_interval / number_tries + number_tries; + + /* get the command to run */ + xasprintf(&command_line, "%s %s %s -p %d @%s %s %s +retry=%d +time=%d", PATH_TO_DIG, dig_args, query_transport, server_port, dns_server, + query_address, record_type, number_tries, timeout_interval_dig); + + alarm(timeout_interval); + gettimeofday(&tv, NULL); + + if (verbose) { + printf("%s\n", command_line); + if (expected_address != NULL) { + printf(_("Looking for: '%s'\n"), expected_address); + } else { + printf(_("Looking for: '%s'\n"), query_address); + } + } + + /* run the command */ + if (np_runcmd(command_line, &chld_out, &chld_err, 0) != 0) { + result = STATE_WARNING; + msg = (char *)_("dig returned an error status"); + } + + for (i = 0; i < chld_out.lines; i++) { + /* the server is responding, we just got the host name... */ + if (strstr(chld_out.line[i], ";; ANSWER SECTION:")) { + + /* loop through the whole 'ANSWER SECTION' */ + for (; i < chld_out.lines; i++) { + /* get the host address */ + if (verbose) + printf("%s\n", chld_out.line[i]); + + if (strcasestr(chld_out.line[i], (expected_address == NULL ? query_address : expected_address)) != NULL) { + msg = chld_out.line[i]; + result = STATE_OK; + + /* Translate output TAB -> SPACE */ + t = msg; + while ((t = strchr(t, '\t')) != NULL) + *t = ' '; + break; + } + } + + if (result == STATE_UNKNOWN) { + msg = (char *)_("Server not found in ANSWER SECTION"); + result = STATE_WARNING; + } + + /* we found the answer section, so break out of the loop */ + break; + } + } + + if (result == STATE_UNKNOWN) { + msg = (char *)_("No ANSWER SECTION found"); + result = STATE_CRITICAL; + } + + /* If we get anything on STDERR, at least set warning */ + if (chld_err.buflen > 0) { + result = max_state(result, STATE_WARNING); + if (!msg) + for (i = 0; i < chld_err.lines; i++) { + msg = strchr(chld_err.line[0], ':'); + if (msg) { + msg++; + break; + } + } + } + + microsec = deltime(tv); + elapsed_time = (double)microsec / 1.0e6; + + if (critical_interval > UNDEFINED && elapsed_time > critical_interval) + result = STATE_CRITICAL; + + else if (warning_interval > UNDEFINED && elapsed_time > warning_interval) + result = STATE_WARNING; + + printf("DNS %s - %.3f seconds response time (%s)|%s\n", state_text(result), elapsed_time, + msg ? msg : _("Probably a non-existent host/domain"), + fperfdata("time", elapsed_time, "s", (warning_interval > UNDEFINED ? true : false), warning_interval, + (critical_interval > UNDEFINED ? true : false), critical_interval, true, 0, false, 0)); + return result; } - - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ - int c; - - int option = 0; - static struct option longopts[] = { - {"hostname", required_argument, 0, 'H'}, - {"query_address", required_argument, 0, 'l'}, - {"warning", required_argument, 0, 'w'}, - {"critical", required_argument, 0, 'c'}, - {"timeout", required_argument, 0, 't'}, - {"dig-arguments", required_argument, 0, 'A'}, - {"verbose", no_argument, 0, 'v'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {"record_type", required_argument, 0, 'T'}, - {"expected_address", required_argument, 0, 'a'}, - {"port", required_argument, 0, 'p'}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {0, 0, 0, 0} - }; - - if (argc < 2) - return ERROR; - - while (1) { - c = getopt_long (argc, argv, "hVvt:l:H:w:c:T:p:a:A:46", longopts, &option); - - if (c == -1 || c == EOF) - break; - - switch (c) { - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'H': /* hostname */ - host_or_die(optarg); - dns_server = optarg; - break; - case 'p': /* server port */ - if (is_intpos (optarg)) { - server_port = atoi (optarg); - } - else { - usage_va(_("Port must be a positive integer - %s"), optarg); - } - break; - case 'l': /* address to lookup */ - query_address = optarg; - break; - case 'w': /* warning */ - if (is_nonnegative (optarg)) { - warning_interval = strtod (optarg, NULL); - } - else { - usage_va(_("Warning interval must be a positive integer - %s"), optarg); - } - break; - case 'c': /* critical */ - if (is_nonnegative (optarg)) { - critical_interval = strtod (optarg, NULL); - } - else { - usage_va(_("Critical interval must be a positive integer - %s"), optarg); - } - break; - case 't': /* timeout */ - if (is_intnonneg (optarg)) { - timeout_interval = atoi (optarg); - } - else { - usage_va(_("Timeout interval must be a positive integer - %s"), optarg); - } - break; - case 'A': /* dig arguments */ - dig_args = strdup(optarg); - break; - case 'v': /* verbose */ - verbose = true; - break; - case 'T': - record_type = optarg; - break; - case 'a': - expected_address = optarg; - break; - case '4': - query_transport = "-4"; - break; - case '6': - query_transport = "-6"; - break; - default: /* usage5 */ - usage5(); - } - } - - c = optind; - if (dns_server == NULL) { - if (c < argc) { - host_or_die(argv[c]); - dns_server = argv[c]; - } - else { - if (strcmp(query_transport,"-6") == 0) - dns_server = strdup("::1"); - else - dns_server = strdup ("127.0.0.1"); - } - } - - return validate_arguments (); +int process_arguments(int argc, char **argv) { + int c; + + int option = 0; + static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, + {"query_address", required_argument, 0, 'l'}, + {"warning", required_argument, 0, 'w'}, + {"critical", required_argument, 0, 'c'}, + {"timeout", required_argument, 0, 't'}, + {"dig-arguments", required_argument, 0, 'A'}, + {"verbose", no_argument, 0, 'v'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {"record_type", required_argument, 0, 'T'}, + {"expected_address", required_argument, 0, 'a'}, + {"port", required_argument, 0, 'p'}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {0, 0, 0, 0}}; + + if (argc < 2) + return ERROR; + + while (1) { + c = getopt_long(argc, argv, "hVvt:l:H:w:c:T:p:a:A:46", longopts, &option); + + if (c == -1 || c == EOF) + break; + + switch (c) { + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'H': /* hostname */ + host_or_die(optarg); + dns_server = optarg; + break; + case 'p': /* server port */ + if (is_intpos(optarg)) { + server_port = atoi(optarg); + } else { + usage_va(_("Port must be a positive integer - %s"), optarg); + } + break; + case 'l': /* address to lookup */ + query_address = optarg; + break; + case 'w': /* warning */ + if (is_nonnegative(optarg)) { + warning_interval = strtod(optarg, NULL); + } else { + usage_va(_("Warning interval must be a positive integer - %s"), optarg); + } + break; + case 'c': /* critical */ + if (is_nonnegative(optarg)) { + critical_interval = strtod(optarg, NULL); + } else { + usage_va(_("Critical interval must be a positive integer - %s"), optarg); + } + break; + case 't': /* timeout */ + if (is_intnonneg(optarg)) { + timeout_interval = atoi(optarg); + } else { + usage_va(_("Timeout interval must be a positive integer - %s"), optarg); + } + break; + case 'A': /* dig arguments */ + dig_args = strdup(optarg); + break; + case 'v': /* verbose */ + verbose = true; + break; + case 'T': + record_type = optarg; + break; + case 'a': + expected_address = optarg; + break; + case '4': + query_transport = "-4"; + break; + case '6': + query_transport = "-6"; + break; + default: /* usage5 */ + usage5(); + } + } + + c = optind; + if (dns_server == NULL) { + if (c < argc) { + host_or_die(argv[c]); + dns_server = argv[c]; + } else { + if (strcmp(query_transport, "-6") == 0) + dns_server = strdup("::1"); + else + dns_server = strdup("127.0.0.1"); + } + } + + return validate_arguments(); } - - -int -validate_arguments (void) -{ - if (query_address != NULL) - return OK; - else - return ERROR; +int validate_arguments(void) { + if (query_address != NULL) + return OK; + else + return ERROR; } +void print_help(void) { + char *myport; + xasprintf(&myport, "%d", DEFAULT_PORT); -void -print_help (void) -{ - char *myport; + print_revision(progname, NP_VERSION); - xasprintf (&myport, "%d", DEFAULT_PORT); + printf("Copyright (c) 2000 Karl DeBisschop \n"); + printf(COPYRIGHT, copyright, email); - print_revision (progname, NP_VERSION); + printf(_("This plugin tests the DNS service on the specified host using dig")); - printf ("Copyright (c) 2000 Karl DeBisschop \n"); - printf (COPYRIGHT, copyright, email); + printf("\n\n"); - printf (_("This plugin tests the DNS service on the specified host using dig")); + print_usage(); - printf ("\n\n"); + printf(UT_HELP_VRSN); - print_usage (); + printf(UT_EXTRA_OPTS); - printf (UT_HELP_VRSN); + printf(UT_HOST_PORT, 'p', myport); - printf (UT_EXTRA_OPTS); + printf(" %s\n", "-4, --use-ipv4"); + printf(" %s\n", _("Force dig to only use IPv4 query transport")); + printf(" %s\n", "-6, --use-ipv6"); + printf(" %s\n", _("Force dig to only use IPv6 query transport")); + printf(" %s\n", "-l, --query_address=STRING"); + printf(" %s\n", _("Machine name to lookup")); + printf(" %s\n", "-T, --record_type=STRING"); + printf(" %s\n", _("Record type to lookup (default: A)")); + printf(" %s\n", "-a, --expected_address=STRING"); + printf(" %s\n", _("An address expected to be in the answer section. If not set, uses whatever")); + printf(" %s\n", _("was in -l")); + printf(" %s\n", "-A, --dig-arguments=STRING"); + printf(" %s\n", _("Pass STRING as argument(s) to dig")); + printf(UT_WARN_CRIT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_VERBOSE); - printf (UT_HOST_PORT, 'p', myport); + printf("\n"); + printf("%s\n", _("Examples:")); + printf(" %s\n", "check_dig -H DNSSERVER -l www.example.com -A \"+tcp\""); + printf(" %s\n", "This will send a tcp query to DNSSERVER for www.example.com"); - printf (" %s\n","-4, --use-ipv4"); - printf (" %s\n",_("Force dig to only use IPv4 query transport")); - printf (" %s\n","-6, --use-ipv6"); - printf (" %s\n",_("Force dig to only use IPv6 query transport")); - printf (" %s\n","-l, --query_address=STRING"); - printf (" %s\n",_("Machine name to lookup")); - printf (" %s\n","-T, --record_type=STRING"); - printf (" %s\n",_("Record type to lookup (default: A)")); - printf (" %s\n","-a, --expected_address=STRING"); - printf (" %s\n",_("An address expected to be in the answer section. If not set, uses whatever")); - printf (" %s\n",_("was in -l")); - printf (" %s\n","-A, --dig-arguments=STRING"); - printf (" %s\n",_("Pass STRING as argument(s) to dig")); - printf (UT_WARN_CRIT); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf (UT_VERBOSE); - - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n", "check_dig -H DNSSERVER -l www.example.com -A \"+tcp\""); - printf (" %s\n", "This will send a tcp query to DNSSERVER for www.example.com"); - - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -l [-H ] [-p ]\n", progname); - printf (" [-T ] [-w ] [-c ]\n"); - printf (" [-t ] [-a ] [-v]\n"); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -l [-H ] [-p ]\n", progname); + printf(" [-T ] [-w ] [-c ]\n"); + printf(" [-t ] [-a ] [-v]\n"); } -- cgit v1.2.3-74-g34f1 From f0d780384219dabb5b7ad569a7dfb3576b199230 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:21:37 +0100 Subject: check_dig: do not export local symbols --- plugins/check_dig.c | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/plugins/check_dig.c b/plugins/check_dig.c index 37e0e243..e5f99930 100644 --- a/plugins/check_dig.c +++ b/plugins/check_dig.c @@ -41,27 +41,27 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "runcmd.h" -int process_arguments(int, char **); -int validate_arguments(void); -void print_help(void); +static int process_arguments(int /*argc*/, char ** /*argv*/); +static int validate_arguments(void); +static void print_help(void); void print_usage(void); #define UNDEFINED 0 #define DEFAULT_PORT 53 #define DEFAULT_TRIES 2 -char *query_address = NULL; -char *record_type = "A"; -char *expected_address = NULL; -char *dns_server = NULL; -char *dig_args = ""; -char *query_transport = ""; -bool verbose = false; -int server_port = DEFAULT_PORT; -int number_tries = DEFAULT_TRIES; -double warning_interval = UNDEFINED; -double critical_interval = UNDEFINED; -struct timeval tv; +static char *query_address = NULL; +static char *record_type = "A"; +static char *expected_address = NULL; +static char *dns_server = NULL; +static char *dig_args = ""; +static char *query_transport = ""; +static bool verbose = false; +static int server_port = DEFAULT_PORT; +static int number_tries = DEFAULT_TRIES; +static double warning_interval = UNDEFINED; +static double critical_interval = UNDEFINED; +static struct timeval tv; int main(int argc, char **argv) { char *command_line; -- cgit v1.2.3-74-g34f1 From acb19fe8f7acaeccb3fe0c1cb11e8ab5fd5e8a1b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:22:43 +0100 Subject: check_dig: Linter fixes --- plugins/check_dig.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/check_dig.c b/plugins/check_dig.c index e5f99930..4d89ca86 100644 --- a/plugins/check_dig.c +++ b/plugins/check_dig.c @@ -65,7 +65,8 @@ static struct timeval tv; int main(int argc, char **argv) { char *command_line; - output chld_out, chld_err; + output chld_out; + output chld_err; char *msg = NULL; size_t i; char *t; @@ -293,8 +294,7 @@ int process_arguments(int argc, char **argv) { int validate_arguments(void) { if (query_address != NULL) return OK; - else - return ERROR; + return ERROR; } void print_help(void) { -- cgit v1.2.3-74-g34f1 From 25e0c67b0972b9bef426ebf6ca11ee191df74cff Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:24:02 +0100 Subject: check_disk: clang-format --- plugins/check_disk.c | 1963 +++++++++++++++++++++++++------------------------- 1 file changed, 962 insertions(+), 1001 deletions(-) diff --git a/plugins/check_disk.c b/plugins/check_disk.c index b3dd301c..fc4039f1 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -1,43 +1,42 @@ /***************************************************************************** -* -* Monitoring check_disk plugin -* -* License: GPL -* Copyright (c) 1999-2008 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_disk plugin -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_disk plugin + * + * License: GPL + * Copyright (c) 1999-2008 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_disk plugin + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_disk"; -const char *program_name = "check_disk"; /* Required for coreutils libs */ +const char *program_name = "check_disk"; /* Required for coreutils libs */ const char *copyright = "1999-2008"; const char *email = "devel@monitoring-plugins.org"; - #include "common.h" #ifdef HAVE_SYS_STAT_H -# include +# include #endif #if HAVE_INTTYPES_H -# include +# include #endif #include #include "popen.h" @@ -48,14 +47,14 @@ const char *email = "devel@monitoring-plugins.org"; #include "mountlist.h" #include #if HAVE_LIMITS_H -# include +# include #endif #include "regex.h" #ifdef __CYGWIN__ -# include -# undef ERROR -# define ERROR -1 +# include +# undef ERROR +# define ERROR -1 #endif /* If nonzero, show even filesystems with zero size or @@ -108,25 +107,24 @@ static struct mount_entry *mount_list; /* For long options that have no equivalent short option, use a non-character as a pseudo short option, starting with CHAR_MAX + 1. */ -enum -{ - SYNC_OPTION = CHAR_MAX + 1, - NO_SYNC_OPTION, - BLOCK_SIZE_OPTION +enum { + SYNC_OPTION = CHAR_MAX + 1, + NO_SYNC_OPTION, + BLOCK_SIZE_OPTION }; #ifdef _AIX -#pragma alloca +# pragma alloca #endif -static int process_arguments (int, char **); -static void set_all_thresholds (struct parameter_list *path); -static void print_help (void); -void print_usage (void); +static int process_arguments(int, char **); +static void set_all_thresholds(struct parameter_list *path); +static void print_help(void); +void print_usage(void); static double calculate_percent(uintmax_t, uintmax_t); -static bool stat_path (struct parameter_list *p); -static void get_stats (struct parameter_list *p, struct fs_usage *fsp); -static void get_path_stats (struct parameter_list *p, struct fs_usage *fsp); +static bool stat_path(struct parameter_list *p); +static void get_stats(struct parameter_list *p, struct fs_usage *fsp); +static void get_path_stats(struct parameter_list *p, struct fs_usage *fsp); static char *units; static uintmax_t mult = 1024 * 1024; @@ -155,992 +153,955 @@ static char *group = NULL; static struct stat *stat_buf; static struct name_list *seen = NULL; - -int -main (int argc, char **argv) -{ - int result = STATE_UNKNOWN; - int disk_result = STATE_UNKNOWN; - char *output; - char *ignored; - char *details; - char *perf; - char *perf_ilabel; - char *preamble = " - free space:"; - char *ignored_preamble = " - ignored paths:"; - char *flag_header; - int temp_result; - - struct mount_entry *me; - struct fs_usage fsp; - struct parameter_list *temp_list, *path; +int main(int argc, char **argv) { + int result = STATE_UNKNOWN; + int disk_result = STATE_UNKNOWN; + char *output; + char *ignored; + char *details; + char *perf; + char *perf_ilabel; + char *preamble = " - free space:"; + char *ignored_preamble = " - ignored paths:"; + char *flag_header; + int temp_result; + + struct mount_entry *me; + struct fs_usage fsp; + struct parameter_list *temp_list, *path; #ifdef __CYGWIN__ - char mountdir[32]; + char mountdir[32]; #endif - output = strdup (""); - ignored = strdup (""); - details = strdup (""); - perf = strdup (""); - perf_ilabel = strdup (""); - stat_buf = malloc(sizeof *stat_buf); - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - mount_list = read_file_system_list (0); - - /* Parse extra opts if any */ - argv = np_extra_opts (&argc, argv, progname); - - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); - - /* If a list of paths has not been selected, find entire - mount list and create list of paths - */ - if (path_selected == false && path_ignored == false) { - for (me = mount_list; me; me = me->me_next) { - if (! (path = np_find_parameter(path_select_list, me->me_mountdir))) { - path = np_add_parameter(&path_select_list, me->me_mountdir); - } - path->best_match = me; - path->group = group; - set_all_thresholds(path); - } - } - - if (path_ignored == false) { - np_set_best_match(path_select_list, mount_list, exact_match); - } - - /* Error if no match found for specified paths */ - temp_list = path_select_list; - - while (path_select_list) { - if (! path_select_list->best_match && ignore_missing == true) { - /* If the first element will be deleted, the temp_list must be updated with the new start address as well */ - if (path_select_list == temp_list) { - temp_list = path_select_list->name_next; - } - /* Add path argument to list of ignored paths to inform about missing paths being ignored and not alerted */ - xasprintf (&ignored, "%s %s;", ignored, path_select_list->name); - /* Delete the path from the list so that it is not stat-checked later in the code. */ - path_select_list = np_del_parameter(path_select_list, path_select_list->name_prev); - } else if (! path_select_list->best_match) { - /* Without --ignore-missing option, exit with Critical state. */ - die (STATE_CRITICAL, _("DISK %s: %s not found\n"), _("CRITICAL"), path_select_list->name); - } else { - /* Continue jumping through the list */ - path_select_list = path_select_list->name_next; - } - } - - path_select_list = temp_list; - - if (! path_select_list && ignore_missing == true) { - result = STATE_OK; - if (verbose >= 2) { - printf ("None of the provided paths were found\n"); - } - } - - /* Process for every path in list */ - for (path = path_select_list; path; path=path->name_next) { - if (verbose >= 3 && path->freespace_percent->warning != NULL && path->freespace_percent->critical != NULL) - printf("Thresholds(pct) for %s warn: %f crit %f\n", - path->name, - path->freespace_percent->warning->end, - path->freespace_percent->critical->end); - - if (verbose >= 3 && path->group != NULL) - printf("Group of %s: %s\n",path->name,path->group); - - /* reset disk result */ - disk_result = STATE_UNKNOWN; - - me = path->best_match; - - if (!me) { - continue; - } + output = strdup(""); + ignored = strdup(""); + details = strdup(""); + perf = strdup(""); + perf_ilabel = strdup(""); + stat_buf = malloc(sizeof *stat_buf); + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + mount_list = read_file_system_list(0); + + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); + + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); + + /* If a list of paths has not been selected, find entire + mount list and create list of paths + */ + if (path_selected == false && path_ignored == false) { + for (me = mount_list; me; me = me->me_next) { + if (!(path = np_find_parameter(path_select_list, me->me_mountdir))) { + path = np_add_parameter(&path_select_list, me->me_mountdir); + } + path->best_match = me; + path->group = group; + set_all_thresholds(path); + } + } + + if (path_ignored == false) { + np_set_best_match(path_select_list, mount_list, exact_match); + } + + /* Error if no match found for specified paths */ + temp_list = path_select_list; + + while (path_select_list) { + if (!path_select_list->best_match && ignore_missing == true) { + /* If the first element will be deleted, the temp_list must be updated with the new start address as well */ + if (path_select_list == temp_list) { + temp_list = path_select_list->name_next; + } + /* Add path argument to list of ignored paths to inform about missing paths being ignored and not alerted */ + xasprintf(&ignored, "%s %s;", ignored, path_select_list->name); + /* Delete the path from the list so that it is not stat-checked later in the code. */ + path_select_list = np_del_parameter(path_select_list, path_select_list->name_prev); + } else if (!path_select_list->best_match) { + /* Without --ignore-missing option, exit with Critical state. */ + die(STATE_CRITICAL, _("DISK %s: %s not found\n"), _("CRITICAL"), path_select_list->name); + } else { + /* Continue jumping through the list */ + path_select_list = path_select_list->name_next; + } + } + + path_select_list = temp_list; + + if (!path_select_list && ignore_missing == true) { + result = STATE_OK; + if (verbose >= 2) { + printf("None of the provided paths were found\n"); + } + } + + /* Process for every path in list */ + for (path = path_select_list; path; path = path->name_next) { + if (verbose >= 3 && path->freespace_percent->warning != NULL && path->freespace_percent->critical != NULL) + printf("Thresholds(pct) for %s warn: %f crit %f\n", path->name, path->freespace_percent->warning->end, + path->freespace_percent->critical->end); + + if (verbose >= 3 && path->group != NULL) + printf("Group of %s: %s\n", path->name, path->group); + + /* reset disk result */ + disk_result = STATE_UNKNOWN; + + me = path->best_match; + + if (!me) { + continue; + } #ifdef __CYGWIN__ - if (strncmp(path->name, "/cygdrive/", 10) != 0 || strlen(path->name) > 11) - continue; - snprintf(mountdir, sizeof(mountdir), "%s:\\", me->me_mountdir + 10); - if (GetDriveType(mountdir) != DRIVE_FIXED) - me->me_remote = 1; + if (strncmp(path->name, "/cygdrive/", 10) != 0 || strlen(path->name) > 11) + continue; + snprintf(mountdir, sizeof(mountdir), "%s:\\", me->me_mountdir + 10); + if (GetDriveType(mountdir) != DRIVE_FIXED) + me->me_remote = 1; #endif - /* Filters */ - - /* Remove filesystems already seen */ - if (np_seen_name(seen, me->me_mountdir)) { - continue; - } - np_add_name(&seen, me->me_mountdir); - - if (path->group == NULL) { - /* Skip remote filesystems if we're not interested in them */ - if (me->me_remote && show_local_fs) { - if (stat_remote_fs) { - if (!stat_path(path) && ignore_missing == true) { - result = STATE_OK; - xasprintf (&ignored, "%s %s;", ignored, path->name); - } - } - continue; - /* Skip pseudo fs's if we haven't asked for all fs's */ - } else if (me->me_dummy && !show_all_fs) { - continue; - /* Skip excluded fstypes */ - } else if (fs_exclude_list && np_find_regmatch (fs_exclude_list, me->me_type)) { - continue; - /* Skip excluded fs's */ - } else if (dp_exclude_list && - (np_find_name (dp_exclude_list, me->me_devname) || - np_find_name (dp_exclude_list, me->me_mountdir))) { - continue; - /* Skip not included fstypes */ - } else if (fs_include_list && !np_find_regmatch(fs_include_list, me->me_type)) { - continue; - } - } - - if (!stat_path(path)) { - if (ignore_missing == true) { - result = STATE_OK; - xasprintf (&ignored, "%s %s;", ignored, path->name); - } - continue; - } - get_fs_usage (me->me_mountdir, me->me_devname, &fsp); - - if (fsp.fsu_blocks && strcmp ("none", me->me_mountdir)) { - get_stats (path, &fsp); - - if (verbose >= 3) { - printf ("For %s, used_pct=%f free_pct=%f used_units=%lu free_units=%lu total_units=%lu used_inodes_pct=%f free_inodes_pct=%f fsp.fsu_blocksize=%lu mult=%lu\n", - me->me_mountdir, - path->dused_pct, - path->dfree_pct, - path->dused_units, - path->dfree_units, - path->dtotal_units, - path->dused_inodes_percent, - path->dfree_inodes_percent, - fsp.fsu_blocksize, - mult); - } - - /* Threshold comparisons */ - - temp_result = get_status(path->dfree_units, path->freespace_units); - if (verbose >=3) printf("Freespace_units result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - temp_result = get_status(path->dfree_pct, path->freespace_percent); - if (verbose >=3) printf("Freespace%% result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - temp_result = get_status(path->dused_units, path->usedspace_units); - if (verbose >=3) printf("Usedspace_units result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - temp_result = get_status(path->dused_pct, path->usedspace_percent); - if (verbose >=3) printf("Usedspace_percent result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - temp_result = get_status(path->dused_inodes_percent, path->usedinodes_percent); - if (verbose >=3) printf("Usedinodes_percent result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - temp_result = get_status(path->dfree_inodes_percent, path->freeinodes_percent); - if (verbose >=3) printf("Freeinodes_percent result=%d\n", temp_result); - disk_result = max_state( disk_result, temp_result ); - - result = max_state(result, disk_result); - - /* What a mess of units. The output shows free space, the perf data shows used space. Yikes! - Hack here. Trying to get warn/crit levels from freespace_(units|percent) for perf - data. Assumption that start=0. Roll on new syntax... - */ - - /* *_high_tide must be reinitialized at each run */ - uint64_t warning_high_tide = UINT64_MAX; - - if (path->freespace_units->warning != NULL) { - warning_high_tide = (path->dtotal_units - path->freespace_units->warning->end) * mult; - } - if (path->freespace_percent->warning != NULL) { - warning_high_tide = min( warning_high_tide, (uint64_t)((1.0 - path->freespace_percent->warning->end/100) * (path->dtotal_units * mult)) ); - } - - uint64_t critical_high_tide = UINT64_MAX; - - if (path->freespace_units->critical != NULL) { - critical_high_tide = (path->dtotal_units - path->freespace_units->critical->end) * mult; - } - if (path->freespace_percent->critical != NULL) { - critical_high_tide = min( critical_high_tide, (uint64_t)((1.0 - path->freespace_percent->critical->end/100) * (path->dtotal_units * mult)) ); - } - - /* Nb: *_high_tide are unset when == UINT64_MAX */ - xasprintf (&perf, "%s %s", perf, - perfdata_uint64 ( - (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, - path->dused_units * mult, "B", - (warning_high_tide == UINT64_MAX ? false : true), warning_high_tide, - (critical_high_tide == UINT64_MAX ? false : true), critical_high_tide, - true, 0, - true, path->dtotal_units * mult)); - - if (display_inodes_perfdata) { - /* *_high_tide must be reinitialized at each run */ - warning_high_tide = UINT64_MAX; - critical_high_tide = UINT64_MAX; - - if (path->freeinodes_percent->warning != NULL) { - warning_high_tide = (uint64_t) fabs( min( (double) warning_high_tide, (double) (1.0 - path->freeinodes_percent->warning->end/100)*path->inodes_total )); - } - if (path->freeinodes_percent->critical != NULL) { - critical_high_tide = (uint64_t) fabs( min( (double) critical_high_tide, (double) (1.0 - path->freeinodes_percent->critical->end/100)*path->inodes_total )); - } - - xasprintf (&perf_ilabel, "%s (inodes)", (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir); - /* Nb: *_high_tide are unset when == UINT64_MAX */ - xasprintf (&perf, "%s %s", perf, - perfdata_uint64 (perf_ilabel, - path->inodes_used, "", - (warning_high_tide != UINT64_MAX ? true : false), warning_high_tide, - (critical_high_tide != UINT64_MAX ? true : false), critical_high_tide, - true, 0, - true, path->inodes_total)); - } - - if (disk_result==STATE_OK && erronly && !verbose) - continue; - - if(disk_result && verbose >= 1) { - xasprintf(&flag_header, " %s [", state_text (disk_result)); - } else { - xasprintf(&flag_header, ""); - } - xasprintf (&output, "%s%s %s %llu%s (%.1f%%", - output, flag_header, - (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, - path->dfree_units, - units, - path->dfree_pct); - if (path->dused_inodes_percent < 0) { - xasprintf(&output, "%s inode=-)%s;", output, (disk_result ? "]" : "")); - } else { - xasprintf(&output, "%s inode=%.0f%%)%s;", output, path->dfree_inodes_percent, ((disk_result && verbose >= 1) ? "]" : "")); - } - free(flag_header); - } - } - - if (verbose >= 2) - xasprintf (&output, "%s%s", output, details); - - if (strcmp(output, "") == 0 && ! erronly) { - preamble = ""; - xasprintf (&output, " - No disks were found for provided parameters"); - } - - printf ("DISK %s%s%s%s%s|%s\n", state_text (result), ((erronly && result==STATE_OK)) ? "" : preamble, output, (strcmp(ignored, "") == 0) ? "" : ignored_preamble, ignored, perf); - return result; -} + /* Filters */ + + /* Remove filesystems already seen */ + if (np_seen_name(seen, me->me_mountdir)) { + continue; + } + np_add_name(&seen, me->me_mountdir); + + if (path->group == NULL) { + /* Skip remote filesystems if we're not interested in them */ + if (me->me_remote && show_local_fs) { + if (stat_remote_fs) { + if (!stat_path(path) && ignore_missing == true) { + result = STATE_OK; + xasprintf(&ignored, "%s %s;", ignored, path->name); + } + } + continue; + /* Skip pseudo fs's if we haven't asked for all fs's */ + } else if (me->me_dummy && !show_all_fs) { + continue; + /* Skip excluded fstypes */ + } else if (fs_exclude_list && np_find_regmatch(fs_exclude_list, me->me_type)) { + continue; + /* Skip excluded fs's */ + } else if (dp_exclude_list && + (np_find_name(dp_exclude_list, me->me_devname) || np_find_name(dp_exclude_list, me->me_mountdir))) { + continue; + /* Skip not included fstypes */ + } else if (fs_include_list && !np_find_regmatch(fs_include_list, me->me_type)) { + continue; + } + } + + if (!stat_path(path)) { + if (ignore_missing == true) { + result = STATE_OK; + xasprintf(&ignored, "%s %s;", ignored, path->name); + } + continue; + } + get_fs_usage(me->me_mountdir, me->me_devname, &fsp); + + if (fsp.fsu_blocks && strcmp("none", me->me_mountdir)) { + get_stats(path, &fsp); + + if (verbose >= 3) { + printf("For %s, used_pct=%f free_pct=%f used_units=%lu free_units=%lu total_units=%lu used_inodes_pct=%f " + "free_inodes_pct=%f fsp.fsu_blocksize=%lu mult=%lu\n", + me->me_mountdir, path->dused_pct, path->dfree_pct, path->dused_units, path->dfree_units, path->dtotal_units, + path->dused_inodes_percent, path->dfree_inodes_percent, fsp.fsu_blocksize, mult); + } + + /* Threshold comparisons */ + + temp_result = get_status(path->dfree_units, path->freespace_units); + if (verbose >= 3) + printf("Freespace_units result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + temp_result = get_status(path->dfree_pct, path->freespace_percent); + if (verbose >= 3) + printf("Freespace%% result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + temp_result = get_status(path->dused_units, path->usedspace_units); + if (verbose >= 3) + printf("Usedspace_units result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + temp_result = get_status(path->dused_pct, path->usedspace_percent); + if (verbose >= 3) + printf("Usedspace_percent result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + temp_result = get_status(path->dused_inodes_percent, path->usedinodes_percent); + if (verbose >= 3) + printf("Usedinodes_percent result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + temp_result = get_status(path->dfree_inodes_percent, path->freeinodes_percent); + if (verbose >= 3) + printf("Freeinodes_percent result=%d\n", temp_result); + disk_result = max_state(disk_result, temp_result); + + result = max_state(result, disk_result); + + /* What a mess of units. The output shows free space, the perf data shows used space. Yikes! + Hack here. Trying to get warn/crit levels from freespace_(units|percent) for perf + data. Assumption that start=0. Roll on new syntax... + */ + + /* *_high_tide must be reinitialized at each run */ + uint64_t warning_high_tide = UINT64_MAX; + + if (path->freespace_units->warning != NULL) { + warning_high_tide = (path->dtotal_units - path->freespace_units->warning->end) * mult; + } + if (path->freespace_percent->warning != NULL) { + warning_high_tide = + min(warning_high_tide, (uint64_t)((1.0 - path->freespace_percent->warning->end / 100) * (path->dtotal_units * mult))); + } + + uint64_t critical_high_tide = UINT64_MAX; + + if (path->freespace_units->critical != NULL) { + critical_high_tide = (path->dtotal_units - path->freespace_units->critical->end) * mult; + } + if (path->freespace_percent->critical != NULL) { + critical_high_tide = + min(critical_high_tide, (uint64_t)((1.0 - path->freespace_percent->critical->end / 100) * (path->dtotal_units * mult))); + } + + /* Nb: *_high_tide are unset when == UINT64_MAX */ + xasprintf(&perf, "%s %s", perf, + perfdata_uint64((!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, + path->dused_units * mult, "B", (warning_high_tide == UINT64_MAX ? false : true), warning_high_tide, + (critical_high_tide == UINT64_MAX ? false : true), critical_high_tide, true, 0, true, + path->dtotal_units * mult)); + + if (display_inodes_perfdata) { + /* *_high_tide must be reinitialized at each run */ + warning_high_tide = UINT64_MAX; + critical_high_tide = UINT64_MAX; + + if (path->freeinodes_percent->warning != NULL) { + warning_high_tide = (uint64_t)fabs( + min((double)warning_high_tide, (double)(1.0 - path->freeinodes_percent->warning->end / 100) * path->inodes_total)); + } + if (path->freeinodes_percent->critical != NULL) { + critical_high_tide = (uint64_t)fabs(min( + (double)critical_high_tide, (double)(1.0 - path->freeinodes_percent->critical->end / 100) * path->inodes_total)); + } + + xasprintf(&perf_ilabel, "%s (inodes)", + (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir); + /* Nb: *_high_tide are unset when == UINT64_MAX */ + xasprintf(&perf, "%s %s", perf, + perfdata_uint64(perf_ilabel, path->inodes_used, "", (warning_high_tide != UINT64_MAX ? true : false), + warning_high_tide, (critical_high_tide != UINT64_MAX ? true : false), critical_high_tide, true, 0, + true, path->inodes_total)); + } + + if (disk_result == STATE_OK && erronly && !verbose) + continue; + + if (disk_result && verbose >= 1) { + xasprintf(&flag_header, " %s [", state_text(disk_result)); + } else { + xasprintf(&flag_header, ""); + } + xasprintf(&output, "%s%s %s %llu%s (%.1f%%", output, flag_header, + (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir, path->dfree_units, units, + path->dfree_pct); + if (path->dused_inodes_percent < 0) { + xasprintf(&output, "%s inode=-)%s;", output, (disk_result ? "]" : "")); + } else { + xasprintf(&output, "%s inode=%.0f%%)%s;", output, path->dfree_inodes_percent, ((disk_result && verbose >= 1) ? "]" : "")); + } + free(flag_header); + } + } + + if (verbose >= 2) + xasprintf(&output, "%s%s", output, details); + if (strcmp(output, "") == 0 && !erronly) { + preamble = ""; + xasprintf(&output, " - No disks were found for provided parameters"); + } + + printf("DISK %s%s%s%s%s|%s\n", state_text(result), ((erronly && result == STATE_OK)) ? "" : preamble, output, + (strcmp(ignored, "") == 0) ? "" : ignored_preamble, ignored, perf); + return result; +} double calculate_percent(uintmax_t value, uintmax_t total) { - double pct = -1; - if(value <= DBL_MAX && total != 0) { - pct = (double)value / total * 100.0; - } - return pct; + double pct = -1; + if (value <= DBL_MAX && total != 0) { + pct = (double)value / total * 100.0; + } + return pct; } /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ - int c, err; - struct parameter_list *se; - struct parameter_list *temp_list = NULL, *previous = NULL; - struct mount_entry *me; - regex_t re; - int cflags = REG_NOSUB | REG_EXTENDED; - int default_cflags = cflags; - char errbuf[MAX_INPUT_BUFFER]; - int fnd = 0; - - int option = 0; - static struct option longopts[] = { - {"timeout", required_argument, 0, 't'}, - {"warning", required_argument, 0, 'w'}, - {"critical", required_argument, 0, 'c'}, - {"iwarning", required_argument, 0, 'W'}, - /* Dang, -C is taken. We might want to reshuffle this. */ - {"icritical", required_argument, 0, 'K'}, - {"kilobytes", no_argument, 0, 'k'}, - {"megabytes", no_argument, 0, 'm'}, - {"units", required_argument, 0, 'u'}, - {"path", required_argument, 0, 'p'}, - {"partition", required_argument, 0, 'p'}, - {"exclude_device", required_argument, 0, 'x'}, - {"exclude-type", required_argument, 0, 'X'}, - {"include-type", required_argument, 0, 'N'}, - {"group", required_argument, 0, 'g'}, - {"eregi-path", required_argument, 0, 'R'}, - {"eregi-partition", required_argument, 0, 'R'}, - {"ereg-path", required_argument, 0, 'r'}, - {"ereg-partition", required_argument, 0, 'r'}, - {"freespace-ignore-reserved", no_argument, 0, 'f'}, - {"ignore-ereg-path", required_argument, 0, 'i'}, - {"ignore-ereg-partition", required_argument, 0, 'i'}, - {"ignore-eregi-path", required_argument, 0, 'I'}, - {"ignore-eregi-partition", required_argument, 0, 'I'}, - {"ignore-missing", no_argument, 0, 'n'}, - {"local", no_argument, 0, 'l'}, - {"stat-remote-fs", no_argument, 0, 'L'}, - {"iperfdata", no_argument, 0, 'P'}, - {"mountpoint", no_argument, 0, 'M'}, - {"errors-only", no_argument, 0, 'e'}, - {"exact-match", no_argument, 0, 'E'}, - {"all", no_argument, 0, 'A'}, - {"verbose", no_argument, 0, 'v'}, - {"quiet", no_argument, 0, 'q'}, - {"clear", no_argument, 0, 'C'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} - }; - - if (argc < 2) - return ERROR; - - np_add_regex(&fs_exclude_list, "iso9660", REG_EXTENDED); - - for (c = 1; c < argc; c++) - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - - while (1) { - c = getopt_long (argc, argv, "+?VqhvefCt:c:w:K:W:u:p:x:X:N:mklLPg:R:r:i:I:MEAn", longopts, &option); - - if (c == -1 || c == EOF) - break; - - switch (c) { - case 't': /* timeout period */ - if (is_integer (optarg)) { - timeout_interval = atoi (optarg); - break; - } - else { - usage2 (_("Timeout interval must be a positive integer"), optarg); - } - - /* See comments for 'c' */ - case 'w': /* warning threshold */ +int process_arguments(int argc, char **argv) { + int c, err; + struct parameter_list *se; + struct parameter_list *temp_list = NULL, *previous = NULL; + struct mount_entry *me; + regex_t re; + int cflags = REG_NOSUB | REG_EXTENDED; + int default_cflags = cflags; + char errbuf[MAX_INPUT_BUFFER]; + int fnd = 0; + + int option = 0; + static struct option longopts[] = {{"timeout", required_argument, 0, 't'}, + {"warning", required_argument, 0, 'w'}, + {"critical", required_argument, 0, 'c'}, + {"iwarning", required_argument, 0, 'W'}, + /* Dang, -C is taken. We might want to reshuffle this. */ + {"icritical", required_argument, 0, 'K'}, + {"kilobytes", no_argument, 0, 'k'}, + {"megabytes", no_argument, 0, 'm'}, + {"units", required_argument, 0, 'u'}, + {"path", required_argument, 0, 'p'}, + {"partition", required_argument, 0, 'p'}, + {"exclude_device", required_argument, 0, 'x'}, + {"exclude-type", required_argument, 0, 'X'}, + {"include-type", required_argument, 0, 'N'}, + {"group", required_argument, 0, 'g'}, + {"eregi-path", required_argument, 0, 'R'}, + {"eregi-partition", required_argument, 0, 'R'}, + {"ereg-path", required_argument, 0, 'r'}, + {"ereg-partition", required_argument, 0, 'r'}, + {"freespace-ignore-reserved", no_argument, 0, 'f'}, + {"ignore-ereg-path", required_argument, 0, 'i'}, + {"ignore-ereg-partition", required_argument, 0, 'i'}, + {"ignore-eregi-path", required_argument, 0, 'I'}, + {"ignore-eregi-partition", required_argument, 0, 'I'}, + {"ignore-missing", no_argument, 0, 'n'}, + {"local", no_argument, 0, 'l'}, + {"stat-remote-fs", no_argument, 0, 'L'}, + {"iperfdata", no_argument, 0, 'P'}, + {"mountpoint", no_argument, 0, 'M'}, + {"errors-only", no_argument, 0, 'e'}, + {"exact-match", no_argument, 0, 'E'}, + {"all", no_argument, 0, 'A'}, + {"verbose", no_argument, 0, 'v'}, + {"quiet", no_argument, 0, 'q'}, + {"clear", no_argument, 0, 'C'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0}}; + + if (argc < 2) + return ERROR; + + np_add_regex(&fs_exclude_list, "iso9660", REG_EXTENDED); + + for (c = 1; c < argc; c++) + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + + while (1) { + c = getopt_long(argc, argv, "+?VqhvefCt:c:w:K:W:u:p:x:X:N:mklLPg:R:r:i:I:MEAn", longopts, &option); + + if (c == -1 || c == EOF) + break; + + switch (c) { + case 't': /* timeout period */ + if (is_integer(optarg)) { + timeout_interval = atoi(optarg); + break; + } else { + usage2(_("Timeout interval must be a positive integer"), optarg); + } + + /* See comments for 'c' */ + case 'w': /* warning threshold */ if (!is_percentage_expression(optarg) && !is_numeric(optarg)) { - die(STATE_UNKNOWN, "Argument for --warning invalid or missing: %s\n", optarg); + die(STATE_UNKNOWN, "Argument for --warning invalid or missing: %s\n", optarg); } - if (strstr(optarg, "%")) { - if (*optarg == '@') { - warn_freespace_percent = optarg; - } else { - xasprintf(&warn_freespace_percent, "@%s", optarg); - } - } else { - if (*optarg == '@') { - warn_freespace_units = optarg; - } else { - xasprintf(&warn_freespace_units, "@%s", optarg); - } - } - break; - - /* Awful mistake where the range values do not make sense. Normally, - you alert if the value is within the range, but since we are using - freespace, we have to alert if outside the range. Thus we artificially - force @ at the beginning of the range, so that it is backwards compatible - */ - case 'c': /* critical threshold */ + if (strstr(optarg, "%")) { + if (*optarg == '@') { + warn_freespace_percent = optarg; + } else { + xasprintf(&warn_freespace_percent, "@%s", optarg); + } + } else { + if (*optarg == '@') { + warn_freespace_units = optarg; + } else { + xasprintf(&warn_freespace_units, "@%s", optarg); + } + } + break; + + /* Awful mistake where the range values do not make sense. Normally, + you alert if the value is within the range, but since we are using + freespace, we have to alert if outside the range. Thus we artificially + force @ at the beginning of the range, so that it is backwards compatible + */ + case 'c': /* critical threshold */ if (!is_percentage_expression(optarg) && !is_numeric(optarg)) { - die(STATE_UNKNOWN, "Argument for --critical invalid or missing: %s\n", optarg); + die(STATE_UNKNOWN, "Argument for --critical invalid or missing: %s\n", optarg); } - if (strstr(optarg, "%")) { - if (*optarg == '@') { - crit_freespace_percent = optarg; - } else { - xasprintf(&crit_freespace_percent, "@%s", optarg); - } - } else { - if (*optarg == '@') { - crit_freespace_units = optarg; - } else { - xasprintf(&crit_freespace_units, "@%s", optarg); - } - } - break; - - case 'W': /* warning inode threshold */ - if (*optarg == '@') { - warn_freeinodes_percent = optarg; - } else { - xasprintf(&warn_freeinodes_percent, "@%s", optarg); - } - break; - case 'K': /* critical inode threshold */ - if (*optarg == '@') { - crit_freeinodes_percent = optarg; - } else { - xasprintf(&crit_freeinodes_percent, "@%s", optarg); - } - break; - case 'u': - if (units) - free(units); - if (! strcasecmp (optarg, "bytes")) { - mult = (uintmax_t)1; - units = strdup ("B"); - } else if (!strcmp(optarg, "KiB")) { - mult = (uintmax_t)1024; - units = strdup ("KiB"); - } else if (! strcmp (optarg, "kB")) { - mult = (uintmax_t)1000; - units = strdup ("kB"); - } else if (!strcmp(optarg, "MiB")) { - mult = (uintmax_t)1024 * 1024; - units = strdup ("MiB"); - } else if (! strcmp (optarg, "MB")) { - mult = (uintmax_t)1000 * 1000; - units = strdup ("MB"); - } else if (!strcmp(optarg, "GiB")) { - mult = (uintmax_t)1024 * 1024 * 1024; - units = strdup ("GiB"); - } else if (! strcmp (optarg, "GB")){ - mult = (uintmax_t)1000 * 1000 * 1000; - units = strdup ("GB"); - } else if (!strcmp(optarg, "TiB")) { - mult = (uintmax_t)1024 * 1024 * 1024 * 1024; - units = strdup ("TiB"); - } else if (! strcmp (optarg, "TB")) { - mult = (uintmax_t)1000 * 1000 * 1000 * 1000; - units = strdup ("TB"); - } else if (!strcmp(optarg, "PiB")) { - mult = (uintmax_t)1024 * 1024 * 1024 * 1024 * 1024; - units = strdup ("PiB"); - } else if (! strcmp (optarg, "PB")){ - mult = (uintmax_t)1000 * 1000 * 1000 * 1000 * 1000; - units = strdup ("PB"); - } else { - die (STATE_UNKNOWN, _("unit type %s not known\n"), optarg); - } - if (units == NULL) - die (STATE_UNKNOWN, _("failed allocating storage for '%s'\n"), "units"); - break; - case 'k': /* display mountpoint */ - mult = 1024; - if (units) - free(units); - units = strdup ("kiB"); - break; - case 'm': /* display mountpoint */ - mult = 1024 * 1024; - if (units) - free(units); - units = strdup ("MiB"); - break; - case 'L': - stat_remote_fs = 1; - /* fallthrough */ - case 'l': - show_local_fs = 1; - break; - case 'P': - display_inodes_perfdata = 1; - break; - case 'p': /* select path */ - if (! (warn_freespace_units || crit_freespace_units || warn_freespace_percent || - crit_freespace_percent || warn_usedspace_units || crit_usedspace_units || - warn_usedspace_percent || crit_usedspace_percent || warn_usedinodes_percent || - crit_usedinodes_percent || warn_freeinodes_percent || crit_freeinodes_percent )) { - die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set a threshold value before using -p\n")); - } - - /* add parameter if not found. overwrite thresholds if path has already been added */ - if (! (se = np_find_parameter(path_select_list, optarg))) { - se = np_add_parameter(&path_select_list, optarg); - - if (stat(optarg, &stat_buf[0]) && ignore_missing == true) { - path_ignored = true; - break; - } - } - se->group = group; - set_all_thresholds(se); - - /* With autofs, it is required to stat() the path before re-populating the mount_list */ - if (!stat_path(se)) { - break; - } - /* NB: We can't free the old mount_list "just like that": both list pointers and struct - * pointers are copied around. One of the reason it wasn't done yet is that other parts - * of check_disk need the same kind of cleanup so it'd better be done as a whole */ - mount_list = read_file_system_list (0); - np_set_best_match(se, mount_list, exact_match); - - path_selected = true; - break; - case 'x': /* exclude path or partition */ - np_add_name(&dp_exclude_list, optarg); - break; - case 'X': /* exclude file system type */ - err = np_add_regex(&fs_exclude_list, optarg, REG_EXTENDED); - if (err != 0) { - regerror (err, &fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER); - die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Could not compile regular expression"), errbuf); - } - break; - case 'N': /* include file system type */ - err = np_add_regex(&fs_include_list, optarg, REG_EXTENDED); - if (err != 0) { - regerror (err, &fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER); - die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Could not compile regular expression"), errbuf); - } - break; - case 'v': /* verbose */ - verbose++; - break; - case 'q': /* TODO: this function should eventually go away (removed 2007-09-20) */ - /* verbose--; **replaced by line below**. -q was only a broken way of implementing -e */ - erronly = true; - break; - case 'e': - erronly = true; - break; - case 'E': - if (path_selected) - die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set -E before selecting paths\n")); - exact_match = true; - break; - case 'f': - freespace_ignore_reserved = true; - break; - case 'g': - if (path_selected) - die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set group value before selecting paths\n")); - group = optarg; - break; - case 'I': - cflags |= REG_ICASE; - // Intentional fallthrough - case 'i': - if (!path_selected) - die (STATE_UNKNOWN, "DISK %s: %s\n", _("UNKNOWN"), _("Paths need to be selected before using -i/-I. Use -A to select all paths explicitly")); - err = regcomp(&re, optarg, cflags); - if (err != 0) { - regerror (err, &re, errbuf, MAX_INPUT_BUFFER); - die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Could not compile regular expression"), errbuf); - } - - temp_list = path_select_list; - - previous = NULL; - while (temp_list) { - if (temp_list->best_match) { - if (np_regex_match_mount_entry(temp_list->best_match, &re)) { - - if (verbose >=3) - printf("ignoring %s matching regex\n", temp_list->name); - - temp_list = np_del_parameter(temp_list, previous); - /* pointer to first element needs to be updated if first item gets deleted */ - if (previous == NULL) - path_select_list = temp_list; - } else { - previous = temp_list; - temp_list = temp_list->name_next; - } - } else { - previous = temp_list; - temp_list = temp_list->name_next; - } - } - - - cflags = default_cflags; - break; - - case 'n': - ignore_missing = true; - break; - case 'A': - optarg = strdup(".*"); - // Intentional fallthrough - case 'R': - cflags |= REG_ICASE; - // Intentional fallthrough - case 'r': - if (! (warn_freespace_units || crit_freespace_units || warn_freespace_percent || - crit_freespace_percent || warn_usedspace_units || crit_usedspace_units || - warn_usedspace_percent || crit_usedspace_percent || warn_usedinodes_percent || - crit_usedinodes_percent || warn_freeinodes_percent || crit_freeinodes_percent )) { - die (STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set a threshold value before using -r/-R/-A (--ereg-path/--eregi-path/--all)\n")); - } - - err = regcomp(&re, optarg, cflags); - if (err != 0) { - regerror (err, &re, errbuf, MAX_INPUT_BUFFER); - die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), _("Could not compile regular expression"), errbuf); - } - - for (me = mount_list; me; me = me->me_next) { - if (np_regex_match_mount_entry(me, &re)) { - fnd = true; - if (verbose >= 3) - printf("%s %s matching expression %s\n", me->me_devname, me->me_mountdir, optarg); - - /* add parameter if not found. overwrite thresholds if path has already been added */ - if (! (se = np_find_parameter(path_select_list, me->me_mountdir))) { - se = np_add_parameter(&path_select_list, me->me_mountdir); - } - se->group = group; - set_all_thresholds(se); - } - } - - if (!fnd && ignore_missing == true) { - path_ignored = true; - path_selected = true; - break; - } else if (!fnd) - die (STATE_UNKNOWN, "DISK %s: %s - %s\n",_("UNKNOWN"), - _("Regular expression did not match any path or disk"), optarg); - - fnd = false; - path_selected = true; - np_set_best_match(path_select_list, mount_list, exact_match); - cflags = default_cflags; - - break; - case 'M': /* display mountpoint */ - display_mntp = true; - break; - case 'C': - /* add all mount entries to path_select list if no partitions have been explicitly defined using -p */ - if (path_selected == false) { - struct parameter_list *path; - for (me = mount_list; me; me = me->me_next) { - if (! (path = np_find_parameter(path_select_list, me->me_mountdir))) - path = np_add_parameter(&path_select_list, me->me_mountdir); - path->best_match = me; - path->group = group; - set_all_thresholds(path); - } - } - warn_freespace_units = NULL; - crit_freespace_units = NULL; - warn_usedspace_units = NULL; - crit_usedspace_units = NULL; - warn_freespace_percent = NULL; - crit_freespace_percent = NULL; - warn_usedspace_percent = NULL; - crit_usedspace_percent = NULL; - warn_usedinodes_percent = NULL; - crit_usedinodes_percent = NULL; - warn_freeinodes_percent = NULL; - crit_freeinodes_percent = NULL; - - path_selected = false; - group = NULL; - break; - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case '?': /* help */ - usage (_("Unknown argument")); - } - } - - /* Support for "check_disk warn crit [fs]" with thresholds at used% level */ - c = optind; - if (warn_usedspace_percent == NULL && argc > c && is_intnonneg (argv[c])) - warn_usedspace_percent = argv[c++]; - - if (crit_usedspace_percent == NULL && argc > c && is_intnonneg (argv[c])) - crit_usedspace_percent = argv[c++]; - - if (argc > c) { - se = np_add_parameter(&path_select_list, strdup(argv[c++])); - path_selected = true; - set_all_thresholds(se); - } - - if (units == NULL) { - units = strdup ("MiB"); - mult = (uintmax_t)1024 * 1024; - } - - return true; -} + if (strstr(optarg, "%")) { + if (*optarg == '@') { + crit_freespace_percent = optarg; + } else { + xasprintf(&crit_freespace_percent, "@%s", optarg); + } + } else { + if (*optarg == '@') { + crit_freespace_units = optarg; + } else { + xasprintf(&crit_freespace_units, "@%s", optarg); + } + } + break; -void -set_all_thresholds (struct parameter_list *path) -{ - if (path->freespace_units != NULL) free(path->freespace_units); - set_thresholds(&path->freespace_units, warn_freespace_units, crit_freespace_units); - if (path->freespace_percent != NULL) free (path->freespace_percent); - set_thresholds(&path->freespace_percent, warn_freespace_percent, crit_freespace_percent); - if (path->usedspace_units != NULL) free (path->usedspace_units); - set_thresholds(&path->usedspace_units, warn_usedspace_units, crit_usedspace_units); - if (path->usedspace_percent != NULL) free (path->usedspace_percent); - set_thresholds(&path->usedspace_percent, warn_usedspace_percent, crit_usedspace_percent); - if (path->usedinodes_percent != NULL) free (path->usedinodes_percent); - set_thresholds(&path->usedinodes_percent, warn_usedinodes_percent, crit_usedinodes_percent); - if (path->freeinodes_percent != NULL) free (path->freeinodes_percent); - set_thresholds(&path->freeinodes_percent, warn_freeinodes_percent, crit_freeinodes_percent); -} + case 'W': /* warning inode threshold */ + if (*optarg == '@') { + warn_freeinodes_percent = optarg; + } else { + xasprintf(&warn_freeinodes_percent, "@%s", optarg); + } + break; + case 'K': /* critical inode threshold */ + if (*optarg == '@') { + crit_freeinodes_percent = optarg; + } else { + xasprintf(&crit_freeinodes_percent, "@%s", optarg); + } + break; + case 'u': + if (units) + free(units); + if (!strcasecmp(optarg, "bytes")) { + mult = (uintmax_t)1; + units = strdup("B"); + } else if (!strcmp(optarg, "KiB")) { + mult = (uintmax_t)1024; + units = strdup("KiB"); + } else if (!strcmp(optarg, "kB")) { + mult = (uintmax_t)1000; + units = strdup("kB"); + } else if (!strcmp(optarg, "MiB")) { + mult = (uintmax_t)1024 * 1024; + units = strdup("MiB"); + } else if (!strcmp(optarg, "MB")) { + mult = (uintmax_t)1000 * 1000; + units = strdup("MB"); + } else if (!strcmp(optarg, "GiB")) { + mult = (uintmax_t)1024 * 1024 * 1024; + units = strdup("GiB"); + } else if (!strcmp(optarg, "GB")) { + mult = (uintmax_t)1000 * 1000 * 1000; + units = strdup("GB"); + } else if (!strcmp(optarg, "TiB")) { + mult = (uintmax_t)1024 * 1024 * 1024 * 1024; + units = strdup("TiB"); + } else if (!strcmp(optarg, "TB")) { + mult = (uintmax_t)1000 * 1000 * 1000 * 1000; + units = strdup("TB"); + } else if (!strcmp(optarg, "PiB")) { + mult = (uintmax_t)1024 * 1024 * 1024 * 1024 * 1024; + units = strdup("PiB"); + } else if (!strcmp(optarg, "PB")) { + mult = (uintmax_t)1000 * 1000 * 1000 * 1000 * 1000; + units = strdup("PB"); + } else { + die(STATE_UNKNOWN, _("unit type %s not known\n"), optarg); + } + if (units == NULL) + die(STATE_UNKNOWN, _("failed allocating storage for '%s'\n"), "units"); + break; + case 'k': /* display mountpoint */ + mult = 1024; + if (units) + free(units); + units = strdup("kiB"); + break; + case 'm': /* display mountpoint */ + mult = 1024 * 1024; + if (units) + free(units); + units = strdup("MiB"); + break; + case 'L': + stat_remote_fs = 1; + /* fallthrough */ + case 'l': + show_local_fs = 1; + break; + case 'P': + display_inodes_perfdata = 1; + break; + case 'p': /* select path */ + if (!(warn_freespace_units || crit_freespace_units || warn_freespace_percent || crit_freespace_percent || + warn_usedspace_units || crit_usedspace_units || warn_usedspace_percent || crit_usedspace_percent || + warn_usedinodes_percent || crit_usedinodes_percent || warn_freeinodes_percent || crit_freeinodes_percent)) { + die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set a threshold value before using -p\n")); + } -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); - - printf ("%s\n", _("This plugin checks the amount of used disk space on a mounted file system")); - printf ("%s\n", _("and generates an alert if free space is less than one of the threshold values")); - - printf ("\n\n"); - - print_usage (); - - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - - printf (" %s\n", "-w, --warning=INTEGER"); - printf (" %s\n", _("Exit with WARNING status if less than INTEGER units of disk are free")); - printf (" %s\n", "-w, --warning=PERCENT%"); - printf (" %s\n", _("Exit with WARNING status if less than PERCENT of disk space is free")); - printf (" %s\n", "-c, --critical=INTEGER"); - printf (" %s\n", _("Exit with CRITICAL status if less than INTEGER units of disk are free")); - printf (" %s\n", "-c, --critical=PERCENT%"); - printf (" %s\n", _("Exit with CRITICAL status if less than PERCENT of disk space is free")); - printf (" %s\n", "-W, --iwarning=PERCENT%"); - printf (" %s\n", _("Exit with WARNING status if less than PERCENT of inode space is free")); - printf (" %s\n", "-K, --icritical=PERCENT%"); - printf (" %s\n", _("Exit with CRITICAL status if less than PERCENT of inode space is free")); - printf (" %s\n", "-p, --path=PATH, --partition=PARTITION"); - printf (" %s\n", _("Mount point or block device as emitted by the mount(8) command (may be repeated)")); - printf (" %s\n", "-x, --exclude_device=PATH "); - printf (" %s\n", _("Ignore device (only works if -p unspecified)")); - printf (" %s\n", "-C, --clear"); - printf (" %s\n", _("Clear thresholds")); - printf (" %s\n", "-E, --exact-match"); - printf (" %s\n", _("For paths or partitions specified with -p, only check for exact paths")); - printf (" %s\n", "-e, --errors-only"); - printf (" %s\n", _("Display only devices/mountpoints with errors")); - printf (" %s\n", "-f, --freespace-ignore-reserved"); - printf (" %s\n", _("Don't account root-reserved blocks into freespace in perfdata")); - printf (" %s\n", "-P, --iperfdata"); - printf (" %s\n", _("Display inode usage in perfdata")); - printf (" %s\n", "-g, --group=NAME"); - printf (" %s\n", _("Group paths. Thresholds apply to (free-)space of all partitions together")); - printf (" %s\n", "-k, --kilobytes"); - printf (" %s\n", _("Same as '--units kB'")); - printf (" %s\n", "-l, --local"); - printf (" %s\n", _("Only check local filesystems")); - printf (" %s\n", "-L, --stat-remote-fs"); - printf (" %s\n", _("Only check local filesystems against thresholds. Yet call stat on remote filesystems")); - printf (" %s\n", _("to test if they are accessible (e.g. to detect Stale NFS Handles)")); - printf (" %s\n", "-M, --mountpoint"); - printf (" %s\n", _("Display the (block) device instead of the mount point")); - printf (" %s\n", "-m, --megabytes"); - printf (" %s\n", _("Same as '--units MB'")); - printf (" %s\n", "-A, --all"); - printf (" %s\n", _("Explicitly select all paths. This is equivalent to -R '.*'")); - printf (" %s\n", "-R, --eregi-path=PATH, --eregi-partition=PARTITION"); - printf (" %s\n", _("Case insensitive regular expression for path/partition (may be repeated)")); - printf (" %s\n", "-r, --ereg-path=PATH, --ereg-partition=PARTITION"); - printf (" %s\n", _("Regular expression for path or partition (may be repeated)")); - printf (" %s\n", "-I, --ignore-eregi-path=PATH, --ignore-eregi-partition=PARTITION"); - printf (" %s\n", _("Regular expression to ignore selected path/partition (case insensitive) (may be repeated)")); - printf (" %s\n", "-i, --ignore-ereg-path=PATH, --ignore-ereg-partition=PARTITION"); - printf (" %s\n", _("Regular expression to ignore selected path or partition (may be repeated)")); - printf (" %s\n", "-n, --ignore-missing"); - printf (" %s\n", _("Return OK if no filesystem matches, filesystem does not exist or is inaccessible.")); - printf (" %s\n", _("(Provide this option before -p / -r / --ereg-path if used)")); - printf (UT_PLUG_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf (" %s\n", "-u, --units=STRING"); - printf (" %s\n", _("Choose bytes, kB, MB, GB, TB (default: MB)")); - printf (UT_VERBOSE); - printf (" %s\n", "-X, --exclude-type=TYPE_REGEX"); - printf (" %s\n", _("Ignore all filesystems of types matching given regex(7) (may be repeated)")); - printf (" %s\n", "-N, --include-type=TYPE_REGEX"); - printf (" %s\n", _("Check only filesystems where the type matches this given regex(7) (may be repeated)")); - - printf ("\n"); - printf ("%s\n", _("General usage hints:")); - printf (" %s\n", _("- Arguments are positional! \"-w 5 -c 1 -p /foo -w6 -c2 -p /bar\" is not the same as")); - printf (" %s\n", _("\"-w 5 -c 1 -p /bar w6 -c2 -p /foo\".")); - printf (" %s\n", _("- The syntax is broadly: \"{thresholds a} {paths a} -C {thresholds b} {thresholds b} ...\"")); - - - - printf ("\n"); - printf ("%s\n", _("Examples:")); - printf (" %s\n", "check_disk -w 10% -c 5% -p /tmp -p /var -C -w 100000 -c 50000 -p /"); - printf (" %s\n\n", _("Checks /tmp and /var at 10% and 5%, and / at 100MB and 50MB")); - printf (" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -g sidDATA -r '^/oracle/SID/data.*$'"); - printf (" %s\n", _("Checks all filesystems not matching -r at 100M and 50M. The fs matching the -r regex")); - printf (" %s\n\n", _("are grouped which means the freespace thresholds are applied to all disks together")); - printf (" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -p /foo -C -w 5% -c 3% -p /bar"); - printf (" %s\n", _("Checks /foo for 1000M/500M and /bar for 5/3%. All remaining volumes use 100M/50M")); - - printf (UT_SUPPORT); -} + /* add parameter if not found. overwrite thresholds if path has already been added */ + if (!(se = np_find_parameter(path_select_list, optarg))) { + se = np_add_parameter(&path_select_list, optarg); + + if (stat(optarg, &stat_buf[0]) && ignore_missing == true) { + path_ignored = true; + break; + } + } + se->group = group; + set_all_thresholds(se); + + /* With autofs, it is required to stat() the path before re-populating the mount_list */ + if (!stat_path(se)) { + break; + } + /* NB: We can't free the old mount_list "just like that": both list pointers and struct + * pointers are copied around. One of the reason it wasn't done yet is that other parts + * of check_disk need the same kind of cleanup so it'd better be done as a whole */ + mount_list = read_file_system_list(0); + np_set_best_match(se, mount_list, exact_match); + + path_selected = true; + break; + case 'x': /* exclude path or partition */ + np_add_name(&dp_exclude_list, optarg); + break; + case 'X': /* exclude file system type */ + err = np_add_regex(&fs_exclude_list, optarg, REG_EXTENDED); + if (err != 0) { + regerror(err, &fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER); + die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); + } + break; + case 'N': /* include file system type */ + err = np_add_regex(&fs_include_list, optarg, REG_EXTENDED); + if (err != 0) { + regerror(err, &fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER); + die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); + } + break; + case 'v': /* verbose */ + verbose++; + break; + case 'q': /* TODO: this function should eventually go away (removed 2007-09-20) */ + /* verbose--; **replaced by line below**. -q was only a broken way of implementing -e */ + erronly = true; + break; + case 'e': + erronly = true; + break; + case 'E': + if (path_selected) + die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set -E before selecting paths\n")); + exact_match = true; + break; + case 'f': + freespace_ignore_reserved = true; + break; + case 'g': + if (path_selected) + die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set group value before selecting paths\n")); + group = optarg; + break; + case 'I': + cflags |= REG_ICASE; + // Intentional fallthrough + case 'i': + if (!path_selected) + die(STATE_UNKNOWN, "DISK %s: %s\n", _("UNKNOWN"), + _("Paths need to be selected before using -i/-I. Use -A to select all paths explicitly")); + err = regcomp(&re, optarg, cflags); + if (err != 0) { + regerror(err, &re, errbuf, MAX_INPUT_BUFFER); + die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); + } + + temp_list = path_select_list; + + previous = NULL; + while (temp_list) { + if (temp_list->best_match) { + if (np_regex_match_mount_entry(temp_list->best_match, &re)) { + + if (verbose >= 3) + printf("ignoring %s matching regex\n", temp_list->name); + + temp_list = np_del_parameter(temp_list, previous); + /* pointer to first element needs to be updated if first item gets deleted */ + if (previous == NULL) + path_select_list = temp_list; + } else { + previous = temp_list; + temp_list = temp_list->name_next; + } + } else { + previous = temp_list; + temp_list = temp_list->name_next; + } + } + + cflags = default_cflags; + break; + + case 'n': + ignore_missing = true; + break; + case 'A': + optarg = strdup(".*"); + // Intentional fallthrough + case 'R': + cflags |= REG_ICASE; + // Intentional fallthrough + case 'r': + if (!(warn_freespace_units || crit_freespace_units || warn_freespace_percent || crit_freespace_percent || + warn_usedspace_units || crit_usedspace_units || warn_usedspace_percent || crit_usedspace_percent || + warn_usedinodes_percent || crit_usedinodes_percent || warn_freeinodes_percent || crit_freeinodes_percent)) { + die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), + _("Must set a threshold value before using -r/-R/-A (--ereg-path/--eregi-path/--all)\n")); + } + + err = regcomp(&re, optarg, cflags); + if (err != 0) { + regerror(err, &re, errbuf, MAX_INPUT_BUFFER); + die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); + } + for (me = mount_list; me; me = me->me_next) { + if (np_regex_match_mount_entry(me, &re)) { + fnd = true; + if (verbose >= 3) + printf("%s %s matching expression %s\n", me->me_devname, me->me_mountdir, optarg); + + /* add parameter if not found. overwrite thresholds if path has already been added */ + if (!(se = np_find_parameter(path_select_list, me->me_mountdir))) { + se = np_add_parameter(&path_select_list, me->me_mountdir); + } + se->group = group; + set_all_thresholds(se); + } + } + if (!fnd && ignore_missing == true) { + path_ignored = true; + path_selected = true; + break; + } else if (!fnd) + die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Regular expression did not match any path or disk"), optarg); + + fnd = false; + path_selected = true; + np_set_best_match(path_select_list, mount_list, exact_match); + cflags = default_cflags; + + break; + case 'M': /* display mountpoint */ + display_mntp = true; + break; + case 'C': + /* add all mount entries to path_select list if no partitions have been explicitly defined using -p */ + if (path_selected == false) { + struct parameter_list *path; + for (me = mount_list; me; me = me->me_next) { + if (!(path = np_find_parameter(path_select_list, me->me_mountdir))) + path = np_add_parameter(&path_select_list, me->me_mountdir); + path->best_match = me; + path->group = group; + set_all_thresholds(path); + } + } + warn_freespace_units = NULL; + crit_freespace_units = NULL; + warn_usedspace_units = NULL; + crit_usedspace_units = NULL; + warn_freespace_percent = NULL; + crit_freespace_percent = NULL; + warn_usedspace_percent = NULL; + crit_usedspace_percent = NULL; + warn_usedinodes_percent = NULL; + crit_usedinodes_percent = NULL; + warn_freeinodes_percent = NULL; + crit_freeinodes_percent = NULL; + + path_selected = false; + group = NULL; + break; + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case '?': /* help */ + usage(_("Unknown argument")); + } + } + + /* Support for "check_disk warn crit [fs]" with thresholds at used% level */ + c = optind; + if (warn_usedspace_percent == NULL && argc > c && is_intnonneg(argv[c])) + warn_usedspace_percent = argv[c++]; + + if (crit_usedspace_percent == NULL && argc > c && is_intnonneg(argv[c])) + crit_usedspace_percent = argv[c++]; + + if (argc > c) { + se = np_add_parameter(&path_select_list, strdup(argv[c++])); + path_selected = true; + set_all_thresholds(se); + } + + if (units == NULL) { + units = strdup("MiB"); + mult = (uintmax_t)1024 * 1024; + } + + return true; +} -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s {-w absolute_limit |-w percentage_limit%% | -W inode_percentage_limit } {-c absolute_limit|-c percentage_limit%% | -K inode_percentage_limit } {-p path | -x device}\n", progname); - printf ("[-C] [-E] [-e] [-f] [-g group ] [-k] [-l] [-M] [-m] [-R path ] [-r path ]\n"); - printf ("[-t timeout] [-u unit] [-v] [-X type_regex] [-N type]\n"); +void set_all_thresholds(struct parameter_list *path) { + if (path->freespace_units != NULL) + free(path->freespace_units); + set_thresholds(&path->freespace_units, warn_freespace_units, crit_freespace_units); + if (path->freespace_percent != NULL) + free(path->freespace_percent); + set_thresholds(&path->freespace_percent, warn_freespace_percent, crit_freespace_percent); + if (path->usedspace_units != NULL) + free(path->usedspace_units); + set_thresholds(&path->usedspace_units, warn_usedspace_units, crit_usedspace_units); + if (path->usedspace_percent != NULL) + free(path->usedspace_percent); + set_thresholds(&path->usedspace_percent, warn_usedspace_percent, crit_usedspace_percent); + if (path->usedinodes_percent != NULL) + free(path->usedinodes_percent); + set_thresholds(&path->usedinodes_percent, warn_usedinodes_percent, crit_usedinodes_percent); + if (path->freeinodes_percent != NULL) + free(path->freeinodes_percent); + set_thresholds(&path->freeinodes_percent, warn_freeinodes_percent, crit_freeinodes_percent); } -bool -stat_path (struct parameter_list *p) -{ - /* Stat entry to check that dir exists and is accessible */ - if (verbose >= 3) - printf("calling stat on %s\n", p->name); - if (stat (p->name, &stat_buf[0])) { - if (verbose >= 3) - printf("stat failed on %s\n", p->name); - if (ignore_missing == true) { - return false; - } else { - printf("DISK %s - ", _("CRITICAL")); - die (STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); - } - } - return true; +void print_help(void) { + print_revision(progname, NP_VERSION); + + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); + + printf("%s\n", _("This plugin checks the amount of used disk space on a mounted file system")); + printf("%s\n", _("and generates an alert if free space is less than one of the threshold values")); + + printf("\n\n"); + + print_usage(); + + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf(" %s\n", "-w, --warning=INTEGER"); + printf(" %s\n", _("Exit with WARNING status if less than INTEGER units of disk are free")); + printf(" %s\n", "-w, --warning=PERCENT%"); + printf(" %s\n", _("Exit with WARNING status if less than PERCENT of disk space is free")); + printf(" %s\n", "-c, --critical=INTEGER"); + printf(" %s\n", _("Exit with CRITICAL status if less than INTEGER units of disk are free")); + printf(" %s\n", "-c, --critical=PERCENT%"); + printf(" %s\n", _("Exit with CRITICAL status if less than PERCENT of disk space is free")); + printf(" %s\n", "-W, --iwarning=PERCENT%"); + printf(" %s\n", _("Exit with WARNING status if less than PERCENT of inode space is free")); + printf(" %s\n", "-K, --icritical=PERCENT%"); + printf(" %s\n", _("Exit with CRITICAL status if less than PERCENT of inode space is free")); + printf(" %s\n", "-p, --path=PATH, --partition=PARTITION"); + printf(" %s\n", _("Mount point or block device as emitted by the mount(8) command (may be repeated)")); + printf(" %s\n", "-x, --exclude_device=PATH "); + printf(" %s\n", _("Ignore device (only works if -p unspecified)")); + printf(" %s\n", "-C, --clear"); + printf(" %s\n", _("Clear thresholds")); + printf(" %s\n", "-E, --exact-match"); + printf(" %s\n", _("For paths or partitions specified with -p, only check for exact paths")); + printf(" %s\n", "-e, --errors-only"); + printf(" %s\n", _("Display only devices/mountpoints with errors")); + printf(" %s\n", "-f, --freespace-ignore-reserved"); + printf(" %s\n", _("Don't account root-reserved blocks into freespace in perfdata")); + printf(" %s\n", "-P, --iperfdata"); + printf(" %s\n", _("Display inode usage in perfdata")); + printf(" %s\n", "-g, --group=NAME"); + printf(" %s\n", _("Group paths. Thresholds apply to (free-)space of all partitions together")); + printf(" %s\n", "-k, --kilobytes"); + printf(" %s\n", _("Same as '--units kB'")); + printf(" %s\n", "-l, --local"); + printf(" %s\n", _("Only check local filesystems")); + printf(" %s\n", "-L, --stat-remote-fs"); + printf(" %s\n", _("Only check local filesystems against thresholds. Yet call stat on remote filesystems")); + printf(" %s\n", _("to test if they are accessible (e.g. to detect Stale NFS Handles)")); + printf(" %s\n", "-M, --mountpoint"); + printf(" %s\n", _("Display the (block) device instead of the mount point")); + printf(" %s\n", "-m, --megabytes"); + printf(" %s\n", _("Same as '--units MB'")); + printf(" %s\n", "-A, --all"); + printf(" %s\n", _("Explicitly select all paths. This is equivalent to -R '.*'")); + printf(" %s\n", "-R, --eregi-path=PATH, --eregi-partition=PARTITION"); + printf(" %s\n", _("Case insensitive regular expression for path/partition (may be repeated)")); + printf(" %s\n", "-r, --ereg-path=PATH, --ereg-partition=PARTITION"); + printf(" %s\n", _("Regular expression for path or partition (may be repeated)")); + printf(" %s\n", "-I, --ignore-eregi-path=PATH, --ignore-eregi-partition=PARTITION"); + printf(" %s\n", _("Regular expression to ignore selected path/partition (case insensitive) (may be repeated)")); + printf(" %s\n", "-i, --ignore-ereg-path=PATH, --ignore-ereg-partition=PARTITION"); + printf(" %s\n", _("Regular expression to ignore selected path or partition (may be repeated)")); + printf(" %s\n", "-n, --ignore-missing"); + printf(" %s\n", _("Return OK if no filesystem matches, filesystem does not exist or is inaccessible.")); + printf(" %s\n", _("(Provide this option before -p / -r / --ereg-path if used)")); + printf(UT_PLUG_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(" %s\n", "-u, --units=STRING"); + printf(" %s\n", _("Choose bytes, kB, MB, GB, TB (default: MB)")); + printf(UT_VERBOSE); + printf(" %s\n", "-X, --exclude-type=TYPE_REGEX"); + printf(" %s\n", _("Ignore all filesystems of types matching given regex(7) (may be repeated)")); + printf(" %s\n", "-N, --include-type=TYPE_REGEX"); + printf(" %s\n", _("Check only filesystems where the type matches this given regex(7) (may be repeated)")); + + printf("\n"); + printf("%s\n", _("General usage hints:")); + printf(" %s\n", _("- Arguments are positional! \"-w 5 -c 1 -p /foo -w6 -c2 -p /bar\" is not the same as")); + printf(" %s\n", _("\"-w 5 -c 1 -p /bar w6 -c2 -p /foo\".")); + printf(" %s\n", _("- The syntax is broadly: \"{thresholds a} {paths a} -C {thresholds b} {thresholds b} ...\"")); + + printf("\n"); + printf("%s\n", _("Examples:")); + printf(" %s\n", "check_disk -w 10% -c 5% -p /tmp -p /var -C -w 100000 -c 50000 -p /"); + printf(" %s\n\n", _("Checks /tmp and /var at 10% and 5%, and / at 100MB and 50MB")); + printf(" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -g sidDATA -r '^/oracle/SID/data.*$'"); + printf(" %s\n", _("Checks all filesystems not matching -r at 100M and 50M. The fs matching the -r regex")); + printf(" %s\n\n", _("are grouped which means the freespace thresholds are applied to all disks together")); + printf(" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -p /foo -C -w 5% -c 3% -p /bar"); + printf(" %s\n", _("Checks /foo for 1000M/500M and /bar for 5/3%. All remaining volumes use 100M/50M")); + + printf(UT_SUPPORT); } +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s {-w absolute_limit |-w percentage_limit%% | -W inode_percentage_limit } {-c absolute_limit|-c percentage_limit%% | -K " + "inode_percentage_limit } {-p path | -x device}\n", + progname); + printf("[-C] [-E] [-e] [-f] [-g group ] [-k] [-l] [-M] [-m] [-R path ] [-r path ]\n"); + printf("[-t timeout] [-u unit] [-v] [-X type_regex] [-N type]\n"); +} -void -get_stats (struct parameter_list *p, struct fs_usage *fsp) { - struct parameter_list *p_list; - struct fs_usage tmpfsp; - int first = 1; +bool stat_path(struct parameter_list *p) { + /* Stat entry to check that dir exists and is accessible */ + if (verbose >= 3) + printf("calling stat on %s\n", p->name); + if (stat(p->name, &stat_buf[0])) { + if (verbose >= 3) + printf("stat failed on %s\n", p->name); + if (ignore_missing == true) { + return false; + } else { + printf("DISK %s - ", _("CRITICAL")); + die(STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); + } + } + return true; +} + +void get_stats(struct parameter_list *p, struct fs_usage *fsp) { + struct parameter_list *p_list; + struct fs_usage tmpfsp; + int first = 1; - if (p->group == NULL) { - get_path_stats(p,fsp); - } else { - /* find all group members */ - for (p_list = path_select_list; p_list; p_list=p_list->name_next) { + if (p->group == NULL) { + get_path_stats(p, fsp); + } else { + /* find all group members */ + for (p_list = path_select_list; p_list; p_list = p_list->name_next) { #ifdef __CYGWIN__ - if (strncmp(p_list->name, "/cygdrive/", 10) != 0) - continue; + if (strncmp(p_list->name, "/cygdrive/", 10) != 0) + continue; #endif - if (p_list->group && ! (strcmp(p_list->group, p->group))) { - if (! stat_path(p_list)) - continue; - get_fs_usage (p_list->best_match->me_mountdir, p_list->best_match->me_devname, &tmpfsp); - get_path_stats(p_list, &tmpfsp); - if (verbose >= 3) - printf("Group %s: adding %lu blocks sized %lu, (%s) used_units=%lu free_units=%lu total_units=%lu mult=%lu\n", - p_list->group, - tmpfsp.fsu_blocks, - tmpfsp.fsu_blocksize, - p_list->best_match->me_mountdir, - p_list->dused_units, - p_list->dfree_units, - p_list->dtotal_units, - mult); - - /* prevent counting the first FS of a group twice since its parameter_list entry - * is used to carry the information of all file systems of the entire group */ - if (! first) { - p->total += p_list->total; - p->available += p_list->available; - p->available_to_root += p_list->available_to_root; - p->used += p_list->used; - - p->dused_units += p_list->dused_units; - p->dfree_units += p_list->dfree_units; - p->dtotal_units += p_list->dtotal_units; - p->inodes_total += p_list->inodes_total; - p->inodes_free += p_list->inodes_free; - p->inodes_free_to_root += p_list->inodes_free_to_root; - p->inodes_used += p_list->inodes_used; - } - first = 0; - } - if (verbose >= 3) - printf("Group %s now has: used_units=%lu free_units=%lu total_units=%lu fsu_blocksize=%lu mult=%lu\n", - p->group, - p->dused_units, - p->dfree_units, - p->dtotal_units, - tmpfsp.fsu_blocksize, - mult); - } - /* modify devname and mountdir for output */ - p->best_match->me_mountdir = p->best_match->me_devname = p->group; - } - /* finally calculate percentages for either plain FS or summed up group */ - p->dused_pct = calculate_percent( p->used, p->used + p->available ); /* used + available can never be > uintmax */ - p->dfree_pct = 100.0 - p->dused_pct; - p->dused_inodes_percent = calculate_percent(p->inodes_total - p->inodes_free, p->inodes_total); - p->dfree_inodes_percent = 100 - p->dused_inodes_percent; - + if (p_list->group && !(strcmp(p_list->group, p->group))) { + if (!stat_path(p_list)) + continue; + get_fs_usage(p_list->best_match->me_mountdir, p_list->best_match->me_devname, &tmpfsp); + get_path_stats(p_list, &tmpfsp); + if (verbose >= 3) + printf("Group %s: adding %lu blocks sized %lu, (%s) used_units=%lu free_units=%lu total_units=%lu mult=%lu\n", + p_list->group, tmpfsp.fsu_blocks, tmpfsp.fsu_blocksize, p_list->best_match->me_mountdir, p_list->dused_units, + p_list->dfree_units, p_list->dtotal_units, mult); + + /* prevent counting the first FS of a group twice since its parameter_list entry + * is used to carry the information of all file systems of the entire group */ + if (!first) { + p->total += p_list->total; + p->available += p_list->available; + p->available_to_root += p_list->available_to_root; + p->used += p_list->used; + + p->dused_units += p_list->dused_units; + p->dfree_units += p_list->dfree_units; + p->dtotal_units += p_list->dtotal_units; + p->inodes_total += p_list->inodes_total; + p->inodes_free += p_list->inodes_free; + p->inodes_free_to_root += p_list->inodes_free_to_root; + p->inodes_used += p_list->inodes_used; + } + first = 0; + } + if (verbose >= 3) + printf("Group %s now has: used_units=%lu free_units=%lu total_units=%lu fsu_blocksize=%lu mult=%lu\n", p->group, + p->dused_units, p->dfree_units, p->dtotal_units, tmpfsp.fsu_blocksize, mult); + } + /* modify devname and mountdir for output */ + p->best_match->me_mountdir = p->best_match->me_devname = p->group; + } + /* finally calculate percentages for either plain FS or summed up group */ + p->dused_pct = calculate_percent(p->used, p->used + p->available); /* used + available can never be > uintmax */ + p->dfree_pct = 100.0 - p->dused_pct; + p->dused_inodes_percent = calculate_percent(p->inodes_total - p->inodes_free, p->inodes_total); + p->dfree_inodes_percent = 100 - p->dused_inodes_percent; } -void -get_path_stats (struct parameter_list *p, struct fs_usage *fsp) { - p->available = fsp->fsu_bavail; - p->available_to_root = fsp->fsu_bfree; - p->used = fsp->fsu_blocks - fsp->fsu_bfree; - if (freespace_ignore_reserved) { - /* option activated : we subtract the root-reserved space from the total */ - p->total = fsp->fsu_blocks - p->available_to_root + p->available; - } else { - /* default behaviour : take all the blocks into account */ - p->total = fsp->fsu_blocks; - } - - p->dused_units = p->used*fsp->fsu_blocksize/mult; - p->dfree_units = p->available*fsp->fsu_blocksize/mult; - p->dtotal_units = p->total*fsp->fsu_blocksize/mult; - /* Free file nodes. Not sure the workaround is required, but in case...*/ - p->inodes_free = fsp->fsu_ffree; - p->inodes_free_to_root = fsp->fsu_ffree; /* Free file nodes for root. */ - p->inodes_used = fsp->fsu_files - fsp->fsu_ffree; - if (freespace_ignore_reserved) { - /* option activated : we subtract the root-reserved inodes from the total */ - /* not all OS report fsp->fsu_favail, only the ones with statvfs syscall */ - /* for others, fsp->fsu_ffree == fsp->fsu_favail */ - p->inodes_total = fsp->fsu_files - p->inodes_free_to_root + p->inodes_free; - } else { - /* default behaviour : take all the inodes into account */ - p->inodes_total = fsp->fsu_files; - } - np_add_name(&seen, p->best_match->me_mountdir); +void get_path_stats(struct parameter_list *p, struct fs_usage *fsp) { + p->available = fsp->fsu_bavail; + p->available_to_root = fsp->fsu_bfree; + p->used = fsp->fsu_blocks - fsp->fsu_bfree; + if (freespace_ignore_reserved) { + /* option activated : we subtract the root-reserved space from the total */ + p->total = fsp->fsu_blocks - p->available_to_root + p->available; + } else { + /* default behaviour : take all the blocks into account */ + p->total = fsp->fsu_blocks; + } + + p->dused_units = p->used * fsp->fsu_blocksize / mult; + p->dfree_units = p->available * fsp->fsu_blocksize / mult; + p->dtotal_units = p->total * fsp->fsu_blocksize / mult; + /* Free file nodes. Not sure the workaround is required, but in case...*/ + p->inodes_free = fsp->fsu_ffree; + p->inodes_free_to_root = fsp->fsu_ffree; /* Free file nodes for root. */ + p->inodes_used = fsp->fsu_files - fsp->fsu_ffree; + if (freespace_ignore_reserved) { + /* option activated : we subtract the root-reserved inodes from the total */ + /* not all OS report fsp->fsu_favail, only the ones with statvfs syscall */ + /* for others, fsp->fsu_ffree == fsp->fsu_favail */ + p->inodes_total = fsp->fsu_files - p->inodes_free_to_root + p->inodes_free; + } else { + /* default behaviour : take all the inodes into account */ + p->inodes_total = fsp->fsu_files; + } + np_add_name(&seen, p->best_match->me_mountdir); } -- cgit v1.2.3-74-g34f1 From 78aa69150556f83d335ec417c290c617b6f6b5df Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:25:04 +0100 Subject: check_disk: Update copyright --- plugins/check_disk.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_disk.c b/plugins/check_disk.c index fc4039f1..873b17bd 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -3,7 +3,7 @@ * Monitoring check_disk plugin * * License: GPL - * Copyright (c) 1999-2008 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -28,7 +28,7 @@ const char *progname = "check_disk"; const char *program_name = "check_disk"; /* Required for coreutils libs */ -const char *copyright = "1999-2008"; +const char *copyright = "1999-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From e57e86aedb91ea8c973b1e751cf233dc1aa0465b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:26:07 +0100 Subject: check_dig: Update copyright --- plugins/check_dig.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_dig.c b/plugins/check_dig.c index 4d89ca86..2bbd1e05 100644 --- a/plugins/check_dig.c +++ b/plugins/check_dig.c @@ -3,7 +3,7 @@ * Monitoring check_dig plugin * * License: GPL - * Copyright (c) 2002-2008 Monitoring Plugins Development Team + * Copyright (c) 2002-2024 Monitoring Plugins Development Team * * Description: * @@ -33,7 +33,7 @@ * because on some architectures those strings are in non-writable memory */ const char *progname = "check_dig"; -const char *copyright = "2002-2008"; +const char *copyright = "2002-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From 08526fd07f99895f198db1e58ad92e52b9b809bb Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:28:27 +0100 Subject: check_disk: Linter fixes --- plugins/check_disk.c | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/plugins/check_disk.c b/plugins/check_disk.c index 873b17bd..d1d1b92a 100644 --- a/plugins/check_disk.c +++ b/plugins/check_disk.c @@ -117,7 +117,7 @@ enum { # pragma alloca #endif -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static void set_all_thresholds(struct parameter_list *path); static void print_help(void); void print_usage(void); @@ -168,7 +168,8 @@ int main(int argc, char **argv) { struct mount_entry *me; struct fs_usage fsp; - struct parameter_list *temp_list, *path; + struct parameter_list *temp_list; + struct parameter_list *path; #ifdef __CYGWIN__ char mountdir[32]; @@ -286,17 +287,20 @@ int main(int argc, char **argv) { } continue; /* Skip pseudo fs's if we haven't asked for all fs's */ - } else if (me->me_dummy && !show_all_fs) { + } + if (me->me_dummy && !show_all_fs) { continue; /* Skip excluded fstypes */ - } else if (fs_exclude_list && np_find_regmatch(fs_exclude_list, me->me_type)) { + } + if (fs_exclude_list && np_find_regmatch(fs_exclude_list, me->me_type)) { continue; /* Skip excluded fs's */ - } else if (dp_exclude_list && - (np_find_name(dp_exclude_list, me->me_devname) || np_find_name(dp_exclude_list, me->me_mountdir))) { + } + if (dp_exclude_list && (np_find_name(dp_exclude_list, me->me_devname) || np_find_name(dp_exclude_list, me->me_mountdir))) { continue; /* Skip not included fstypes */ - } else if (fs_include_list && !np_find_regmatch(fs_include_list, me->me_type)) { + } + if (fs_include_list && !np_find_regmatch(fs_include_list, me->me_type)) { continue; } } @@ -453,9 +457,11 @@ double calculate_percent(uintmax_t value, uintmax_t total) { /* process command-line arguments */ int process_arguments(int argc, char **argv) { - int c, err; + int c; + int err; struct parameter_list *se; - struct parameter_list *temp_list = NULL, *previous = NULL; + struct parameter_list *temp_list = NULL; + struct parameter_list *previous = NULL; struct mount_entry *me; regex_t re; int cflags = REG_NOSUB | REG_EXTENDED; @@ -803,7 +809,8 @@ int process_arguments(int argc, char **argv) { path_ignored = true; path_selected = true; break; - } else if (!fnd) + } + if (!fnd) die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Regular expression did not match any path or disk"), optarg); fnd = false; @@ -1011,10 +1018,9 @@ bool stat_path(struct parameter_list *p) { printf("stat failed on %s\n", p->name); if (ignore_missing == true) { return false; - } else { - printf("DISK %s - ", _("CRITICAL")); - die(STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); } + printf("DISK %s - ", _("CRITICAL")); + die(STATE_CRITICAL, _("%s %s: %s\n"), p->name, _("is not accessible"), strerror(errno)); } return true; } -- cgit v1.2.3-74-g34f1 From 499c0a07ae42ef48b3a1f25031fb933c3c59e327 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:29:32 +0100 Subject: check_dns: clang-format --- plugins/check_dns.c | 1067 ++++++++++++++++++++++++--------------------------- 1 file changed, 509 insertions(+), 558 deletions(-) diff --git a/plugins/check_dns.c b/plugins/check_dns.c index 468bc958..7cd23162 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_dns plugin -* -* License: GPL -* Copyright (c) 2000-2008 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_dns plugin -* -* LIMITATION: nslookup on Solaris 7 can return output over 2 lines, which -* will not be picked up by this plugin -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_dns plugin + * + * License: GPL + * Copyright (c) 2000-2008 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_dns plugin + * + * LIMITATION: nslookup on Solaris 7 can return output over 2 lines, which + * will not be picked up by this plugin + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_dns"; const char *copyright = "2000-2008"; @@ -39,13 +39,13 @@ const char *email = "devel@monitoring-plugins.org"; #include "netutils.h" #include "runcmd.h" -int process_arguments (int, char **); -int validate_arguments (void); -int error_scan (char *, bool *); +int process_arguments(int, char **); +int validate_arguments(void); +int error_scan(char *, bool *); bool ip_match_cidr(const char *, const char *); unsigned long ip2long(const char *); -void print_help (void); -void print_usage (void); +void print_help(void); +void print_usage(void); #define ADDRESS_LENGTH 256 char query_address[ADDRESS_LENGTH] = ""; @@ -60,558 +60,509 @@ bool expect_authority = false; bool all_match = false; thresholds *time_thresholds = NULL; -static int -qstrcmp(const void *p1, const void *p2) -{ +static int qstrcmp(const void *p1, const void *p2) { /* The actual arguments to this function are "pointers to pointers to char", but strcmp() arguments are "pointers to char", hence the following cast plus dereference */ - return strcmp(* (char * const *) p1, * (char * const *) p2); + return strcmp(*(char *const *)p1, *(char *const *)p2); } +int main(int argc, char **argv) { + char *command_line = NULL; + char input_buffer[MAX_INPUT_BUFFER]; + char *address = NULL; /* comma separated str with addrs/ptrs (sorted) */ + char **addresses = NULL; + int n_addresses = 0; + char *msg = NULL; + char *temp_buffer = NULL; + bool non_authoritative = false; + int result = STATE_UNKNOWN; + double elapsed_time; + long microsec; + struct timeval tv; + bool parse_address = false; /* This flag scans for Address: but only after Name: */ + output chld_out, chld_err; + bool is_nxdomain = false; + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + /* Set signal handling and alarm */ + if (signal(SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) { + usage_va(_("Cannot catch SIGALRM")); + } + + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); + + if (process_arguments(argc, argv) == ERROR) { + usage_va(_("Could not parse arguments")); + } + + /* get the command to run */ + xasprintf(&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server); + + alarm(timeout_interval); + gettimeofday(&tv, NULL); + + if (verbose) + printf("%s\n", command_line); + + /* run the command */ + if ((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) { + msg = (char *)_("nslookup returned an error status"); + result = STATE_WARNING; + } + + /* scan stdout */ + for (size_t i = 0; i < chld_out.lines; i++) { + if (addresses == NULL) + addresses = malloc(sizeof(*addresses) * 10); + else if (!(n_addresses % 10)) + addresses = realloc(addresses, sizeof(*addresses) * (n_addresses + 10)); + + if (verbose) + puts(chld_out.line[i]); + + if (strcasestr(chld_out.line[i], ".in-addr.arpa") || strcasestr(chld_out.line[i], ".ip6.arpa")) { + if ((temp_buffer = strstr(chld_out.line[i], "name = "))) + addresses[n_addresses++] = strdup(temp_buffer + 7); + else { + msg = (char *)_("Warning plugin error"); + result = STATE_WARNING; + } + } + + /* bug ID: 2946553 - Older versions of bind will use all available dns + servers, we have to match the one specified */ + if (strstr(chld_out.line[i], "Server:") && strlen(dns_server) > 0) { + temp_buffer = strchr(chld_out.line[i], ':'); + temp_buffer++; + + /* Strip leading tabs */ + for (; *temp_buffer != '\0' && *temp_buffer == '\t'; temp_buffer++) + /* NOOP */; + + strip(temp_buffer); + if (temp_buffer == NULL || strlen(temp_buffer) == 0) { + die(STATE_CRITICAL, _("DNS CRITICAL - '%s' returned empty server string\n"), NSLOOKUP_COMMAND); + } + + if (strcmp(temp_buffer, dns_server) != 0) { + die(STATE_CRITICAL, _("DNS CRITICAL - No response from DNS %s\n"), dns_server); + } + } + + /* the server is responding, we just got the host name... */ + if (strstr(chld_out.line[i], "Name:")) + parse_address = true; + else if (parse_address && (strstr(chld_out.line[i], "Address:") || strstr(chld_out.line[i], "Addresses:"))) { + temp_buffer = index(chld_out.line[i], ':'); + temp_buffer++; + + /* Strip leading spaces */ + while (*temp_buffer == ' ') + temp_buffer++; + + strip(temp_buffer); + if (temp_buffer == NULL || strlen(temp_buffer) == 0) { + die(STATE_CRITICAL, _("DNS CRITICAL - '%s' returned empty host name string\n"), NSLOOKUP_COMMAND); + } + + addresses[n_addresses++] = strdup(temp_buffer); + } else if (strstr(chld_out.line[i], _("Non-authoritative answer:"))) { + non_authoritative = true; + } + + result = error_scan(chld_out.line[i], &is_nxdomain); + if (result != STATE_OK) { + msg = strchr(chld_out.line[i], ':'); + if (msg) + msg++; + break; + } + } + + /* scan stderr */ + for (size_t i = 0; i < chld_err.lines; i++) { + if (verbose) + puts(chld_err.line[i]); + + if (error_scan(chld_err.line[i], &is_nxdomain) != STATE_OK) { + result = max_state(result, error_scan(chld_err.line[i], &is_nxdomain)); + msg = strchr(input_buffer, ':'); + if (msg) + msg++; + else + msg = input_buffer; + } + } + + if (is_nxdomain && !expect_nxdomain) { + die(STATE_CRITICAL, _("Domain '%s' was not found by the server\n"), query_address); + } -int -main (int argc, char **argv) -{ - char *command_line = NULL; - char input_buffer[MAX_INPUT_BUFFER]; - char *address = NULL; /* comma separated str with addrs/ptrs (sorted) */ - char **addresses = NULL; - int n_addresses = 0; - char *msg = NULL; - char *temp_buffer = NULL; - bool non_authoritative = false; - int result = STATE_UNKNOWN; - double elapsed_time; - long microsec; - struct timeval tv; - bool parse_address = false; /* This flag scans for Address: but only after Name: */ - output chld_out, chld_err; - bool is_nxdomain = false; - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - /* Set signal handling and alarm */ - if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) { - usage_va(_("Cannot catch SIGALRM")); - } - - /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); - - if (process_arguments (argc, argv) == ERROR) { - usage_va(_("Could not parse arguments")); - } - - /* get the command to run */ - xasprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server); - - alarm (timeout_interval); - gettimeofday (&tv, NULL); - - if (verbose) - printf ("%s\n", command_line); - - /* run the command */ - if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) { - msg = (char *)_("nslookup returned an error status"); - result = STATE_WARNING; - } - - /* scan stdout */ - for(size_t i = 0; i < chld_out.lines; i++) { - if (addresses == NULL) - addresses = malloc(sizeof(*addresses)*10); - else if (!(n_addresses % 10)) - addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10)); - - if (verbose) - puts(chld_out.line[i]); - - if (strcasestr (chld_out.line[i], ".in-addr.arpa") || strcasestr (chld_out.line[i], ".ip6.arpa")) { - if ((temp_buffer = strstr (chld_out.line[i], "name = "))) - addresses[n_addresses++] = strdup (temp_buffer + 7); - else { - msg = (char *)_("Warning plugin error"); - result = STATE_WARNING; - } - } - - /* bug ID: 2946553 - Older versions of bind will use all available dns - servers, we have to match the one specified */ - if (strstr (chld_out.line[i], "Server:") && strlen(dns_server) > 0) { - temp_buffer = strchr (chld_out.line[i], ':'); - temp_buffer++; - - /* Strip leading tabs */ - for (; *temp_buffer != '\0' && *temp_buffer == '\t'; temp_buffer++) - /* NOOP */; - - strip(temp_buffer); - if (temp_buffer==NULL || strlen(temp_buffer)==0) { - die (STATE_CRITICAL, - _("DNS CRITICAL - '%s' returned empty server string\n"), - NSLOOKUP_COMMAND); - } - - if (strcmp(temp_buffer, dns_server) != 0) { - die (STATE_CRITICAL, _("DNS CRITICAL - No response from DNS %s\n"), dns_server); - } - } - - /* the server is responding, we just got the host name... */ - if (strstr (chld_out.line[i], "Name:")) - parse_address = true; - else if (parse_address && (strstr (chld_out.line[i], "Address:") || - strstr (chld_out.line[i], "Addresses:"))) { - temp_buffer = index (chld_out.line[i], ':'); - temp_buffer++; - - /* Strip leading spaces */ - while (*temp_buffer == ' ') - temp_buffer++; - - strip(temp_buffer); - if (temp_buffer==NULL || strlen(temp_buffer)==0) { - die (STATE_CRITICAL, - _("DNS CRITICAL - '%s' returned empty host name string\n"), - NSLOOKUP_COMMAND); - } - - addresses[n_addresses++] = strdup(temp_buffer); - } - else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) { - non_authoritative = true; - } - - - result = error_scan (chld_out.line[i], &is_nxdomain); - if (result != STATE_OK) { - msg = strchr (chld_out.line[i], ':'); - if(msg) msg++; - break; - } - } - - /* scan stderr */ - for(size_t i = 0; i < chld_err.lines; i++) { - if (verbose) - puts(chld_err.line[i]); - - if (error_scan (chld_err.line[i], &is_nxdomain) != STATE_OK) { - result = max_state (result, error_scan (chld_err.line[i], &is_nxdomain)); - msg = strchr(input_buffer, ':'); - if(msg) - msg++; - else - msg = input_buffer; - } - } - - if (is_nxdomain && !expect_nxdomain) { - die (STATE_CRITICAL, _("Domain '%s' was not found by the server\n"), query_address); - } - - if (addresses) { - int i,slen; - char *adrp; - qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp); - for(i=0, slen=1; i < n_addresses; i++) { - slen += strlen(addresses[i])+1; - } - adrp = address = malloc(slen); - for(i=0; i < n_addresses; i++) { - if (i) *adrp++ = ','; - strcpy(adrp, addresses[i]); - adrp += strlen(addresses[i]); - } - *adrp = 0; - } else - die (STATE_CRITICAL, - _("DNS CRITICAL - '%s' msg parsing exited with no address\n"), - NSLOOKUP_COMMAND); - - /* compare to expected address */ - if (result == STATE_OK && expected_address_cnt > 0) { - result = STATE_CRITICAL; - temp_buffer = ""; - unsigned long expect_match = (1 << expected_address_cnt) - 1; - unsigned long addr_match = (1 << n_addresses) - 1; - - for (int i=0; iwarning != NULL) && (time_thresholds->critical != NULL)) { - printf ("|%s\n", fperfdata ("time", elapsed_time, "s", - true, time_thresholds->warning->end, - true, time_thresholds->critical->end, - true, 0, false, 0)); - } else if ((time_thresholds->warning == NULL) && (time_thresholds->critical != NULL)) { - printf ("|%s\n", fperfdata ("time", elapsed_time, "s", - false, 0, - true, time_thresholds->critical->end, - true, 0, false, 0)); - } else if ((time_thresholds->warning != NULL) && (time_thresholds->critical == NULL)) { - printf ("|%s\n", fperfdata ("time", elapsed_time, "s", - true, time_thresholds->warning->end, - false, 0, - true, 0, false, 0)); - } else - printf ("|%s\n", fperfdata ("time", elapsed_time, "s", false, 0, false, 0, true, 0, false, 0)); - } - else if (result == STATE_WARNING) - printf (_("DNS WARNING - %s\n"), - !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg); - else if (result == STATE_CRITICAL) - printf (_("DNS CRITICAL - %s\n"), - !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg); - else - printf (_("DNS UNKNOWN - %s\n"), - !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg); - - return result; + if (addresses) { + int i, slen; + char *adrp; + qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp); + for (i = 0, slen = 1; i < n_addresses; i++) { + slen += strlen(addresses[i]) + 1; + } + adrp = address = malloc(slen); + for (i = 0; i < n_addresses; i++) { + if (i) + *adrp++ = ','; + strcpy(adrp, addresses[i]); + adrp += strlen(addresses[i]); + } + *adrp = 0; + } else + die(STATE_CRITICAL, _("DNS CRITICAL - '%s' msg parsing exited with no address\n"), NSLOOKUP_COMMAND); + + /* compare to expected address */ + if (result == STATE_OK && expected_address_cnt > 0) { + result = STATE_CRITICAL; + temp_buffer = ""; + unsigned long expect_match = (1 << expected_address_cnt) - 1; + unsigned long addr_match = (1 << n_addresses) - 1; + + for (int i = 0; i < expected_address_cnt; i++) { + int j; + /* check if we get a match on 'raw' ip or cidr */ + for (j = 0; j < n_addresses; j++) { + if (strcmp(addresses[j], expected_address[i]) == 0 || ip_match_cidr(addresses[j], expected_address[i])) { + result = STATE_OK; + addr_match &= ~(1 << j); + expect_match &= ~(1 << i); + } + } + + /* prepare an error string */ + xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]); + } + /* check if expected_address must cover all in addresses and none may be missing */ + if (all_match && (expect_match != 0 || addr_match != 0)) + result = STATE_CRITICAL; + if (result == STATE_CRITICAL) { + /* Strip off last semicolon... */ + temp_buffer[strlen(temp_buffer) - 2] = '\0'; + xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address); + } + } + + if (expect_nxdomain) { + if (!is_nxdomain) { + result = STATE_CRITICAL; + xasprintf(&msg, _("Domain '%s' was found by the server: '%s'\n"), query_address, address); + } else { + if (address != NULL) + free(address); + address = "NXDOMAIN"; + } + } + + /* check if authoritative */ + if (result == STATE_OK && expect_authority && non_authoritative) { + result = STATE_CRITICAL; + xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address); + } + + microsec = deltime(tv); + elapsed_time = (double)microsec / 1.0e6; + + if (result == STATE_OK) { + result = get_status(elapsed_time, time_thresholds); + if (result == STATE_OK) { + printf("DNS %s: ", _("OK")); + } else if (result == STATE_WARNING) { + printf("DNS %s: ", _("WARNING")); + } else if (result == STATE_CRITICAL) { + printf("DNS %s: ", _("CRITICAL")); + } + printf(ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time); + printf(_(". %s returns %s"), query_address, address); + if ((time_thresholds->warning != NULL) && (time_thresholds->critical != NULL)) { + printf("|%s\n", fperfdata("time", elapsed_time, "s", true, time_thresholds->warning->end, true, time_thresholds->critical->end, + true, 0, false, 0)); + } else if ((time_thresholds->warning == NULL) && (time_thresholds->critical != NULL)) { + printf("|%s\n", fperfdata("time", elapsed_time, "s", false, 0, true, time_thresholds->critical->end, true, 0, false, 0)); + } else if ((time_thresholds->warning != NULL) && (time_thresholds->critical == NULL)) { + printf("|%s\n", fperfdata("time", elapsed_time, "s", true, time_thresholds->warning->end, false, 0, true, 0, false, 0)); + } else + printf("|%s\n", fperfdata("time", elapsed_time, "s", false, 0, false, 0, true, 0, false, 0)); + } else if (result == STATE_WARNING) + printf(_("DNS WARNING - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg); + else if (result == STATE_CRITICAL) + printf(_("DNS CRITICAL - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg); + else + printf(_("DNS UNKNOWN - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg); + + return result; } bool ip_match_cidr(const char *addr, const char *cidr_ro) { - char *subnet, *mask_c, *cidr = strdup(cidr_ro); - int mask; - subnet = strtok(cidr, "/"); - mask_c = strtok(NULL, "\0"); - if (!subnet || !mask_c) { - return false; + char *subnet, *mask_c, *cidr = strdup(cidr_ro); + int mask; + subnet = strtok(cidr, "/"); + mask_c = strtok(NULL, "\0"); + if (!subnet || !mask_c) { + return false; } - mask = atoi(mask_c); + mask = atoi(mask_c); - /* https://www.cryptobells.com/verifying-ips-in-a-subnet-in-php/ */ - return (ip2long(addr) & ~((1 << (32 - mask)) - 1)) == (ip2long(subnet) >> (32 - mask)) << (32 - mask); + /* https://www.cryptobells.com/verifying-ips-in-a-subnet-in-php/ */ + return (ip2long(addr) & ~((1 << (32 - mask)) - 1)) == (ip2long(subnet) >> (32 - mask)) << (32 - mask); } -unsigned long -ip2long(const char* src) { - unsigned long ip[4]; - /* http://computer-programming-forum.com/47-c-language/1376ffb92a12c471.htm */ - return (sscanf(src, "%3lu.%3lu.%3lu.%3lu", - &ip[0], &ip[1], &ip[2], &ip[3]) == 4 && - ip[0] < 256 && ip[1] < 256 && - ip[2] < 256 && ip[3] < 256) - ? ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3] - : 0; +unsigned long ip2long(const char *src) { + unsigned long ip[4]; + /* http://computer-programming-forum.com/47-c-language/1376ffb92a12c471.htm */ + return (sscanf(src, "%3lu.%3lu.%3lu.%3lu", &ip[0], &ip[1], &ip[2], &ip[3]) == 4 && ip[0] < 256 && ip[1] < 256 && ip[2] < 256 && + ip[3] < 256) + ? ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3] + : 0; } -int -error_scan (char *input_buffer, bool *is_nxdomain) -{ - - const int nxdomain = strstr (input_buffer, "Non-existent") || - strstr (input_buffer, "** server can't find") || - strstr (input_buffer, "** Can't find") || - strstr (input_buffer, "NXDOMAIN"); - if (nxdomain) *is_nxdomain = true; - - /* the DNS lookup timed out */ - if (strstr (input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) || - strstr (input_buffer, _("Consider using the `dig' or `host' programs instead. Run nslookup with")) || - strstr (input_buffer, _("the `-sil[ent]' option to prevent this message from appearing."))) - return STATE_OK; - - /* DNS server is not running... */ - else if (strstr (input_buffer, "No response from server")) - die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server); - else if (strstr (input_buffer, "no servers could be reached")) - die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server); - - /* Host name is valid, but server doesn't have records... */ - else if (strstr (input_buffer, "No records")) - die (STATE_CRITICAL, _("DNS %s has no records\n"), dns_server); - - /* Connection was refused */ - else if (strstr (input_buffer, "Connection refused") || - strstr (input_buffer, "Couldn't find server") || - strstr (input_buffer, "Refused") || - (strstr (input_buffer, "** server can't find") && - strstr (input_buffer, ": REFUSED"))) - die (STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server); - - /* Query refused (usually by an ACL in the namserver) */ - else if (strstr (input_buffer, "Query refused")) - die (STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server); - - /* No information (e.g. nameserver IP has two PTR records) */ - else if (strstr (input_buffer, "No information")) - die (STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server); - - /* Network is unreachable */ - else if (strstr (input_buffer, "Network is unreachable")) - die (STATE_CRITICAL, _("Network is unreachable\n")); - - /* Internal server failure */ - else if (strstr (input_buffer, "Server failure")) - die (STATE_CRITICAL, _("DNS failure for %s\n"), dns_server); - - /* Request error or the DNS lookup timed out */ - else if (strstr (input_buffer, "Format error") || - strstr (input_buffer, "Timed out")) - return STATE_WARNING; - - return STATE_OK; +int error_scan(char *input_buffer, bool *is_nxdomain) { -} + const int nxdomain = strstr(input_buffer, "Non-existent") || strstr(input_buffer, "** server can't find") || + strstr(input_buffer, "** Can't find") || strstr(input_buffer, "NXDOMAIN"); + if (nxdomain) + *is_nxdomain = true; + + /* the DNS lookup timed out */ + if (strstr(input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) || + strstr(input_buffer, _("Consider using the `dig' or `host' programs instead. Run nslookup with")) || + strstr(input_buffer, _("the `-sil[ent]' option to prevent this message from appearing."))) + return STATE_OK; + + /* DNS server is not running... */ + else if (strstr(input_buffer, "No response from server")) + die(STATE_CRITICAL, _("No response from DNS %s\n"), dns_server); + else if (strstr(input_buffer, "no servers could be reached")) + die(STATE_CRITICAL, _("No response from DNS %s\n"), dns_server); + + /* Host name is valid, but server doesn't have records... */ + else if (strstr(input_buffer, "No records")) + die(STATE_CRITICAL, _("DNS %s has no records\n"), dns_server); + + /* Connection was refused */ + else if (strstr(input_buffer, "Connection refused") || strstr(input_buffer, "Couldn't find server") || + strstr(input_buffer, "Refused") || (strstr(input_buffer, "** server can't find") && strstr(input_buffer, ": REFUSED"))) + die(STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server); + + /* Query refused (usually by an ACL in the namserver) */ + else if (strstr(input_buffer, "Query refused")) + die(STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server); + + /* No information (e.g. nameserver IP has two PTR records) */ + else if (strstr(input_buffer, "No information")) + die(STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server); + + /* Network is unreachable */ + else if (strstr(input_buffer, "Network is unreachable")) + die(STATE_CRITICAL, _("Network is unreachable\n")); + + /* Internal server failure */ + else if (strstr(input_buffer, "Server failure")) + die(STATE_CRITICAL, _("DNS failure for %s\n"), dns_server); + /* Request error or the DNS lookup timed out */ + else if (strstr(input_buffer, "Format error") || strstr(input_buffer, "Timed out")) + return STATE_WARNING; + + return STATE_OK; +} /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ - int c; - char *warning = NULL; - char *critical = NULL; - - int opt_index = 0; - static struct option long_opts[] = { - {"help", no_argument, 0, 'h'}, - {"version", no_argument, 0, 'V'}, - {"verbose", no_argument, 0, 'v'}, - {"timeout", required_argument, 0, 't'}, - {"hostname", required_argument, 0, 'H'}, - {"server", required_argument, 0, 's'}, - {"reverse-server", required_argument, 0, 'r'}, - {"expected-address", required_argument, 0, 'a'}, - {"expect-nxdomain", no_argument, 0, 'n'}, - {"expect-authority", no_argument, 0, 'A'}, - {"all", no_argument, 0, 'L'}, - {"warning", required_argument, 0, 'w'}, - {"critical", required_argument, 0, 'c'}, - {0, 0, 0, 0} - }; - - if (argc < 2) - return ERROR; - - for (c = 1; c < argc; c++) - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - - while (1) { - c = getopt_long (argc, argv, "hVvALnt:H:s:r:a:w:c:", long_opts, &opt_index); - - if (c == -1 || c == EOF) - break; - - switch (c) { - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'v': /* version */ - verbose = true; - break; - case 't': /* timeout period */ - timeout_interval = atoi (optarg); - break; - case 'H': /* hostname */ - if (strlen (optarg) >= ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - strcpy (query_address, optarg); - break; - case 's': /* server name */ - /* TODO: this host_or_die check is probably unnecessary. - * Better to confirm nslookup response matches */ - host_or_die(optarg); - if (strlen (optarg) >= ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - strcpy (dns_server, optarg); - break; - case 'r': /* reverse server name */ - /* TODO: Is this host_or_die necessary? */ - host_or_die(optarg); - if (strlen (optarg) >= ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - strcpy (ptr_server, optarg); - break; - case 'a': /* expected address */ - if (strlen (optarg) >= ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - if (strchr(optarg, ',') != NULL) { - char *comma = strchr(optarg, ','); - while (comma != NULL) { - expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); - expected_address[expected_address_cnt] = strndup(optarg, comma - optarg); - expected_address_cnt++; - optarg = comma + 1; - comma = strchr(optarg, ','); +int process_arguments(int argc, char **argv) { + int c; + char *warning = NULL; + char *critical = NULL; + + int opt_index = 0; + static struct option long_opts[] = {{"help", no_argument, 0, 'h'}, + {"version", no_argument, 0, 'V'}, + {"verbose", no_argument, 0, 'v'}, + {"timeout", required_argument, 0, 't'}, + {"hostname", required_argument, 0, 'H'}, + {"server", required_argument, 0, 's'}, + {"reverse-server", required_argument, 0, 'r'}, + {"expected-address", required_argument, 0, 'a'}, + {"expect-nxdomain", no_argument, 0, 'n'}, + {"expect-authority", no_argument, 0, 'A'}, + {"all", no_argument, 0, 'L'}, + {"warning", required_argument, 0, 'w'}, + {"critical", required_argument, 0, 'c'}, + {0, 0, 0, 0}}; + + if (argc < 2) + return ERROR; + + for (c = 1; c < argc; c++) + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + + while (1) { + c = getopt_long(argc, argv, "hVvALnt:H:s:r:a:w:c:", long_opts, &opt_index); + + if (c == -1 || c == EOF) + break; + + switch (c) { + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'v': /* version */ + verbose = true; + break; + case 't': /* timeout period */ + timeout_interval = atoi(optarg); + break; + case 'H': /* hostname */ + if (strlen(optarg) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + strcpy(query_address, optarg); + break; + case 's': /* server name */ + /* TODO: this host_or_die check is probably unnecessary. + * Better to confirm nslookup response matches */ + host_or_die(optarg); + if (strlen(optarg) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + strcpy(dns_server, optarg); + break; + case 'r': /* reverse server name */ + /* TODO: Is this host_or_die necessary? */ + host_or_die(optarg); + if (strlen(optarg) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + strcpy(ptr_server, optarg); + break; + case 'a': /* expected address */ + if (strlen(optarg) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + if (strchr(optarg, ',') != NULL) { + char *comma = strchr(optarg, ','); + while (comma != NULL) { + expected_address = (char **)realloc(expected_address, (expected_address_cnt + 1) * sizeof(char **)); + expected_address[expected_address_cnt] = strndup(optarg, comma - optarg); + expected_address_cnt++; + optarg = comma + 1; + comma = strchr(optarg, ','); + } + expected_address = (char **)realloc(expected_address, (expected_address_cnt + 1) * sizeof(char **)); + expected_address[expected_address_cnt] = strdup(optarg); + expected_address_cnt++; + } else { + expected_address = (char **)realloc(expected_address, (expected_address_cnt + 1) * sizeof(char **)); + expected_address[expected_address_cnt] = strdup(optarg); + expected_address_cnt++; + } + break; + case 'n': /* expect NXDOMAIN */ + expect_nxdomain = true; + break; + case 'A': /* expect authority */ + expect_authority = true; + break; + case 'L': /* all must match */ + all_match = true; + break; + case 'w': + warning = optarg; + break; + case 'c': + critical = optarg; + break; + default: /* args not parsable */ + usage5(); + } } - expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); - expected_address[expected_address_cnt] = strdup(optarg); - expected_address_cnt++; - } else { - expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); - expected_address[expected_address_cnt] = strdup(optarg); - expected_address_cnt++; - } - break; - case 'n': /* expect NXDOMAIN */ - expect_nxdomain = true; - break; - case 'A': /* expect authority */ - expect_authority = true; - break; - case 'L': /* all must match */ - all_match = true; - break; - case 'w': - warning = optarg; - break; - case 'c': - critical = optarg; - break; - default: /* args not parsable */ - usage5(); - } - } - - c = optind; - if (strlen(query_address)==0 && c=ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - strcpy (query_address, argv[c++]); - } - - if (strlen(dns_server)==0 && c= ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - strcpy (dns_server, argv[c++]); - } - - set_thresholds(&time_thresholds, warning, critical); - - return validate_arguments (); -} + c = optind; + if (strlen(query_address) == 0 && c < argc) { + if (strlen(argv[c]) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + strcpy(query_address, argv[c++]); + } -int -validate_arguments () -{ - if (query_address[0] == 0) { - printf ("missing --host argument\n"); - return ERROR; - } + if (strlen(dns_server) == 0 && c < argc) { + /* TODO: See -s option */ + host_or_die(argv[c]); + if (strlen(argv[c]) >= ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + strcpy(dns_server, argv[c++]); + } - if (expected_address_cnt > 0 && expect_nxdomain) { - printf ("--expected-address and --expect-nxdomain cannot be combined\n"); - return ERROR; - } + set_thresholds(&time_thresholds, warning, critical); - return OK; + return validate_arguments(); } +int validate_arguments() { + if (query_address[0] == 0) { + printf("missing --host argument\n"); + return ERROR; + } + + if (expected_address_cnt > 0 && expect_nxdomain) { + printf("--expected-address and --expect-nxdomain cannot be combined\n"); + return ERROR; + } -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); - - printf ("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query.")); - printf ("%s\n", _("An optional DNS server to use may be specified.")); - printf ("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used.")); - - printf ("\n\n"); - - print_usage (); - - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - - printf (" -H, --hostname=HOST\n"); - printf (" %s\n", _("The name or address you want to query")); - printf (" -s, --server=HOST\n"); - printf (" %s\n", _("Optional DNS server you want to use for the lookup")); - printf (" -a, --expected-address=IP-ADDRESS|CIDR|HOST\n"); - printf (" %s\n", _("Optional IP-ADDRESS/CIDR you expect the DNS server to return. HOST must end")); - printf (" %s\n", _("with a dot (.). This option can be repeated multiple times (Returns OK if any")); - printf (" %s\n", _("value matches).")); - printf (" -n, --expect-nxdomain\n"); - printf (" %s\n", _("Expect the DNS server to return NXDOMAIN (i.e. the domain was not found)")); - printf (" %s\n", _("Cannot be used together with -a")); - printf (" -A, --expect-authority\n"); - printf (" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup")); - printf (" -w, --warning=seconds\n"); - printf (" %s\n", _("Return warning if elapsed time exceeds value. Default off")); - printf (" -c, --critical=seconds\n"); - printf (" %s\n", _("Return critical if elapsed time exceeds value. Default off")); - printf (" -L, --all\n"); - printf (" %s\n", _("Return critical if the list of expected addresses does not match all addresses")); - printf (" %s\n", _("returned. Default off")); - - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - - printf (UT_SUPPORT); + return OK; } +void print_help(void) { + print_revision(progname, NP_VERSION); + + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); + + printf("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query.")); + printf("%s\n", _("An optional DNS server to use may be specified.")); + printf("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used.")); + + printf("\n\n"); + + print_usage(); + + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf(" -H, --hostname=HOST\n"); + printf(" %s\n", _("The name or address you want to query")); + printf(" -s, --server=HOST\n"); + printf(" %s\n", _("Optional DNS server you want to use for the lookup")); + printf(" -a, --expected-address=IP-ADDRESS|CIDR|HOST\n"); + printf(" %s\n", _("Optional IP-ADDRESS/CIDR you expect the DNS server to return. HOST must end")); + printf(" %s\n", _("with a dot (.). This option can be repeated multiple times (Returns OK if any")); + printf(" %s\n", _("value matches).")); + printf(" -n, --expect-nxdomain\n"); + printf(" %s\n", _("Expect the DNS server to return NXDOMAIN (i.e. the domain was not found)")); + printf(" %s\n", _("Cannot be used together with -a")); + printf(" -A, --expect-authority\n"); + printf(" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup")); + printf(" -w, --warning=seconds\n"); + printf(" %s\n", _("Return warning if elapsed time exceeds value. Default off")); + printf(" -c, --critical=seconds\n"); + printf(" %s\n", _("Return critical if elapsed time exceeds value. Default off")); + printf(" -L, --all\n"); + printf(" %s\n", _("Return critical if the list of expected addresses does not match all addresses")); + printf(" %s\n", _("returned. Default off")); + + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + + printf(UT_SUPPORT); +} -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H host [-s server] [-a expected-address] [-n] [-A] [-t timeout] [-w warn] [-c crit] [-L]\n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H host [-s server] [-a expected-address] [-n] [-A] [-t timeout] [-w warn] [-c crit] [-L]\n", progname); } -- cgit v1.2.3-74-g34f1 From 702dc596a4a6ed124751c55cbd5c62f96ae8a157 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:30:42 +0100 Subject: check_dns: do not export local variables --- plugins/check_dns.c | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/plugins/check_dns.c b/plugins/check_dns.c index 7cd23162..911853b9 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -39,26 +39,26 @@ const char *email = "devel@monitoring-plugins.org"; #include "netutils.h" #include "runcmd.h" -int process_arguments(int, char **); -int validate_arguments(void); -int error_scan(char *, bool *); -bool ip_match_cidr(const char *, const char *); -unsigned long ip2long(const char *); -void print_help(void); +static int process_arguments(int, char **); +static int validate_arguments(void); +static int error_scan(char *, bool *); +static bool ip_match_cidr(const char *, const char *); +static unsigned long ip2long(const char *); +static void print_help(void); void print_usage(void); #define ADDRESS_LENGTH 256 -char query_address[ADDRESS_LENGTH] = ""; -char dns_server[ADDRESS_LENGTH] = ""; -char ptr_server[ADDRESS_LENGTH] = ""; -bool verbose = false; -char **expected_address = NULL; -int expected_address_cnt = 0; -bool expect_nxdomain = false; - -bool expect_authority = false; -bool all_match = false; -thresholds *time_thresholds = NULL; +static char query_address[ADDRESS_LENGTH] = ""; +static char dns_server[ADDRESS_LENGTH] = ""; +static char ptr_server[ADDRESS_LENGTH] = ""; +static bool verbose = false; +static char **expected_address = NULL; +static int expected_address_cnt = 0; +static bool expect_nxdomain = false; + +static bool expect_authority = false; +static bool all_match = false; +static thresholds *time_thresholds = NULL; static int qstrcmp(const void *p1, const void *p2) { /* The actual arguments to this function are "pointers to -- cgit v1.2.3-74-g34f1 From 4f34506c81484673bf3623d1c3a8100dc1761e8c Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:33:10 +0100 Subject: check_dns: Linter fixes --- plugins/check_dns.c | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/plugins/check_dns.c b/plugins/check_dns.c index 911853b9..e5ca581b 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -39,11 +39,11 @@ const char *email = "devel@monitoring-plugins.org"; #include "netutils.h" #include "runcmd.h" -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static int validate_arguments(void); -static int error_scan(char *, bool *); -static bool ip_match_cidr(const char *, const char *); -static unsigned long ip2long(const char *); +static int error_scan(char * /*input_buffer*/, bool *); +static bool ip_match_cidr(const char * /*addr*/, const char * /*cidr_ro*/); +static unsigned long ip2long(const char * /*src*/); static void print_help(void); void print_usage(void); @@ -81,7 +81,8 @@ int main(int argc, char **argv) { long microsec; struct timeval tv; bool parse_address = false; /* This flag scans for Address: but only after Name: */ - output chld_out, chld_err; + output chld_out; + output chld_err; bool is_nxdomain = false; setlocale(LC_ALL, ""); @@ -204,7 +205,8 @@ int main(int argc, char **argv) { } if (addresses) { - int i, slen; + int i; + int slen; char *adrp; qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp); for (i = 0, slen = 1; i < n_addresses; i++) { @@ -303,7 +305,9 @@ int main(int argc, char **argv) { } bool ip_match_cidr(const char *addr, const char *cidr_ro) { - char *subnet, *mask_c, *cidr = strdup(cidr_ro); + char *subnet; + char *mask_c; + char *cidr = strdup(cidr_ro); int mask; subnet = strtok(cidr, "/"); mask_c = strtok(NULL, "\0"); @@ -505,7 +509,7 @@ int process_arguments(int argc, char **argv) { return validate_arguments(); } -int validate_arguments() { +int validate_arguments(void) { if (query_address[0] == 0) { printf("missing --host argument\n"); return ERROR; -- cgit v1.2.3-74-g34f1 From 078e9b96adce9a9ae10535e496a743288eb8c9f2 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:33:51 +0100 Subject: check_dns: update copyright --- plugins/check_dns.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_dns.c b/plugins/check_dns.c index e5ca581b..e1e7c00e 100644 --- a/plugins/check_dns.c +++ b/plugins/check_dns.c @@ -3,7 +3,7 @@ * Monitoring check_dns plugin * * License: GPL - * Copyright (c) 2000-2008 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_dns"; -const char *copyright = "2000-2008"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From 31133c789c609f510a8490032633b4be822060fc Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:34:46 +0100 Subject: check_dummy: clang-format --- plugins/check_dummy.c | 193 +++++++++++++++++++++++--------------------------- 1 file changed, 90 insertions(+), 103 deletions(-) diff --git a/plugins/check_dummy.c b/plugins/check_dummy.c index 212a1344..1d9d2abb 100644 --- a/plugins/check_dummy.c +++ b/plugins/check_dummy.c @@ -1,32 +1,32 @@ /***************************************************************************** -* -* Monitoring check_dummy plugin -* -* License: GPL -* Copyright (c) 1999-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_dummy plugin -* -* This plugin will simply return the state corresponding to the numeric value -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_dummy plugin + * + * License: GPL + * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_dummy plugin + * + * This plugin will simply return the state corresponding to the numeric value + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_dummy"; const char *copyright = "1999-2007"; @@ -35,90 +35,77 @@ const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "utils.h" -void print_help (void); -void print_usage (void); - - -int -main (int argc, char **argv) -{ - int result = STATE_UNKNOWN; - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - if (argc < 2) - usage4 (_("Could not parse arguments")); - else if (strcmp (argv[1], "-V") == 0 || strcmp (argv[1], "--version") == 0) { - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - } - else if (strcmp (argv[1], "-h") == 0 || strcmp (argv[1], "--help") == 0) { - print_help (); - exit (STATE_UNKNOWN); - } - else if (!is_integer (argv[1])) - usage4 (_("Arguments to check_dummy must be an integer")); - else - result = atoi (argv[1]); - - switch (result) { - case STATE_OK: - printf (_("OK")); - break; - case STATE_WARNING: - printf (_("WARNING")); - break; - case STATE_CRITICAL: - printf (_("CRITICAL")); - break; - case STATE_UNKNOWN: - printf (_("UNKNOWN")); - break; - default: - printf (_("UNKNOWN")); - printf (": "); - printf (_("Status %d is not a supported error state\n"), result); - return STATE_UNKNOWN; - } - - if (argc >= 3) - printf (": %s", argv[2]); - - printf("\n"); - - return result; +void print_help(void); +void print_usage(void); + +int main(int argc, char **argv) { + int result = STATE_UNKNOWN; + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + if (argc < 2) + usage4(_("Could not parse arguments")); + else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0) { + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + } else if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) { + print_help(); + exit(STATE_UNKNOWN); + } else if (!is_integer(argv[1])) + usage4(_("Arguments to check_dummy must be an integer")); + else + result = atoi(argv[1]); + + switch (result) { + case STATE_OK: + printf(_("OK")); + break; + case STATE_WARNING: + printf(_("WARNING")); + break; + case STATE_CRITICAL: + printf(_("CRITICAL")); + break; + case STATE_UNKNOWN: + printf(_("UNKNOWN")); + break; + default: + printf(_("UNKNOWN")); + printf(": "); + printf(_("Status %d is not a supported error state\n"), result); + return STATE_UNKNOWN; + } + + if (argc >= 3) + printf(": %s", argv[2]); + + printf("\n"); + + return result; } +void print_help(void) { + print_revision(progname, NP_VERSION); + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); -void -print_help (void) -{ - print_revision (progname, NP_VERSION); + printf("%s\n", _("This plugin will simply return the state corresponding to the numeric value")); - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); + printf("%s\n", _("of the argument with optional text")); - printf ("%s\n", _("This plugin will simply return the state corresponding to the numeric value")); + printf("\n\n"); - printf ("%s\n", _("of the argument with optional text")); + print_usage(); - printf ("\n\n"); + printf(UT_HELP_VRSN); - print_usage (); - - printf (UT_HELP_VRSN); - - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s [optional text]\n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s [optional text]\n", progname); } -- cgit v1.2.3-74-g34f1 From 1633fd73bde6f2a2899b2f20d2e07683d5ea13ce Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:35:18 +0100 Subject: check_dummy: update copyright --- plugins/check_dummy.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_dummy.c b/plugins/check_dummy.c index 1d9d2abb..92622384 100644 --- a/plugins/check_dummy.c +++ b/plugins/check_dummy.c @@ -3,7 +3,7 @@ * Monitoring check_dummy plugin * * License: GPL - * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * Copyright (c) 1999-2024 Monitoring Plugins Development Team * * Description: * @@ -29,7 +29,7 @@ *****************************************************************************/ const char *progname = "check_dummy"; -const char *copyright = "1999-2007"; +const char *copyright = "1999-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From 5f2ae6d5e5240570de28a344fea2e822e1fa0bf4 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:36:00 +0100 Subject: check_dummy: do not export local symbols --- plugins/check_dummy.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/check_dummy.c b/plugins/check_dummy.c index 92622384..19f6c046 100644 --- a/plugins/check_dummy.c +++ b/plugins/check_dummy.c @@ -35,7 +35,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "utils.h" -void print_help(void); +static void print_help(void); void print_usage(void); int main(int argc, char **argv) { -- cgit v1.2.3-74-g34f1 From 82975ac988cad3f555fb381da98fc3b018a5769f Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:36:59 +0100 Subject: check_fping: clang-format --- plugins/check_fping.c | 881 ++++++++++++++++++++++++-------------------------- 1 file changed, 421 insertions(+), 460 deletions(-) diff --git a/plugins/check_fping.c b/plugins/check_fping.c index 70d6f9fc..ec151143 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_fping plugin -* -* License: GPL -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_disk plugin -* -* This plugin will use the fping command to ping the specified host for a -* fast check -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_fping plugin + * + * License: GPL + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_disk plugin + * + * This plugin will use the fping command to ping the specified host for a + * fast check + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_fping"; const char *copyright = "2000-2007"; @@ -40,17 +40,17 @@ const char *email = "devel@monitoring-plugins.org"; #include enum { - PACKET_COUNT = 1, - PACKET_SIZE = 56, - PL = 0, - RTA = 1 + PACKET_COUNT = 1, + PACKET_SIZE = 56, + PL = 0, + RTA = 1 }; -int textscan (char *buf); -int process_arguments (int, char **); -int get_threshold (char *arg, char *rv[2]); -void print_help (void); -void print_usage (void); +int textscan(char *buf); +int process_arguments(int, char **); +int get_threshold(char *arg, char *rv[2]); +void print_help(void); +void print_usage(void); char *server_name = NULL; char *sourceip = NULL; @@ -70,458 +70,419 @@ bool alive_p = false; bool crta_p = false; bool wrta_p = false; -int -main (int argc, char **argv) -{ -/* normally should be int result = STATE_UNKNOWN; */ - - int status = STATE_UNKNOWN; - int result = 0; - char *fping_prog = NULL; - char *server = NULL; - char *command_line = NULL; - char *input_buffer = NULL; - char *option_string = ""; - input_buffer = malloc (MAX_INPUT_BUFFER); - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); - - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); - - server = strscpy (server, server_name); - - /* compose the command */ - if (target_timeout) - xasprintf(&option_string, "%s-t %d ", option_string, target_timeout); - if (packet_interval) - xasprintf(&option_string, "%s-p %d ", option_string, packet_interval); - if (sourceip) - xasprintf(&option_string, "%s-S %s ", option_string, sourceip); - if (sourceif) - xasprintf(&option_string, "%s-I %s ", option_string, sourceif); +int main(int argc, char **argv) { + /* normally should be int result = STATE_UNKNOWN; */ + + int status = STATE_UNKNOWN; + int result = 0; + char *fping_prog = NULL; + char *server = NULL; + char *command_line = NULL; + char *input_buffer = NULL; + char *option_string = ""; + input_buffer = malloc(MAX_INPUT_BUFFER); + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); + + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); + + server = strscpy(server, server_name); + + /* compose the command */ + if (target_timeout) + xasprintf(&option_string, "%s-t %d ", option_string, target_timeout); + if (packet_interval) + xasprintf(&option_string, "%s-p %d ", option_string, packet_interval); + if (sourceip) + xasprintf(&option_string, "%s-S %s ", option_string, sourceip); + if (sourceif) + xasprintf(&option_string, "%s-I %s ", option_string, sourceif); #ifdef PATH_TO_FPING6 - if (address_family != AF_INET && is_inet6_addr(server)) - fping_prog = strdup(PATH_TO_FPING6); - else - fping_prog = strdup(PATH_TO_FPING); + if (address_family != AF_INET && is_inet6_addr(server)) + fping_prog = strdup(PATH_TO_FPING6); + else + fping_prog = strdup(PATH_TO_FPING); #else - fping_prog = strdup(PATH_TO_FPING); + fping_prog = strdup(PATH_TO_FPING); #endif - xasprintf (&command_line, "%s %s-b %d -c %d %s", fping_prog, - option_string, packet_size, packet_count, server); - - if (verbose) - printf ("%s\n", command_line); - - /* run the command */ - child_process = spopen (command_line); - if (child_process == NULL) { - printf (_("Could not open pipe: %s\n"), command_line); - return STATE_UNKNOWN; - } - - child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); - if (child_stderr == NULL) { - printf (_("Could not open stderr for %s\n"), command_line); - } - - while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { - if (verbose) - printf ("%s", input_buffer); - status = max_state (status, textscan (input_buffer)); - } - - /* If we get anything on STDERR, at least set warning */ - while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { - status = max_state (status, STATE_WARNING); - if (verbose) - printf ("%s", input_buffer); - status = max_state (status, textscan (input_buffer)); - } - (void) fclose (child_stderr); - - /* close the pipe */ - result = spclose (child_process); - if (result) { - /* need to use max_state not max */ - status = max_state (status, STATE_WARNING); - } - - if (result > 1 ) { - status = max_state (status, STATE_UNKNOWN); - if (result == 2) { - die (STATE_UNKNOWN, _("FPING UNKNOWN - IP address not found\n")); - } - if (result == 3) { - die (STATE_UNKNOWN, _("FPING UNKNOWN - invalid commandline argument\n")); - } - if (result == 4) { - die (STATE_UNKNOWN, _("FPING UNKNOWN - failed system call\n")); - } - - } - - printf ("FPING %s - %s\n", state_text (status), server_name); - - return status; + xasprintf(&command_line, "%s %s-b %d -c %d %s", fping_prog, option_string, packet_size, packet_count, server); + + if (verbose) + printf("%s\n", command_line); + + /* run the command */ + child_process = spopen(command_line); + if (child_process == NULL) { + printf(_("Could not open pipe: %s\n"), command_line); + return STATE_UNKNOWN; + } + + child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r"); + if (child_stderr == NULL) { + printf(_("Could not open stderr for %s\n"), command_line); + } + + while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { + if (verbose) + printf("%s", input_buffer); + status = max_state(status, textscan(input_buffer)); + } + + /* If we get anything on STDERR, at least set warning */ + while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { + status = max_state(status, STATE_WARNING); + if (verbose) + printf("%s", input_buffer); + status = max_state(status, textscan(input_buffer)); + } + (void)fclose(child_stderr); + + /* close the pipe */ + result = spclose(child_process); + if (result) { + /* need to use max_state not max */ + status = max_state(status, STATE_WARNING); + } + + if (result > 1) { + status = max_state(status, STATE_UNKNOWN); + if (result == 2) { + die(STATE_UNKNOWN, _("FPING UNKNOWN - IP address not found\n")); + } + if (result == 3) { + die(STATE_UNKNOWN, _("FPING UNKNOWN - invalid commandline argument\n")); + } + if (result == 4) { + die(STATE_UNKNOWN, _("FPING UNKNOWN - failed system call\n")); + } + } + + printf("FPING %s - %s\n", state_text(status), server_name); + + return status; } - -int textscan (char *buf) { - char *rtastr = NULL; - char *losstr = NULL; - char *xmtstr = NULL; - double loss; - double rta; - double xmt; - int status = STATE_UNKNOWN; - - /* stops testing after the first successful reply. */ - if (alive_p && strstr(buf, "avg, 0% loss)")) { - rtastr = strstr (buf, "ms ("); - rtastr = 1 + index(rtastr, '('); - rta = strtod(rtastr, NULL); - loss=strtod("0",NULL); - die (STATE_OK, - _("FPING %s - %s (rta=%f ms)|%s\n"), - state_text (STATE_OK), server_name,rta, - /* No loss since we only waited for the first reply - perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100), */ - fperfdata ("rta", rta/1.0e3, "s", wrta_p, wrta/1.0e3, crta_p, crta/1.0e3, true, 0, false, 0)); - } - - if (strstr (buf, "not found")) { - die (STATE_CRITICAL, _("FPING UNKNOWN - %s not found\n"), server_name); - - } - else if (strstr (buf, "is unreachable") || strstr (buf, "Unreachable")) { - die (STATE_CRITICAL, _("FPING CRITICAL - %s is unreachable\n"), - "host"); - - } - else if (strstr (buf, "Operation not permitted") || strstr (buf, "No such device") ) { - die (STATE_UNKNOWN, _("FPING UNKNOWN - %s parameter error\n"), - "host"); - } - else if (strstr (buf, "is down")) { - die (STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name); - - } - else if (strstr (buf, "is alive")) { - status = STATE_OK; - - } - else if (strstr (buf, "xmt/rcv/%loss") && strstr (buf, "min/avg/max")) { - losstr = strstr (buf, "="); - losstr = 1 + strstr (losstr, "/"); - losstr = 1 + strstr (losstr, "/"); - rtastr = strstr (buf, "min/avg/max"); - rtastr = strstr (rtastr, "="); - rtastr = 1 + index (rtastr, '/'); - loss = strtod (losstr, NULL); - rta = strtod (rtastr, NULL); - if (cpl_p && loss > cpl) - status = STATE_CRITICAL; - else if (crta_p && rta > crta) - status = STATE_CRITICAL; - else if (wpl_p && loss > wpl) - status = STATE_WARNING; - else if (wrta_p && rta > wrta) - status = STATE_WARNING; - else - status = STATE_OK; - die (status, - _("FPING %s - %s (loss=%.0f%%, rta=%f ms)|%s %s\n"), - state_text (status), server_name, loss, rta, - perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100), - fperfdata ("rta", rta/1.0e3, "s", wrta_p, wrta/1.0e3, crta_p, crta/1.0e3, true, 0, false, 0)); - - } - else if(strstr (buf, "xmt/rcv/%loss") ) { - /* no min/max/avg if host was unreachable in fping v2.2.b1 */ - /* in v2.4b2: 10.99.0.1 : xmt/rcv/%loss = 0/0/0% */ - losstr = strstr (buf, "="); - xmtstr = 1 + losstr; - xmt = strtod (xmtstr, NULL); - if(xmt == 0) - die (STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name); - losstr = 1 + strstr (losstr, "/"); - losstr = 1 + strstr (losstr, "/"); - loss = strtod (losstr, NULL); - if (atoi(losstr) == 100) - status = STATE_CRITICAL; - else if (cpl_p && loss > cpl) - status = STATE_CRITICAL; - else if (wpl_p && loss > wpl) - status = STATE_WARNING; - else - status = STATE_OK; - /* loss=%.0f%%;%d;%d;0;100 */ - die (status, _("FPING %s - %s (loss=%.0f%% )|%s\n"), - state_text (status), server_name, loss , - perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100)); - - } - else { - status = max_state (status, STATE_WARNING); - } - - return status; +int textscan(char *buf) { + char *rtastr = NULL; + char *losstr = NULL; + char *xmtstr = NULL; + double loss; + double rta; + double xmt; + int status = STATE_UNKNOWN; + + /* stops testing after the first successful reply. */ + if (alive_p && strstr(buf, "avg, 0% loss)")) { + rtastr = strstr(buf, "ms ("); + rtastr = 1 + index(rtastr, '('); + rta = strtod(rtastr, NULL); + loss = strtod("0", NULL); + die(STATE_OK, _("FPING %s - %s (rta=%f ms)|%s\n"), state_text(STATE_OK), server_name, rta, + /* No loss since we only waited for the first reply + perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100), */ + fperfdata("rta", rta / 1.0e3, "s", wrta_p, wrta / 1.0e3, crta_p, crta / 1.0e3, true, 0, false, 0)); + } + + if (strstr(buf, "not found")) { + die(STATE_CRITICAL, _("FPING UNKNOWN - %s not found\n"), server_name); + + } else if (strstr(buf, "is unreachable") || strstr(buf, "Unreachable")) { + die(STATE_CRITICAL, _("FPING CRITICAL - %s is unreachable\n"), "host"); + + } else if (strstr(buf, "Operation not permitted") || strstr(buf, "No such device")) { + die(STATE_UNKNOWN, _("FPING UNKNOWN - %s parameter error\n"), "host"); + } else if (strstr(buf, "is down")) { + die(STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name); + + } else if (strstr(buf, "is alive")) { + status = STATE_OK; + + } else if (strstr(buf, "xmt/rcv/%loss") && strstr(buf, "min/avg/max")) { + losstr = strstr(buf, "="); + losstr = 1 + strstr(losstr, "/"); + losstr = 1 + strstr(losstr, "/"); + rtastr = strstr(buf, "min/avg/max"); + rtastr = strstr(rtastr, "="); + rtastr = 1 + index(rtastr, '/'); + loss = strtod(losstr, NULL); + rta = strtod(rtastr, NULL); + if (cpl_p && loss > cpl) + status = STATE_CRITICAL; + else if (crta_p && rta > crta) + status = STATE_CRITICAL; + else if (wpl_p && loss > wpl) + status = STATE_WARNING; + else if (wrta_p && rta > wrta) + status = STATE_WARNING; + else + status = STATE_OK; + die(status, _("FPING %s - %s (loss=%.0f%%, rta=%f ms)|%s %s\n"), state_text(status), server_name, loss, rta, + perfdata("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100), + fperfdata("rta", rta / 1.0e3, "s", wrta_p, wrta / 1.0e3, crta_p, crta / 1.0e3, true, 0, false, 0)); + + } else if (strstr(buf, "xmt/rcv/%loss")) { + /* no min/max/avg if host was unreachable in fping v2.2.b1 */ + /* in v2.4b2: 10.99.0.1 : xmt/rcv/%loss = 0/0/0% */ + losstr = strstr(buf, "="); + xmtstr = 1 + losstr; + xmt = strtod(xmtstr, NULL); + if (xmt == 0) + die(STATE_CRITICAL, _("FPING CRITICAL - %s is down\n"), server_name); + losstr = 1 + strstr(losstr, "/"); + losstr = 1 + strstr(losstr, "/"); + loss = strtod(losstr, NULL); + if (atoi(losstr) == 100) + status = STATE_CRITICAL; + else if (cpl_p && loss > cpl) + status = STATE_CRITICAL; + else if (wpl_p && loss > wpl) + status = STATE_WARNING; + else + status = STATE_OK; + /* loss=%.0f%%;%d;%d;0;100 */ + die(status, _("FPING %s - %s (loss=%.0f%% )|%s\n"), state_text(status), server_name, loss, + perfdata("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100)); + + } else { + status = max_state(status, STATE_WARNING); + } + + return status; } - - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ - int c; - char *rv[2]; - - int option = 0; - static struct option longopts[] = { - {"hostname", required_argument, 0, 'H'}, - {"sourceip", required_argument, 0, 'S'}, - {"sourceif", required_argument, 0, 'I'}, - {"critical", required_argument, 0, 'c'}, - {"warning", required_argument, 0, 'w'}, - {"alive", no_argument, 0, 'a'}, - {"bytes", required_argument, 0, 'b'}, - {"number", required_argument, 0, 'n'}, - {"target-timeout", required_argument, 0, 'T'}, - {"interval", required_argument, 0, 'i'}, - {"verbose", no_argument, 0, 'v'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {"use-ipv4", no_argument, 0, '4'}, - {"use-ipv6", no_argument, 0, '6'}, - {0, 0, 0, 0} - }; - - rv[PL] = NULL; - rv[RTA] = NULL; - - if (argc < 2) - return ERROR; - - if (!is_option (argv[1])) { - server_name = argv[1]; - argv[1] = argv[0]; - argv = &argv[1]; - argc--; - } - - while (1) { - c = getopt_long (argc, argv, "+hVvaH:S:c:w:b:n:T:i:I:46", longopts, &option); - - if (c == -1 || c == EOF || c == 1) - break; - - switch (c) { - case '?': /* print short usage statement if args not parsable */ - usage5 (); - case 'a': /* host alive mode */ - alive_p = true; - break; - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'v': /* verbose mode */ - verbose = true; - break; - case 'H': /* hostname */ - if (is_host (optarg) == false) { - usage2 (_("Invalid hostname/address"), optarg); - } - server_name = strscpy (server_name, optarg); - break; - case 'S': /* sourceip */ - if (is_host (optarg) == false) { - usage2 (_("Invalid hostname/address"), optarg); - } - sourceip = strscpy (sourceip, optarg); - break; - case 'I': /* sourceip */ - sourceif = strscpy (sourceif, optarg); +int process_arguments(int argc, char **argv) { + int c; + char *rv[2]; + + int option = 0; + static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, + {"sourceip", required_argument, 0, 'S'}, + {"sourceif", required_argument, 0, 'I'}, + {"critical", required_argument, 0, 'c'}, + {"warning", required_argument, 0, 'w'}, + {"alive", no_argument, 0, 'a'}, + {"bytes", required_argument, 0, 'b'}, + {"number", required_argument, 0, 'n'}, + {"target-timeout", required_argument, 0, 'T'}, + {"interval", required_argument, 0, 'i'}, + {"verbose", no_argument, 0, 'v'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {0, 0, 0, 0}}; + + rv[PL] = NULL; + rv[RTA] = NULL; + + if (argc < 2) + return ERROR; + + if (!is_option(argv[1])) { + server_name = argv[1]; + argv[1] = argv[0]; + argv = &argv[1]; + argc--; + } + + while (1) { + c = getopt_long(argc, argv, "+hVvaH:S:c:w:b:n:T:i:I:46", longopts, &option); + + if (c == -1 || c == EOF || c == 1) + break; + + switch (c) { + case '?': /* print short usage statement if args not parsable */ + usage5(); + case 'a': /* host alive mode */ + alive_p = true; + break; + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'v': /* verbose mode */ + verbose = true; + break; + case 'H': /* hostname */ + if (is_host(optarg) == false) { + usage2(_("Invalid hostname/address"), optarg); + } + server_name = strscpy(server_name, optarg); break; - case '4': /* IPv4 only */ - address_family = AF_INET; - break; - case '6': /* IPv6 only */ + case 'S': /* sourceip */ + if (is_host(optarg) == false) { + usage2(_("Invalid hostname/address"), optarg); + } + sourceip = strscpy(sourceip, optarg); + break; + case 'I': /* sourceip */ + sourceif = strscpy(sourceif, optarg); + break; + case '4': /* IPv4 only */ + address_family = AF_INET; + break; + case '6': /* IPv6 only */ #ifdef USE_IPV6 - address_family = AF_INET6; + address_family = AF_INET6; #else - usage (_("IPv6 support not available\n")); + usage(_("IPv6 support not available\n")); #endif - break; - case 'c': - get_threshold (optarg, rv); - if (rv[RTA]) { - crta = strtod (rv[RTA], NULL); - crta_p = true; - rv[RTA] = NULL; - } - if (rv[PL]) { - cpl = atoi (rv[PL]); - cpl_p = true; - rv[PL] = NULL; - } - break; - case 'w': - get_threshold (optarg, rv); - if (rv[RTA]) { - wrta = strtod (rv[RTA], NULL); - wrta_p = true; - rv[RTA] = NULL; - } - if (rv[PL]) { - wpl = atoi (rv[PL]); - wpl_p = true; - rv[PL] = NULL; - } - break; - case 'b': /* bytes per packet */ - if (is_intpos (optarg)) - packet_size = atoi (optarg); - else - usage (_("Packet size must be a positive integer")); - break; - case 'n': /* number of packets */ - if (is_intpos (optarg)) - packet_count = atoi (optarg); - else - usage (_("Packet count must be a positive integer")); - break; - case 'T': /* timeout in msec */ - if (is_intpos (optarg)) - target_timeout = atoi (optarg); - else - usage (_("Target timeout must be a positive integer")); - break; - case 'i': /* interval in msec */ - if (is_intpos (optarg)) - packet_interval = atoi (optarg); - else - usage (_("Interval must be a positive integer")); - break; - } - } - - if (server_name == NULL) - usage4 (_("Hostname was not supplied")); - - return OK; -} + break; + case 'c': + get_threshold(optarg, rv); + if (rv[RTA]) { + crta = strtod(rv[RTA], NULL); + crta_p = true; + rv[RTA] = NULL; + } + if (rv[PL]) { + cpl = atoi(rv[PL]); + cpl_p = true; + rv[PL] = NULL; + } + break; + case 'w': + get_threshold(optarg, rv); + if (rv[RTA]) { + wrta = strtod(rv[RTA], NULL); + wrta_p = true; + rv[RTA] = NULL; + } + if (rv[PL]) { + wpl = atoi(rv[PL]); + wpl_p = true; + rv[PL] = NULL; + } + break; + case 'b': /* bytes per packet */ + if (is_intpos(optarg)) + packet_size = atoi(optarg); + else + usage(_("Packet size must be a positive integer")); + break; + case 'n': /* number of packets */ + if (is_intpos(optarg)) + packet_count = atoi(optarg); + else + usage(_("Packet count must be a positive integer")); + break; + case 'T': /* timeout in msec */ + if (is_intpos(optarg)) + target_timeout = atoi(optarg); + else + usage(_("Target timeout must be a positive integer")); + break; + case 'i': /* interval in msec */ + if (is_intpos(optarg)) + packet_interval = atoi(optarg); + else + usage(_("Interval must be a positive integer")); + break; + } + } + if (server_name == NULL) + usage4(_("Hostname was not supplied")); -int -get_threshold (char *arg, char *rv[2]) -{ - char *arg1 = NULL; - char *arg2 = NULL; - - arg1 = strscpy (arg1, arg); - if (strpbrk (arg1, ",:")) - arg2 = 1 + strpbrk (arg1, ",:"); - - if (arg2) { - arg1[strcspn (arg1, ",:")] = 0; - if (strstr (arg1, "%") && strstr (arg2, "%")) - die (STATE_UNKNOWN, - _("%s: Only one threshold may be packet loss (%s)\n"), progname, - arg); - if (!strstr (arg1, "%") && !strstr (arg2, "%")) - die (STATE_UNKNOWN, - _("%s: Only one threshold must be packet loss (%s)\n"), - progname, arg); - } - - if (arg2 && strstr (arg2, "%")) { - rv[PL] = arg2; - rv[RTA] = arg1; - } - else if (arg2) { - rv[PL] = arg1; - rv[RTA] = arg2; - } - else if (strstr (arg1, "%")) { - rv[PL] = arg1; - } - else { - rv[RTA] = arg1; - } - - return OK; + return OK; } +int get_threshold(char *arg, char *rv[2]) { + char *arg1 = NULL; + char *arg2 = NULL; + + arg1 = strscpy(arg1, arg); + if (strpbrk(arg1, ",:")) + arg2 = 1 + strpbrk(arg1, ",:"); + + if (arg2) { + arg1[strcspn(arg1, ",:")] = 0; + if (strstr(arg1, "%") && strstr(arg2, "%")) + die(STATE_UNKNOWN, _("%s: Only one threshold may be packet loss (%s)\n"), progname, arg); + if (!strstr(arg1, "%") && !strstr(arg2, "%")) + die(STATE_UNKNOWN, _("%s: Only one threshold must be packet loss (%s)\n"), progname, arg); + } + + if (arg2 && strstr(arg2, "%")) { + rv[PL] = arg2; + rv[RTA] = arg1; + } else if (arg2) { + rv[PL] = arg1; + rv[RTA] = arg2; + } else if (strstr(arg1, "%")) { + rv[PL] = arg1; + } else { + rv[RTA] = arg1; + } + + return OK; +} -void print_help (void) { +void print_help(void) { - print_revision (progname, NP_VERSION); + print_revision(progname, NP_VERSION); - printf ("Copyright (c) 1999 Didi Rieder \n"); - printf (COPYRIGHT, copyright, email); + printf("Copyright (c) 1999 Didi Rieder \n"); + printf(COPYRIGHT, copyright, email); - printf ("%s\n", _("This plugin will use the fping command to ping the specified host for a fast check")); + printf("%s\n", _("This plugin will use the fping command to ping the specified host for a fast check")); - printf ("%s\n", _("Note that it is necessary to set the suid flag on fping.")); + printf("%s\n", _("Note that it is necessary to set the suid flag on fping.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (UT_IPv46); + printf(UT_IPv46); - printf (" %s\n", "-H, --hostname=HOST"); - printf (" %s\n", _("name or IP Address of host to ping (IP Address bypasses name lookup, reducing system load)")); - printf (" %s\n", "-w, --warning=THRESHOLD"); - printf (" %s\n", _("warning threshold pair")); - printf (" %s\n", "-c, --critical=THRESHOLD"); - printf (" %s\n", _("critical threshold pair")); - printf (" %s\n", "-a, --alive"); - printf (" %s\n", _("Return OK after first successful reply")); - printf (" %s\n", "-b, --bytes=INTEGER"); - printf (" %s (default: %d)\n", _("size of ICMP packet"),PACKET_SIZE); - printf (" %s\n", "-n, --number=INTEGER"); - printf (" %s (default: %d)\n", _("number of ICMP packets to send"),PACKET_COUNT); - printf (" %s\n", "-T, --target-timeout=INTEGER"); - printf (" %s (default: fping's default for -t)\n", _("Target timeout (ms)")); - printf (" %s\n", "-i, --interval=INTEGER"); - printf (" %s (default: fping's default for -p)\n", _("Interval (ms) between sending packets")); - printf (" %s\n", "-S, --sourceip=HOST"); - printf (" %s\n", _("name or IP Address of sourceip")); - printf (" %s\n", "-I, --sourceif=IF"); - printf (" %s\n", _("source interface name")); - printf (UT_VERBOSE); - printf ("\n"); - printf (" %s\n", _("THRESHOLD is ,%% where is the round trip average travel time (ms)")); - printf (" %s\n", _("which triggers a WARNING or CRITICAL state, and is the percentage of")); - printf (" %s\n", _("packet loss to trigger an alarm state.")); + printf(" %s\n", "-H, --hostname=HOST"); + printf(" %s\n", _("name or IP Address of host to ping (IP Address bypasses name lookup, reducing system load)")); + printf(" %s\n", "-w, --warning=THRESHOLD"); + printf(" %s\n", _("warning threshold pair")); + printf(" %s\n", "-c, --critical=THRESHOLD"); + printf(" %s\n", _("critical threshold pair")); + printf(" %s\n", "-a, --alive"); + printf(" %s\n", _("Return OK after first successful reply")); + printf(" %s\n", "-b, --bytes=INTEGER"); + printf(" %s (default: %d)\n", _("size of ICMP packet"), PACKET_SIZE); + printf(" %s\n", "-n, --number=INTEGER"); + printf(" %s (default: %d)\n", _("number of ICMP packets to send"), PACKET_COUNT); + printf(" %s\n", "-T, --target-timeout=INTEGER"); + printf(" %s (default: fping's default for -t)\n", _("Target timeout (ms)")); + printf(" %s\n", "-i, --interval=INTEGER"); + printf(" %s (default: fping's default for -p)\n", _("Interval (ms) between sending packets")); + printf(" %s\n", "-S, --sourceip=HOST"); + printf(" %s\n", _("name or IP Address of sourceip")); + printf(" %s\n", "-I, --sourceif=IF"); + printf(" %s\n", _("source interface name")); + printf(UT_VERBOSE); + printf("\n"); + printf(" %s\n", _("THRESHOLD is ,%% where is the round trip average travel time (ms)")); + printf(" %s\n", _("which triggers a WARNING or CRITICAL state, and is the percentage of")); + printf(" %s\n", _("packet loss to trigger an alarm state.")); - printf ("\n"); - printf (" %s\n", _("IPv4 is used by default. Specify -6 to use IPv6.")); + printf("\n"); + printf(" %s\n", _("IPv4 is used by default. Specify -6 to use IPv6.")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s -w limit -c limit [-b size] [-n number] [-T number] [-i number]\n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s -w limit -c limit [-b size] [-n number] [-T number] [-i number]\n", progname); } -- cgit v1.2.3-74-g34f1 From 5490729f1ff8fd65ba408906cf1552331938424b Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:37:38 +0100 Subject: check_fping: update copyright --- plugins/check_fping.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_fping.c b/plugins/check_fping.c index ec151143..b11508a5 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -3,7 +3,7 @@ * Monitoring check_fping plugin * * License: GPL - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_fping"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From f3ed9c6038eb960efcdaff7f58cae7934dd20a3e Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:38:44 +0100 Subject: check_fping: do not export local symbols --- plugins/check_fping.c | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/plugins/check_fping.c b/plugins/check_fping.c index b11508a5..79d672ce 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -46,29 +46,29 @@ enum { RTA = 1 }; -int textscan(char *buf); -int process_arguments(int, char **); -int get_threshold(char *arg, char *rv[2]); -void print_help(void); +static int textscan(char *buf); +static int process_arguments(int, char **); +static int get_threshold(char *arg, char *rv[2]); +static void print_help(void); void print_usage(void); -char *server_name = NULL; -char *sourceip = NULL; -char *sourceif = NULL; -int packet_size = PACKET_SIZE; -int packet_count = PACKET_COUNT; -int target_timeout = 0; -int packet_interval = 0; -bool verbose = false; -int cpl; -int wpl; -double crta; -double wrta; -bool cpl_p = false; -bool wpl_p = false; -bool alive_p = false; -bool crta_p = false; -bool wrta_p = false; +static char *server_name = NULL; +static char *sourceip = NULL; +static char *sourceif = NULL; +static int packet_size = PACKET_SIZE; +static int packet_count = PACKET_COUNT; +static int target_timeout = 0; +static int packet_interval = 0; +static bool verbose = false; +static int cpl; +static int wpl; +static double crta; +static double wrta; +static bool cpl_p = false; +static bool wpl_p = false; +static bool alive_p = false; +static bool crta_p = false; +static bool wrta_p = false; int main(int argc, char **argv) { /* normally should be int result = STATE_UNKNOWN; */ -- cgit v1.2.3-74-g34f1 From 1d0f532750f24b2208846c139927fb8ed50ff1d3 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:39:38 +0100 Subject: check_fping: Linter fixes --- plugins/check_fping.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/check_fping.c b/plugins/check_fping.c index 79d672ce..49235e28 100644 --- a/plugins/check_fping.c +++ b/plugins/check_fping.c @@ -47,7 +47,7 @@ enum { }; static int textscan(char *buf); -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static int get_threshold(char *arg, char *rv[2]); static void print_help(void); void print_usage(void); -- cgit v1.2.3-74-g34f1 From 11a5ab2b8d1ae2c21e2831dd8f6fc4097775dbf7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:40:12 +0100 Subject: check_game: clang-format --- plugins/check_game.c | 540 ++++++++++++++++++++++++--------------------------- 1 file changed, 256 insertions(+), 284 deletions(-) diff --git a/plugins/check_game.c b/plugins/check_game.c index ca126973..843c558b 100644 --- a/plugins/check_game.c +++ b/plugins/check_game.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_game plugin -* -* License: GPL -* Copyright (c) 2002-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_game plugin -* -* This plugin tests game server connections with the specified host. -* using the qstat program -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_game plugin + * + * License: GPL + * Copyright (c) 2002-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_game plugin + * + * This plugin tests game server connections with the specified host. + * using the qstat program + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_game"; const char *copyright = "2002-2007"; @@ -37,16 +37,16 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "runcmd.h" -int process_arguments (int, char **); -int validate_arguments (void); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_help(void); +void print_usage(void); -#define QSTAT_DATA_DELIMITER "," +#define QSTAT_DATA_DELIMITER "," -#define QSTAT_HOST_ERROR "ERROR" -#define QSTAT_HOST_DOWN "DOWN" -#define QSTAT_HOST_TIMEOUT "TIMEOUT" +#define QSTAT_HOST_ERROR "ERROR" +#define QSTAT_HOST_DOWN "DOWN" +#define QSTAT_HOST_TIMEOUT "TIMEOUT" #define QSTAT_MAX_RETURN_ARGS 12 char *server_ip; @@ -61,275 +61,247 @@ int qstat_game_field = -1; int qstat_map_field = -1; int qstat_ping_field = -1; - -int -main (int argc, char **argv) -{ - char *command_line; - int result = STATE_UNKNOWN; - char *p, *ret[QSTAT_MAX_RETURN_ARGS]; - size_t i = 0; - output chld_out; - - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); - - /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); - - if (process_arguments (argc, argv) == ERROR) - usage_va(_("Could not parse arguments")); - - result = STATE_OK; - - /* create the command line to execute */ - xasprintf (&command_line, "%s -raw %s -%s %s", - PATH_TO_QSTAT, QSTAT_DATA_DELIMITER, game_type, server_ip); - - if (port) - xasprintf (&command_line, "%s:%-d", command_line, port); - - if (verbose) - printf ("%s\n", command_line); - - /* run the command. historically, this plugin ignores output on stderr, - * as well as return status of the qstat program */ - (void)np_runcmd(command_line, &chld_out, NULL, 0); - - /* sanity check */ - /* was thinking about running qstat without any options, capturing the - -default line, parsing it & making an array of all know server types - but thought this would be too much hassle considering this is a tool - for intelligent sysadmins (ha). Could put a static array of known - server types in a header file but then we'd be limiting ourselves - - In the end, I figured I'd simply let an error occur & then trap it - */ - - if (!strncmp (chld_out.line[0], "unknown option", 14)) { - printf (_("CRITICAL - Host type parameter incorrect!\n")); - result = STATE_CRITICAL; - return result; - } - - p = (char *) strtok (chld_out.line[0], QSTAT_DATA_DELIMITER); - while (p != NULL) { - ret[i] = p; - p = (char *) strtok (NULL, QSTAT_DATA_DELIMITER); - i++; - if (i >= QSTAT_MAX_RETURN_ARGS) - break; - } - - if (strstr (ret[2], QSTAT_HOST_ERROR)) { - printf (_("CRITICAL - Host not found\n")); - result = STATE_CRITICAL; - } - else if (strstr (ret[2], QSTAT_HOST_DOWN)) { - printf (_("CRITICAL - Game server down or unavailable\n")); - result = STATE_CRITICAL; - } - else if (strstr (ret[2], QSTAT_HOST_TIMEOUT)) { - printf (_("CRITICAL - Game server timeout\n")); - result = STATE_CRITICAL; - } - else { - printf ("OK: %s/%s %s (%s), Ping: %s ms|%s %s\n", - ret[qstat_game_players], - ret[qstat_game_players_max], - ret[qstat_game_field], - ret[qstat_map_field], - ret[qstat_ping_field], - perfdata ("players", atol(ret[qstat_game_players]), "", - false, 0, false, 0, - true, 0, true, atol(ret[qstat_game_players_max])), - fperfdata ("ping", strtod(ret[qstat_ping_field], NULL), "", - false, 0, false, 0, - true, 0, false, 0)); - } - - return result; +int main(int argc, char **argv) { + char *command_line; + int result = STATE_UNKNOWN; + char *p, *ret[QSTAT_MAX_RETURN_ARGS]; + size_t i = 0; + output chld_out; + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + /* Parse extra opts if any */ + argv = np_extra_opts(&argc, argv, progname); + + if (process_arguments(argc, argv) == ERROR) + usage_va(_("Could not parse arguments")); + + result = STATE_OK; + + /* create the command line to execute */ + xasprintf(&command_line, "%s -raw %s -%s %s", PATH_TO_QSTAT, QSTAT_DATA_DELIMITER, game_type, server_ip); + + if (port) + xasprintf(&command_line, "%s:%-d", command_line, port); + + if (verbose) + printf("%s\n", command_line); + + /* run the command. historically, this plugin ignores output on stderr, + * as well as return status of the qstat program */ + (void)np_runcmd(command_line, &chld_out, NULL, 0); + + /* sanity check */ + /* was thinking about running qstat without any options, capturing the + -default line, parsing it & making an array of all know server types + but thought this would be too much hassle considering this is a tool + for intelligent sysadmins (ha). Could put a static array of known + server types in a header file but then we'd be limiting ourselves + + In the end, I figured I'd simply let an error occur & then trap it + */ + + if (!strncmp(chld_out.line[0], "unknown option", 14)) { + printf(_("CRITICAL - Host type parameter incorrect!\n")); + result = STATE_CRITICAL; + return result; + } + + p = (char *)strtok(chld_out.line[0], QSTAT_DATA_DELIMITER); + while (p != NULL) { + ret[i] = p; + p = (char *)strtok(NULL, QSTAT_DATA_DELIMITER); + i++; + if (i >= QSTAT_MAX_RETURN_ARGS) + break; + } + + if (strstr(ret[2], QSTAT_HOST_ERROR)) { + printf(_("CRITICAL - Host not found\n")); + result = STATE_CRITICAL; + } else if (strstr(ret[2], QSTAT_HOST_DOWN)) { + printf(_("CRITICAL - Game server down or unavailable\n")); + result = STATE_CRITICAL; + } else if (strstr(ret[2], QSTAT_HOST_TIMEOUT)) { + printf(_("CRITICAL - Game server timeout\n")); + result = STATE_CRITICAL; + } else { + printf("OK: %s/%s %s (%s), Ping: %s ms|%s %s\n", ret[qstat_game_players], ret[qstat_game_players_max], ret[qstat_game_field], + ret[qstat_map_field], ret[qstat_ping_field], + perfdata("players", atol(ret[qstat_game_players]), "", false, 0, false, 0, true, 0, true, atol(ret[qstat_game_players_max])), + fperfdata("ping", strtod(ret[qstat_ping_field], NULL), "", false, 0, false, 0, true, 0, false, 0)); + } + + return result; } - -int -process_arguments (int argc, char **argv) -{ - int c; - - int opt_index = 0; - static struct option long_opts[] = { - {"help", no_argument, 0, 'h'}, - {"version", no_argument, 0, 'V'}, - {"verbose", no_argument, 0, 'v'}, - {"timeout", required_argument, 0, 't'}, - {"hostname", required_argument, 0, 'H'}, - {"port", required_argument, 0, 'P'}, - {"game-type", required_argument, 0, 'G'}, - {"map-field", required_argument, 0, 'm'}, - {"ping-field", required_argument, 0, 'p'}, - {"game-field", required_argument, 0, 'g'}, - {"players-field", required_argument, 0, 129}, - {"max-players-field", required_argument, 0, 130}, - {0, 0, 0, 0} - }; - - if (argc < 2) - return ERROR; - - for (c = 1; c < argc; c++) { - if (strcmp ("-mf", argv[c]) == 0) - strcpy (argv[c], "-m"); - else if (strcmp ("-pf", argv[c]) == 0) - strcpy (argv[c], "-p"); - else if (strcmp ("-gf", argv[c]) == 0) - strcpy (argv[c], "-g"); - } - - while (1) { - c = getopt_long (argc, argv, "hVvt:H:P:G:g:p:m:", long_opts, &opt_index); - - if (c == -1 || c == EOF) - break; - - switch (c) { - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'v': /* version */ - verbose = true; - break; - case 't': /* timeout period */ - timeout_interval = atoi (optarg); - break; - case 'H': /* hostname */ - if (strlen (optarg) >= MAX_HOST_ADDRESS_LENGTH) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - server_ip = optarg; - break; - case 'P': /* port */ - port = atoi (optarg); - break; - case 'G': /* hostname */ - if (strlen (optarg) >= MAX_INPUT_BUFFER) - die (STATE_UNKNOWN, _("Input buffer overflow\n")); - game_type = optarg; - break; - case 'p': /* index of ping field */ - qstat_ping_field = atoi (optarg); - if (qstat_ping_field < 0 || qstat_ping_field > QSTAT_MAX_RETURN_ARGS) - return ERROR; - break; - case 'm': /* index on map field */ - qstat_map_field = atoi (optarg); - if (qstat_map_field < 0 || qstat_map_field > QSTAT_MAX_RETURN_ARGS) - return ERROR; - break; - case 'g': /* index of game field */ - qstat_game_field = atoi (optarg); - if (qstat_game_field < 0 || qstat_game_field > QSTAT_MAX_RETURN_ARGS) - return ERROR; - break; - case 129: /* index of player count field */ - qstat_game_players = atoi (optarg); - if (qstat_game_players_max == 0) - qstat_game_players_max = qstat_game_players - 1; - if (qstat_game_players < 0 || qstat_game_players > QSTAT_MAX_RETURN_ARGS) - return ERROR; - break; - case 130: /* index of max players field */ - qstat_game_players_max = atoi (optarg); - if (qstat_game_players_max < 0 || qstat_game_players_max > QSTAT_MAX_RETURN_ARGS) - return ERROR; - break; - default: /* args not parsable */ - usage5(); - } - } - - c = optind; - /* first option is the game type */ - if (!game_type && c= MAX_HOST_ADDRESS_LENGTH) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + server_ip = optarg; + break; + case 'P': /* port */ + port = atoi(optarg); + break; + case 'G': /* hostname */ + if (strlen(optarg) >= MAX_INPUT_BUFFER) + die(STATE_UNKNOWN, _("Input buffer overflow\n")); + game_type = optarg; + break; + case 'p': /* index of ping field */ + qstat_ping_field = atoi(optarg); + if (qstat_ping_field < 0 || qstat_ping_field > QSTAT_MAX_RETURN_ARGS) + return ERROR; + break; + case 'm': /* index on map field */ + qstat_map_field = atoi(optarg); + if (qstat_map_field < 0 || qstat_map_field > QSTAT_MAX_RETURN_ARGS) + return ERROR; + break; + case 'g': /* index of game field */ + qstat_game_field = atoi(optarg); + if (qstat_game_field < 0 || qstat_game_field > QSTAT_MAX_RETURN_ARGS) + return ERROR; + break; + case 129: /* index of player count field */ + qstat_game_players = atoi(optarg); + if (qstat_game_players_max == 0) + qstat_game_players_max = qstat_game_players - 1; + if (qstat_game_players < 0 || qstat_game_players > QSTAT_MAX_RETURN_ARGS) + return ERROR; + break; + case 130: /* index of max players field */ + qstat_game_players_max = atoi(optarg); + if (qstat_game_players_max < 0 || qstat_game_players_max > QSTAT_MAX_RETURN_ARGS) + return ERROR; + break; + default: /* args not parsable */ + usage5(); + } + } + + c = optind; + /* first option is the game type */ + if (!game_type && c < argc) + game_type = strdup(argv[c++]); + + /* Second option is the server name */ + if (!server_ip && c < argc) + server_ip = strdup(argv[c++]); + + return validate_arguments(); } +int validate_arguments(void) { + if (qstat_game_players_max < 0) + qstat_game_players_max = 4; -int -validate_arguments (void) -{ - if (qstat_game_players_max < 0) - qstat_game_players_max = 4; + if (qstat_game_players < 0) + qstat_game_players = 5; - if (qstat_game_players < 0) - qstat_game_players = 5; + if (qstat_game_field < 0) + qstat_game_field = 2; - if (qstat_game_field < 0) - qstat_game_field = 2; + if (qstat_map_field < 0) + qstat_map_field = 3; - if (qstat_map_field < 0) - qstat_map_field = 3; + if (qstat_ping_field < 0) + qstat_ping_field = 5; - if (qstat_ping_field < 0) - qstat_ping_field = 5; - - return OK; + return OK; } +void print_help(void) { + print_revision(progname, NP_VERSION); -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Ian Cass, Knowledge Matters Limited\n"); - printf (COPYRIGHT, copyright, email); + printf("Copyright (c) 1999 Ian Cass, Knowledge Matters Limited\n"); + printf(COPYRIGHT, copyright, email); - printf (_("This plugin tests game server connections with the specified host.")); + printf(_("This plugin tests game server connections with the specified host.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (" %s\n", "-p"); - printf (" %s\n", _("Optional port of which to connect")); - printf (" %s\n", "gf"); - printf (" %s\n", _("Field number in raw qstat output that contains game name")); - printf (" %s\n", "-mf"); - printf (" %s\n", _("Field number in raw qstat output that contains map name")); - printf (" %s\n", "-pf"); - printf (" %s\n", _("Field number in raw qstat output that contains ping time")); + printf(" %s\n", "-p"); + printf(" %s\n", _("Optional port of which to connect")); + printf(" %s\n", "gf"); + printf(" %s\n", _("Field number in raw qstat output that contains game name")); + printf(" %s\n", "-mf"); + printf(" %s\n", _("Field number in raw qstat output that contains map name")); + printf(" %s\n", "-pf"); + printf(" %s\n", _("Field number in raw qstat output that contains ping time")); - printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("This plugin uses the 'qstat' command, the popular game server status query tool.")); - printf (" %s\n", _("If you don't have the package installed, you will need to download it from")); - printf (" %s\n", _("https://github.com/multiplay/qstat before you can use this plugin.")); + printf("\n"); + printf("%s\n", _("Notes:")); + printf(" %s\n", _("This plugin uses the 'qstat' command, the popular game server status query tool.")); + printf(" %s\n", _("If you don't have the package installed, you will need to download it from")); + printf(" %s\n", _("https://github.com/multiplay/qstat before you can use this plugin.")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf (" %s [-hvV] [-P port] [-t timeout] [-g game_field] [-m map_field] [-p ping_field] [-G game-time] [-H hostname] \n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf(" %s [-hvV] [-P port] [-t timeout] [-g game_field] [-m map_field] [-p ping_field] [-G game-time] [-H hostname] " + "\n", + progname); } /****************************************************************************** -- cgit v1.2.3-74-g34f1 From aa143390f5ee7ca43958312e3142b25df6653e9a Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:41:06 +0100 Subject: check_game: update copyright --- plugins/check_game.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_game.c b/plugins/check_game.c index 843c558b..b372cf1b 100644 --- a/plugins/check_game.c +++ b/plugins/check_game.c @@ -3,7 +3,7 @@ * Monitoring check_game plugin * * License: GPL - * Copyright (c) 2002-2007 Monitoring Plugins Development Team + * Copyright (c) 2002-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_game"; -const char *copyright = "2002-2007"; +const char *copyright = "2002-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From 8355b9db407f2ca763467efb509de7564f8016a4 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:42:06 +0100 Subject: check_game: do not export local symbols --- plugins/check_game.c | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/plugins/check_game.c b/plugins/check_game.c index b372cf1b..80a90e44 100644 --- a/plugins/check_game.c +++ b/plugins/check_game.c @@ -37,9 +37,9 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "runcmd.h" -int process_arguments(int, char **); -int validate_arguments(void); -void print_help(void); +static int process_arguments(int, char **); +static int validate_arguments(void); +static void print_help(void); void print_usage(void); #define QSTAT_DATA_DELIMITER "," @@ -49,17 +49,17 @@ void print_usage(void); #define QSTAT_HOST_TIMEOUT "TIMEOUT" #define QSTAT_MAX_RETURN_ARGS 12 -char *server_ip; -char *game_type; -int port = 0; +static char *server_ip; +static char *game_type; +static int port = 0; -bool verbose = false; +static bool verbose = false; -int qstat_game_players_max = -1; -int qstat_game_players = -1; -int qstat_game_field = -1; -int qstat_map_field = -1; -int qstat_ping_field = -1; +static int qstat_game_players_max = -1; +static int qstat_game_players = -1; +static int qstat_game_field = -1; +static int qstat_map_field = -1; +static int qstat_ping_field = -1; int main(int argc, char **argv) { char *command_line; -- cgit v1.2.3-74-g34f1 From 0e0c517b19c7a97cb4efec0731c40caf57d1a340 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:44:06 +0100 Subject: check_game: linter fixes --- plugins/check_game.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/plugins/check_game.c b/plugins/check_game.c index 80a90e44..619277e7 100644 --- a/plugins/check_game.c +++ b/plugins/check_game.c @@ -37,7 +37,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "utils.h" #include "runcmd.h" -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static int validate_arguments(void); static void print_help(void); void print_usage(void); @@ -64,7 +64,8 @@ static int qstat_ping_field = -1; int main(int argc, char **argv) { char *command_line; int result = STATE_UNKNOWN; - char *p, *ret[QSTAT_MAX_RETURN_ARGS]; + char *p; + char *ret[QSTAT_MAX_RETURN_ARGS]; size_t i = 0; output chld_out; -- cgit v1.2.3-74-g34f1 From 80fcc8dfacba565881bc552f1f5515d7ea5ffbed Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:45:03 +0100 Subject: check_hpjd: clang-format --- plugins/check_hpjd.c | 409 ++++++++++++++++++++++----------------------------- 1 file changed, 179 insertions(+), 230 deletions(-) diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c index c34bb082..836bf955 100644 --- a/plugins/check_hpjd.c +++ b/plugins/check_hpjd.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_hpjd plugin -* -* License: GPL -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_hpjd plugin -* -* This plugin tests the STATUS of an HP printer with a JetDirect card. -* Net-SNMP must be installed on the computer running the plugin. -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_hpjd plugin + * + * License: GPL + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_hpjd plugin + * + * This plugin tests the STATUS of an HP printer with a JetDirect card. + * Net-SNMP must be installed on the computer running the plugin. + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_hpjd"; const char *copyright = "2000-2007"; @@ -39,7 +39,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "netutils.h" #define DEFAULT_COMMUNITY "public" -#define DEFAULT_PORT "161" +#define DEFAULT_PORT "161" const char *option_summary = "-H host [-C community]\n"; @@ -56,22 +56,20 @@ const char *option_summary = "-H host [-C community]\n"; #define HPJD_GD_PAPER_OUTPUT ".1.3.6.1.4.1.11.2.3.9.1.1.2.19" #define HPJD_GD_STATUS_DISPLAY ".1.3.6.1.4.1.11.2.3.9.1.1.3" -#define ONLINE 0 -#define OFFLINE 1 +#define ONLINE 0 +#define OFFLINE 1 -int process_arguments (int, char **); -int validate_arguments (void); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_help(void); +void print_usage(void); char *community = NULL; char *address = NULL; unsigned int port = 0; -int check_paper_out = 1; +int check_paper_out = 1; -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { char command_line[1024]; int result = STATE_UNKNOWN; int line; @@ -94,116 +92,99 @@ main (int argc, char **argv) errmsg = malloc(MAX_INPUT_BUFFER); - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments")); /* removed ' 2>1' at end of command 10/27/1999 - EG */ /* create the query string */ - sprintf - (query_string, - "%s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0", - HPJD_LINE_STATUS, - HPJD_PAPER_STATUS, - HPJD_INTERVENTION_REQUIRED, - HPJD_GD_PERIPHERAL_ERROR, - HPJD_GD_PAPER_JAM, - HPJD_GD_PAPER_OUT, - HPJD_GD_TONER_LOW, - HPJD_GD_PAGE_PUNT, - HPJD_GD_MEMORY_OUT, - HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY); + sprintf(query_string, "%s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0 %s.0", HPJD_LINE_STATUS, HPJD_PAPER_STATUS, + HPJD_INTERVENTION_REQUIRED, HPJD_GD_PERIPHERAL_ERROR, HPJD_GD_PAPER_JAM, HPJD_GD_PAPER_OUT, HPJD_GD_TONER_LOW, + HPJD_GD_PAGE_PUNT, HPJD_GD_MEMORY_OUT, HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY); /* get the command to run */ - sprintf (command_line, "%s -OQa -m : -v 1 -c %s %s:%u %s", - PATH_TO_SNMPGET, - community, - address, - port, - query_string); + sprintf(command_line, "%s -OQa -m : -v 1 -c %s %s:%u %s", PATH_TO_SNMPGET, community, address, port, query_string); /* run the command */ - child_process = spopen (command_line); + child_process = spopen(command_line); if (child_process == NULL) { - printf (_("Could not open pipe: %s\n"), command_line); + printf(_("Could not open pipe: %s\n"), command_line); return STATE_UNKNOWN; } - child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); + child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r"); if (child_stderr == NULL) { - printf (_("Could not open stderr for %s\n"), command_line); + printf(_("Could not open stderr for %s\n"), command_line); } result = STATE_OK; line = 0; - while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { + while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { /* strip the newline character from the end of the input */ - if (input_buffer[strlen (input_buffer) - 1] == '\n') - input_buffer[strlen (input_buffer) - 1] = 0; + if (input_buffer[strlen(input_buffer) - 1] == '\n') + input_buffer[strlen(input_buffer) - 1] = 0; line++; - temp_buffer = strtok (input_buffer, "="); - temp_buffer = strtok (NULL, "="); + temp_buffer = strtok(input_buffer, "="); + temp_buffer = strtok(NULL, "="); if (temp_buffer == NULL && line < 13) { - result = STATE_UNKNOWN; - strcpy (errmsg, input_buffer); + result = STATE_UNKNOWN; + strcpy(errmsg, input_buffer); } else { switch (line) { - case 1: /* 1st line should contain the line status */ - line_status = atoi (temp_buffer); + case 1: /* 1st line should contain the line status */ + line_status = atoi(temp_buffer); break; - case 2: /* 2nd line should contain the paper status */ - paper_status = atoi (temp_buffer); + case 2: /* 2nd line should contain the paper status */ + paper_status = atoi(temp_buffer); break; - case 3: /* 3rd line should be intervention required */ - intervention_required = atoi (temp_buffer); + case 3: /* 3rd line should be intervention required */ + intervention_required = atoi(temp_buffer); break; - case 4: /* 4th line should be peripheral error */ - peripheral_error = atoi (temp_buffer); + case 4: /* 4th line should be peripheral error */ + peripheral_error = atoi(temp_buffer); break; - case 5: /* 5th line should contain the paper jam status */ - paper_jam = atoi (temp_buffer); + case 5: /* 5th line should contain the paper jam status */ + paper_jam = atoi(temp_buffer); break; - case 6: /* 6th line should contain the paper out status */ - paper_out = atoi (temp_buffer); + case 6: /* 6th line should contain the paper out status */ + paper_out = atoi(temp_buffer); break; - case 7: /* 7th line should contain the toner low status */ - toner_low = atoi (temp_buffer); + case 7: /* 7th line should contain the toner low status */ + toner_low = atoi(temp_buffer); break; - case 8: /* did data come too slow for engine */ - page_punt = atoi (temp_buffer); + case 8: /* did data come too slow for engine */ + page_punt = atoi(temp_buffer); break; - case 9: /* did we run out of memory */ - memory_out = atoi (temp_buffer); + case 9: /* did we run out of memory */ + memory_out = atoi(temp_buffer); break; - case 10: /* is there a door open */ - door_open = atoi (temp_buffer); + case 10: /* is there a door open */ + door_open = atoi(temp_buffer); break; - case 11: /* is output tray full */ - paper_output = atoi (temp_buffer); + case 11: /* is output tray full */ + paper_output = atoi(temp_buffer); break; - case 12: /* display panel message */ - strcpy (display_message, temp_buffer + 1); + case 12: /* display panel message */ + strcpy(display_message, temp_buffer + 1); break; - default: /* fold multiline message */ - strncat (display_message, input_buffer, - sizeof (display_message) - strlen (display_message) - 1); + default: /* fold multiline message */ + strncat(display_message, input_buffer, sizeof(display_message) - strlen(display_message) - 1); } - } /* break out of the read loop if we encounter an error */ @@ -212,29 +193,27 @@ main (int argc, char **argv) } /* WARNING if output found on stderr */ - if (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { - result = max_state (result, STATE_WARNING); + if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { + result = max_state(result, STATE_WARNING); /* remove CRLF */ - if (input_buffer[strlen (input_buffer) - 1] == '\n') - input_buffer[strlen (input_buffer) - 1] = 0; - sprintf (errmsg, "%s", input_buffer ); - + if (input_buffer[strlen(input_buffer) - 1] == '\n') + input_buffer[strlen(input_buffer) - 1] = 0; + sprintf(errmsg, "%s", input_buffer); } /* close stderr */ - (void) fclose (child_stderr); + (void)fclose(child_stderr); /* close the pipe */ - if (spclose (child_process)) - result = max_state (result, STATE_WARNING); + if (spclose(child_process)) + result = max_state(result, STATE_WARNING); /* if there wasn't any output, display an error */ if (line == 0) { /* might not be the problem, but most likely is. */ - result = STATE_UNKNOWN ; - xasprintf (&errmsg, "%s : Timeout from host %s\n", errmsg, address ); - + result = STATE_UNKNOWN; + xasprintf(&errmsg, "%s : Timeout from host %s\n", errmsg, address); } /* if we had no read errors, check the printer status results... */ @@ -242,201 +221,171 @@ main (int argc, char **argv) if (paper_jam) { result = STATE_WARNING; - strcpy (errmsg, _("Paper Jam")); - } - else if (paper_out) { + strcpy(errmsg, _("Paper Jam")); + } else if (paper_out) { if (check_paper_out) result = STATE_WARNING; - strcpy (errmsg, _("Out of Paper")); - } - else if (line_status == OFFLINE) { - if (strcmp (errmsg, "POWERSAVE ON") != 0) { + strcpy(errmsg, _("Out of Paper")); + } else if (line_status == OFFLINE) { + if (strcmp(errmsg, "POWERSAVE ON") != 0) { result = STATE_WARNING; - strcpy (errmsg, _("Printer Offline")); + strcpy(errmsg, _("Printer Offline")); } - } - else if (peripheral_error) { + } else if (peripheral_error) { result = STATE_WARNING; - strcpy (errmsg, _("Peripheral Error")); - } - else if (intervention_required) { + strcpy(errmsg, _("Peripheral Error")); + } else if (intervention_required) { result = STATE_WARNING; - strcpy (errmsg, _("Intervention Required")); - } - else if (toner_low) { + strcpy(errmsg, _("Intervention Required")); + } else if (toner_low) { result = STATE_WARNING; - strcpy (errmsg, _("Toner Low")); - } - else if (memory_out) { + strcpy(errmsg, _("Toner Low")); + } else if (memory_out) { result = STATE_WARNING; - strcpy (errmsg, _("Insufficient Memory")); - } - else if (door_open) { + strcpy(errmsg, _("Insufficient Memory")); + } else if (door_open) { result = STATE_WARNING; - strcpy (errmsg, _("A Door is Open")); - } - else if (paper_output) { + strcpy(errmsg, _("A Door is Open")); + } else if (paper_output) { result = STATE_WARNING; - strcpy (errmsg, _("Output Tray is Full")); - } - else if (page_punt) { + strcpy(errmsg, _("Output Tray is Full")); + } else if (page_punt) { result = STATE_WARNING; - strcpy (errmsg, _("Data too Slow for Engine")); - } - else if (paper_status) { + strcpy(errmsg, _("Data too Slow for Engine")); + } else if (paper_status) { result = STATE_WARNING; - strcpy (errmsg, _("Unknown Paper Error")); + strcpy(errmsg, _("Unknown Paper Error")); } } if (result == STATE_OK) - printf (_("Printer ok - (%s)\n"), display_message); + printf(_("Printer ok - (%s)\n"), display_message); else if (result == STATE_UNKNOWN) { - printf ("%s\n", errmsg); + printf("%s\n", errmsg); /* if printer could not be reached, escalate to critical */ - if (strstr (errmsg, "Timeout")) + if (strstr(errmsg, "Timeout")) result = STATE_CRITICAL; } else if (result == STATE_WARNING) - printf ("%s (%s)\n", errmsg, display_message); + printf("%s (%s)\n", errmsg, display_message); return result; } - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; int option = 0; - static struct option longopts[] = { - {"hostname", required_argument, 0, 'H'}, - {"community", required_argument, 0, 'C'}, -/* {"critical", required_argument,0,'c'}, */ -/* {"warning", required_argument,0,'w'}, */ - {"port", required_argument,0,'p'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, + {"community", required_argument, 0, 'C'}, + /* {"critical", required_argument,0,'c'}, */ + /* {"warning", required_argument,0,'w'}, */ + {"port", required_argument, 0, 'p'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0}}; if (argc < 2) return ERROR; - while (1) { - c = getopt_long (argc, argv, "+hVH:C:p:D", longopts, &option); + c = getopt_long(argc, argv, "+hVH:C:p:D", longopts, &option); if (c == -1 || c == EOF || c == 1) break; switch (c) { - case 'H': /* hostname */ - if (is_host (optarg)) { - address = strscpy(address, optarg) ; - } - else { - usage2 (_("Invalid hostname/address"), optarg); + case 'H': /* hostname */ + if (is_host(optarg)) { + address = strscpy(address, optarg); + } else { + usage2(_("Invalid hostname/address"), optarg); } break; - case 'C': /* community */ - community = strscpy (community, optarg); + case 'C': /* community */ + community = strscpy(community, optarg); break; case 'p': if (!is_intpos(optarg)) - usage2 (_("Port must be a positive short integer"), optarg); + usage2(_("Port must be a positive short integer"), optarg); else port = atoi(optarg); break; - case 'D': /* disable paper out check*/ + case 'D': /* disable paper out check*/ check_paper_out = 0; break; - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case '?': /* help */ - usage5 (); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case '?': /* help */ + usage5(); } } c = optind; if (address == NULL) { - if (is_host (argv[c])) { + if (is_host(argv[c])) { address = argv[c++]; - } - else { - usage2 (_("Invalid hostname/address"), argv[c]); + } else { + usage2(_("Invalid hostname/address"), argv[c]); } } if (community == NULL) { - if (argv[c] != NULL ) + if (argv[c] != NULL) community = argv[c]; else - community = strdup (DEFAULT_COMMUNITY); + community = strdup(DEFAULT_COMMUNITY); } if (port == 0) { port = atoi(DEFAULT_PORT); } - return validate_arguments (); + return validate_arguments(); } +int validate_arguments(void) { return OK; } -int -validate_arguments (void) -{ - return OK; -} - - -void -print_help (void) -{ - print_revision (progname, NP_VERSION); +void print_help(void) { + print_revision(progname, NP_VERSION); - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); - printf ("%s\n", _("This plugin tests the STATUS of an HP printer with a JetDirect card.")); - printf ("%s\n", _("Net-snmp must be installed on the computer running the plugin.")); + printf("%s\n", _("This plugin tests the STATUS of an HP printer with a JetDirect card.")); + printf("%s\n", _("Net-snmp must be installed on the computer running the plugin.")); - printf ("\n\n"); + printf("\n\n"); - print_usage (); + print_usage(); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (" %s\n", "-C, --community=STRING"); - printf (" %s", _("The SNMP community name ")); - printf (_("(default=%s)"), DEFAULT_COMMUNITY); - printf ("\n"); - printf (" %s\n", "-p, --port=STRING"); - printf (" %s", _("Specify the port to check ")); - printf (_("(default=%s)"), DEFAULT_PORT); - printf ("\n"); - printf (" %s\n", "-D"); - printf (" %s", _("Disable paper check ")); + printf(" %s\n", "-C, --community=STRING"); + printf(" %s", _("The SNMP community name ")); + printf(_("(default=%s)"), DEFAULT_COMMUNITY); + printf("\n"); + printf(" %s\n", "-p, --port=STRING"); + printf(" %s", _("Specify the port to check ")); + printf(_("(default=%s)"), DEFAULT_PORT); + printf("\n"); + printf(" %s\n", "-D"); + printf(" %s", _("Disable paper check ")); - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s -H host [-C community] [-p port] [-D]\n", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s -H host [-C community] [-p port] [-D]\n", progname); } -- cgit v1.2.3-74-g34f1 From a4b3386657625fa8d24ca25993560895694ad9c8 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:45:50 +0100 Subject: check_hpjd: update copyright --- plugins/check_hpjd.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c index 836bf955..713b108b 100644 --- a/plugins/check_hpjd.c +++ b/plugins/check_hpjd.c @@ -3,7 +3,7 @@ * Monitoring check_hpjd plugin * * License: GPL - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -30,7 +30,7 @@ *****************************************************************************/ const char *progname = "check_hpjd"; -const char *copyright = "2000-2007"; +const char *copyright = "2000-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From f33412e50acbb57c3c02a412a3e9574639576f83 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:47:03 +0100 Subject: check_hpjd: do not export local symbols --- plugins/check_hpjd.c | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c index 713b108b..6e4ddcbf 100644 --- a/plugins/check_hpjd.c +++ b/plugins/check_hpjd.c @@ -41,8 +41,6 @@ const char *email = "devel@monitoring-plugins.org"; #define DEFAULT_COMMUNITY "public" #define DEFAULT_PORT "161" -const char *option_summary = "-H host [-C community]\n"; - #define HPJD_LINE_STATUS ".1.3.6.1.4.1.11.2.3.9.1.1.2.1" #define HPJD_PAPER_STATUS ".1.3.6.1.4.1.11.2.3.9.1.1.2.2" #define HPJD_INTERVENTION_REQUIRED ".1.3.6.1.4.1.11.2.3.9.1.1.2.3" @@ -59,15 +57,15 @@ const char *option_summary = "-H host [-C community]\n"; #define ONLINE 0 #define OFFLINE 1 -int process_arguments(int, char **); -int validate_arguments(void); -void print_help(void); +static int process_arguments(int, char **); +static int validate_arguments(void); +static void print_help(void); void print_usage(void); -char *community = NULL; -char *address = NULL; -unsigned int port = 0; -int check_paper_out = 1; +static char *community = NULL; +static char *address = NULL; +static unsigned int port = 0; +static int check_paper_out = 1; int main(int argc, char **argv) { char command_line[1024]; -- cgit v1.2.3-74-g34f1 From e03fb9904ba91e44023ea56758f438b0005f8972 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:47:51 +0100 Subject: check_hpjd: linter fixes --- plugins/check_hpjd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c index 6e4ddcbf..b39bccff 100644 --- a/plugins/check_hpjd.c +++ b/plugins/check_hpjd.c @@ -57,7 +57,7 @@ const char *email = "devel@monitoring-plugins.org"; #define ONLINE 0 #define OFFLINE 1 -static int process_arguments(int, char **); +static int process_arguments(int /*argc*/, char ** /*argv*/); static int validate_arguments(void); static void print_help(void); void print_usage(void); -- cgit v1.2.3-74-g34f1 From 536d8e700267432dc7b3ab0504d80a9071972a22 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:48:28 +0100 Subject: check_ide_smart: clang-format --- plugins/check_ide_smart.c | 484 +++++++++++++++++++--------------------------- 1 file changed, 202 insertions(+), 282 deletions(-) diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c index 3872e341..00d9eb31 100644 --- a/plugins/check_ide_smart.c +++ b/plugins/check_ide_smart.c @@ -1,112 +1,105 @@ /***************************************************************************** -* -* Monitoring check_ide_smart plugin -* ide-smart 1.3 - IDE S.M.A.R.T. checking tool -* -* License: GPL -* Copyright (C) 1998-1999 Ragnar Hojland Espinosa -* 1998 Gadi Oxman -* Copyright (c) 2000 Robert Dale -* Copyright (c) 2000-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_ide_smart plugin -* -* This plugin checks a local hard drive with the (Linux specific) SMART -* interface -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_ide_smart plugin + * ide-smart 1.3 - IDE S.M.A.R.T. checking tool + * + * License: GPL + * Copyright (C) 1998-1999 Ragnar Hojland Espinosa + * 1998 Gadi Oxman + * Copyright (c) 2000 Robert Dale + * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_ide_smart plugin + * + * This plugin checks a local hard drive with the (Linux specific) SMART + * interface + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_ide_smart"; const char *copyright = "1998-2007"; const char *email = "devel@monitoring-plugins.org"; - + #include "common.h" #include "utils.h" -void print_help (void); -void print_usage (void); +void print_help(void); +void print_usage(void); #include #include #include #ifdef __linux__ -#include -#include +# include +# include -#define OPEN_MODE O_RDONLY +# define OPEN_MODE O_RDONLY #endif /* __linux__ */ #ifdef __NetBSD__ -#include -#include -#include -#include /* for __u8 and friends */ -#include -#include -#include -#include - -#define SMART_ENABLE WDSM_ENABLE_OPS -#define SMART_DISABLE WDSM_DISABLE_OPS -#define SMART_IMMEDIATE_OFFLINE WDSM_EXEC_OFFL_IMM -#define SMART_AUTO_OFFLINE 0xdb /* undefined in NetBSD headers */ - -#define OPEN_MODE O_RDWR +# include +# include +# include +# include /* for __u8 and friends */ +# include +# include +# include +# include + +# define SMART_ENABLE WDSM_ENABLE_OPS +# define SMART_DISABLE WDSM_DISABLE_OPS +# define SMART_IMMEDIATE_OFFLINE WDSM_EXEC_OFFL_IMM +# define SMART_AUTO_OFFLINE 0xdb /* undefined in NetBSD headers */ + +# define OPEN_MODE O_RDWR #endif /* __NetBSD__ */ #include - -#define NR_ATTRIBUTES 30 - -#define PREFAILURE 2 -#define ADVISORY 1 + +#define NR_ATTRIBUTES 30 + +#define PREFAILURE 2 +#define ADVISORY 1 #define OPERATIONAL 0 -#define UNKNOWN -1 +#define UNKNOWN -1 -typedef struct threshold_s -{ +typedef struct threshold_s { __u8 id; __u8 threshold; __u8 reserved[10]; -} -__attribute__ ((packed)) threshold_t; +} __attribute__((packed)) threshold_t; -typedef struct thresholds_s -{ +typedef struct thresholds_s { __u16 revision; threshold_t thresholds[NR_ATTRIBUTES]; __u8 reserved[18]; __u8 vendor[131]; __u8 checksum; -} -__attribute__ ((packed)) thresholds_t; +} __attribute__((packed)) thresholds_t; -typedef struct value_s -{ +typedef struct value_s { __u8 id; __u16 status; __u8 value; __u8 vendor[8]; -} -__attribute__ ((packed)) value_t; +} __attribute__((packed)) value_t; -typedef struct values_s -{ +typedef struct values_s { __u16 revision; value_t values[NR_ATTRIBUTES]; __u8 offline_status; @@ -118,60 +111,43 @@ typedef struct values_s __u8 reserved[16]; __u8 vendor[125]; __u8 checksum; -} -__attribute__ ((packed)) values_t; +} __attribute__((packed)) values_t; -struct -{ +struct { __u8 value; char *text; } -offline_status_text[] = - { - {0x00, "NeverStarted"}, - {0x02, "Completed"}, - {0x04, "Suspended"}, - {0x05, "Aborted"}, - {0x06, "Failed"}, - {0, 0} - }; - -struct -{ +offline_status_text[] = {{0x00, "NeverStarted"}, {0x02, "Completed"}, {0x04, "Suspended"}, {0x05, "Aborted"}, {0x06, "Failed"}, {0, 0}}; + +struct { __u8 value; char *text; } -smart_command[] = - { - {SMART_ENABLE, "SMART_ENABLE"}, - {SMART_DISABLE, "SMART_DISABLE"}, - {SMART_IMMEDIATE_OFFLINE, "SMART_IMMEDIATE_OFFLINE"}, - {SMART_AUTO_OFFLINE, "SMART_AUTO_OFFLINE"} - }; - - -/* Index to smart_command table, keep in order */ -enum SmartCommand - { SMART_CMD_ENABLE, - SMART_CMD_DISABLE, - SMART_CMD_IMMEDIATE_OFFLINE, - SMART_CMD_AUTO_OFFLINE - }; - -char *get_offline_text (int); -int smart_read_values (int, values_t *); -int nagios (values_t *, thresholds_t *); -void print_value (value_t *, threshold_t *); -void print_values (values_t *, thresholds_t *); -int smart_cmd_simple (int, enum SmartCommand, __u8, bool); -int smart_read_thresholds (int, thresholds_t *); +smart_command[] = {{SMART_ENABLE, "SMART_ENABLE"}, + {SMART_DISABLE, "SMART_DISABLE"}, + {SMART_IMMEDIATE_OFFLINE, "SMART_IMMEDIATE_OFFLINE"}, + {SMART_AUTO_OFFLINE, "SMART_AUTO_OFFLINE"}}; + +/* Index to smart_command table, keep in order */ +enum SmartCommand { + SMART_CMD_ENABLE, + SMART_CMD_DISABLE, + SMART_CMD_IMMEDIATE_OFFLINE, + SMART_CMD_AUTO_OFFLINE +}; + +char *get_offline_text(int); +int smart_read_values(int, values_t *); +int nagios(values_t *, thresholds_t *); +void print_value(value_t *, threshold_t *); +void print_values(values_t *, thresholds_t *); +int smart_cmd_simple(int, enum SmartCommand, __u8, bool); +int smart_read_thresholds(int, thresholds_t *); bool verbose = false; -int -main (int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { char *device = NULL; int o, longindex; int retval = 0; @@ -180,28 +156,26 @@ main (int argc, char *argv[]) values_t values; int fd; - static struct option longopts[] = { - {"device", required_argument, 0, 'd'}, - {"immediate", no_argument, 0, 'i'}, - {"quiet-check", no_argument, 0, 'q'}, - {"auto-on", no_argument, 0, '1'}, - {"auto-off", no_argument, 0, '0'}, - {"nagios", no_argument, 0, 'n'}, /* DEPRECATED, but we still accept it */ - {"help", no_argument, 0, 'h'}, - {"version", no_argument, 0, 'V'}, - {0, 0, 0, 0} - }; + static struct option longopts[] = {{"device", required_argument, 0, 'd'}, + {"immediate", no_argument, 0, 'i'}, + {"quiet-check", no_argument, 0, 'q'}, + {"auto-on", no_argument, 0, '1'}, + {"auto-off", no_argument, 0, '0'}, + {"nagios", no_argument, 0, 'n'}, /* DEPRECATED, but we still accept it */ + {"help", no_argument, 0, 'h'}, + {"version", no_argument, 0, 'V'}, + {0, 0, 0, 0}}; /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); while (true) { - - o = getopt_long (argc, argv, "+d:iq10nhVv", longopts, &longindex); + + o = getopt_long(argc, argv, "+d:iq10nhVv", longopts, &longindex); if (o == -1 || o == EOF || o == 1) break; @@ -211,30 +185,30 @@ main (int argc, char *argv[]) device = optarg; break; case 'q': - fprintf (stderr, "%s\n", _("DEPRECATION WARNING: the -q switch (quiet output) is no longer \"quiet\".")); - fprintf (stderr, "%s\n", _("Nagios-compatible output is now always returned.")); + fprintf(stderr, "%s\n", _("DEPRECATION WARNING: the -q switch (quiet output) is no longer \"quiet\".")); + fprintf(stderr, "%s\n", _("Nagios-compatible output is now always returned.")); break; case 'i': case '1': case '0': - printf ("%s\n", _("SMART commands are broken and have been disabled (See Notes in --help).")); + printf("%s\n", _("SMART commands are broken and have been disabled (See Notes in --help).")); return STATE_CRITICAL; break; case 'n': - fprintf (stderr, "%s\n", _("DEPRECATION WARNING: the -n switch (Nagios-compatible output) is now the")); - fprintf (stderr, "%s\n", _("default and will be removed from future releases.")); + fprintf(stderr, "%s\n", _("DEPRECATION WARNING: the -n switch (Nagios-compatible output) is now the")); + fprintf(stderr, "%s\n", _("default and will be removed from future releases.")); break; case 'v': /* verbose */ verbose = true; break; case 'h': - print_help (); + print_help(); return STATE_UNKNOWN; case 'V': - print_revision (progname, NP_VERSION); + print_revision(progname, NP_VERSION); return STATE_UNKNOWN; default: - usage5 (); + usage5(); } } @@ -243,36 +217,33 @@ main (int argc, char *argv[]) } if (!device) { - print_help (); + print_help(); return STATE_UNKNOWN; } - fd = open (device, OPEN_MODE); + fd = open(device, OPEN_MODE); if (fd < 0) { - printf (_("CRITICAL - Couldn't open device %s: %s\n"), device, strerror (errno)); + printf(_("CRITICAL - Couldn't open device %s: %s\n"), device, strerror(errno)); return STATE_CRITICAL; } - if (smart_cmd_simple (fd, SMART_CMD_ENABLE, 0, false)) { - printf (_("CRITICAL - SMART_CMD_ENABLE\n")); + if (smart_cmd_simple(fd, SMART_CMD_ENABLE, 0, false)) { + printf(_("CRITICAL - SMART_CMD_ENABLE\n")); return STATE_CRITICAL; } - smart_read_values (fd, &values); - smart_read_thresholds (fd, &thresholds); - retval = nagios (&values, &thresholds); - if (verbose) print_values (&values, &thresholds); + smart_read_values(fd, &values); + smart_read_thresholds(fd, &thresholds); + retval = nagios(&values, &thresholds); + if (verbose) + print_values(&values, &thresholds); - close (fd); + close(fd); return retval; } - - -char * -get_offline_text (int status) -{ +char *get_offline_text(int status) { int i; for (i = 0; offline_status_text[i].text; i++) { if (offline_status_text[i].value == status) { @@ -282,11 +253,7 @@ get_offline_text (int status) return "UNKNOWN"; } - - -int -smart_read_values (int fd, values_t * values) -{ +int smart_read_values(int fd, values_t *values) { #ifdef __linux__ int e; __u8 args[4 + 512]; @@ -294,12 +261,12 @@ smart_read_values (int fd, values_t * values) args[1] = 0; args[2] = SMART_READ_VALUES; args[3] = 1; - if (ioctl (fd, HDIO_DRIVE_CMD, &args)) { + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) { e = errno; - printf (_("CRITICAL - SMART_READ_VALUES: %s\n"), strerror (errno)); + printf(_("CRITICAL - SMART_READ_VALUES: %s\n"), strerror(errno)); return e; } - memcpy (values, args + 4, 512); + memcpy(values, args + 4, 512); #endif /* __linux__ */ #ifdef __NetBSD__ struct atareq req; @@ -323,7 +290,7 @@ smart_read_values (int fd, values_t * values) if (errno != 0) { int e = errno; - printf (_("CRITICAL - SMART_READ_VALUES: %s\n"), strerror (errno)); + printf(_("CRITICAL - SMART_READ_VALUES: %s\n"), strerror(errno)); return e; } @@ -332,13 +299,9 @@ smart_read_values (int fd, values_t * values) return 0; } - - -int -nagios (values_t * p, thresholds_t * t) -{ - value_t * value = p->values; - threshold_t * threshold = t->thresholds; +int nagios(values_t *p, thresholds_t *t) { + value_t *value = p->values; + threshold_t *threshold = t->thresholds; int status = OPERATIONAL; int prefailure = 0; int advisory = 0; @@ -353,13 +316,11 @@ nagios (values_t * p, thresholds_t * t) if (value->status & 1) { status = PREFAILURE; ++prefailure; - } - else { + } else { status = ADVISORY; ++advisory; } - } - else { + } else { ++passed; } ++total; @@ -369,81 +330,49 @@ nagios (values_t * p, thresholds_t * t) } switch (status) { case PREFAILURE: - printf (_("CRITICAL - %d Harddrive PreFailure%cDetected! %d/%d tests failed.\n"), - prefailure, - prefailure > 1 ? 's' : ' ', - failed, - total); - status=STATE_CRITICAL; + printf(_("CRITICAL - %d Harddrive PreFailure%cDetected! %d/%d tests failed.\n"), prefailure, prefailure > 1 ? 's' : ' ', failed, + total); + status = STATE_CRITICAL; break; case ADVISORY: - printf (_("WARNING - %d Harddrive Advisor%s Detected. %d/%d tests failed.\n"), - advisory, - advisory > 1 ? "ies" : "y", - failed, - total); - status=STATE_WARNING; + printf(_("WARNING - %d Harddrive Advisor%s Detected. %d/%d tests failed.\n"), advisory, advisory > 1 ? "ies" : "y", failed, total); + status = STATE_WARNING; break; case OPERATIONAL: - printf (_("OK - Operational (%d/%d tests passed)\n"), passed, total); - status=STATE_OK; + printf(_("OK - Operational (%d/%d tests passed)\n"), passed, total); + status = STATE_OK; break; default: - printf (_("ERROR - Status '%d' unknown. %d/%d tests passed\n"), status, - passed, total); + printf(_("ERROR - Status '%d' unknown. %d/%d tests passed\n"), status, passed, total); status = STATE_UNKNOWN; break; } return status; } - - -void -print_value (value_t * p, threshold_t * t) -{ - printf ("Id=%3d, Status=%2d {%s , %s}, Value=%3d, Threshold=%3d, %s\n", - p->id, p->status, p->status & 1 ? "PreFailure" : "Advisory ", - p->status & 2 ? "OnLine " : "OffLine", p->value, t->threshold, - p->value >= t->threshold ? "Passed" : "Failed"); +void print_value(value_t *p, threshold_t *t) { + printf("Id=%3d, Status=%2d {%s , %s}, Value=%3d, Threshold=%3d, %s\n", p->id, p->status, p->status & 1 ? "PreFailure" : "Advisory ", + p->status & 2 ? "OnLine " : "OffLine", p->value, t->threshold, p->value >= t->threshold ? "Passed" : "Failed"); } - - -void -print_values (values_t * p, thresholds_t * t) -{ - value_t * value = p->values; - threshold_t * threshold = t->thresholds; +void print_values(values_t *p, thresholds_t *t) { + value_t *value = p->values; + threshold_t *threshold = t->thresholds; int i; for (i = 0; i < NR_ATTRIBUTES; i++) { if (value->id && threshold->id && value->id == threshold->id) { - print_value (value++, threshold++); + print_value(value++, threshold++); } } - printf - (_("OffLineStatus=%d {%s}, AutoOffLine=%s, OffLineTimeout=%d minutes\n"), - p->offline_status, - get_offline_text (p->offline_status & 0x7f), - (p->offline_status & 0x80 ? "Yes" : "No"), - p->offline_timeout / 60); - printf - (_("OffLineCapability=%d {%s %s %s}\n"), - p->offline_capability, - p->offline_capability & 1 ? "Immediate" : "", - p->offline_capability & 2 ? "Auto" : "", - p->offline_capability & 4 ? "AbortOnCmd" : "SuspendOnCmd"); - printf - (_("SmartRevision=%d, CheckSum=%d, SmartCapability=%d {%s %s}\n"), - p->revision, - p->checksum, - p->smart_capability, - p->smart_capability & 1 ? "SaveOnStandBy" : "", - p->smart_capability & 2 ? "AutoSave" : ""); + printf(_("OffLineStatus=%d {%s}, AutoOffLine=%s, OffLineTimeout=%d minutes\n"), p->offline_status, + get_offline_text(p->offline_status & 0x7f), (p->offline_status & 0x80 ? "Yes" : "No"), p->offline_timeout / 60); + printf(_("OffLineCapability=%d {%s %s %s}\n"), p->offline_capability, p->offline_capability & 1 ? "Immediate" : "", + p->offline_capability & 2 ? "Auto" : "", p->offline_capability & 4 ? "AbortOnCmd" : "SuspendOnCmd"); + printf(_("SmartRevision=%d, CheckSum=%d, SmartCapability=%d {%s %s}\n"), p->revision, p->checksum, p->smart_capability, + p->smart_capability & 1 ? "SaveOnStandBy" : "", p->smart_capability & 2 ? "AutoSave" : ""); } - -int smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, bool show_error) { +int smart_cmd_simple(int fd, enum SmartCommand command, __u8 val0, bool show_error) { int e = STATE_UNKNOWN; #ifdef __linux__ __u8 args[4]; @@ -451,14 +380,14 @@ int smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, bool show_er args[1] = val0; args[2] = smart_command[command].value; args[3] = 0; - if (ioctl (fd, HDIO_DRIVE_CMD, &args)) { + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) { e = STATE_CRITICAL; if (show_error) - printf (_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror (errno)); + printf(_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror(errno)); } else { e = STATE_OK; if (show_error) - printf (_("OK - Command sent (%s)\n"), smart_command[command].text); + printf(_("OK - Command sent (%s)\n"), smart_command[command].text); } #endif /* __linux__ */ @@ -483,35 +412,31 @@ int smart_cmd_simple (int fd, enum SmartCommand command, __u8 val0, bool show_er if (errno != 0) { e = STATE_CRITICAL; if (show_error) - printf (_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror (errno)); + printf(_("CRITICAL - %s: %s\n"), smart_command[command].text, strerror(errno)); } else { e = STATE_OK; if (show_error) - printf (_("OK - Command sent (%s)\n"), smart_command[command].text); + printf(_("OK - Command sent (%s)\n"), smart_command[command].text); } #endif /* __NetBSD__ */ return e; } - - -int -smart_read_thresholds (int fd, thresholds_t * thresholds) -{ +int smart_read_thresholds(int fd, thresholds_t *thresholds) { #ifdef __linux__ int e; __u8 args[4 + 512]; args[0] = WIN_SMART; - args[1] = 0; - args[2] = SMART_READ_THRESHOLDS; - args[3] = 1; - if (ioctl (fd, HDIO_DRIVE_CMD, &args)) { + args[1] = 0; + args[2] = SMART_READ_THRESHOLDS; + args[3] = 1; + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) { e = errno; - printf (_("CRITICAL - SMART_READ_THRESHOLDS: %s\n"), strerror (errno)); + printf(_("CRITICAL - SMART_READ_THRESHOLDS: %s\n"), strerror(errno)); return e; } - memcpy (thresholds, args + 4, 512); + memcpy(thresholds, args + 4, 512); #endif /* __linux__ */ #ifdef __NetBSD__ struct atareq req; @@ -535,7 +460,7 @@ smart_read_thresholds (int fd, thresholds_t * thresholds) if (errno != 0) { int e = errno; - printf (_("CRITICAL - SMART_READ_THRESHOLDS: %s\n"), strerror (errno)); + printf(_("CRITICAL - SMART_READ_THRESHOLDS: %s\n"), strerror(errno)); return e; } @@ -544,45 +469,43 @@ smart_read_thresholds (int fd, thresholds_t * thresholds) return 0; } +void print_help(void) { + print_revision(progname, NP_VERSION); -void -print_help (void) -{ - print_revision (progname, NP_VERSION); + printf("(C) 1999 Ragnar Hojland Espinosa \n"); + printf("Plugin implementation - 1999 Robert Dale \n"); + printf(COPYRIGHT, copyright, email); - printf ("(C) 1999 Ragnar Hojland Espinosa \n"); - printf ("Plugin implementation - 1999 Robert Dale \n"); - printf (COPYRIGHT, copyright, email); + printf(_("This plugin checks a local hard drive with the (Linux specific) SMART interface " + "[http://smartlinux.sourceforge.net/smart/index.php].")); - printf (_("This plugin checks a local hard drive with the (Linux specific) SMART interface [http://smartlinux.sourceforge.net/smart/index.php].")); + printf("\n\n"); - printf ("\n\n"); + print_usage(); - print_usage (); + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); + printf(" %s\n", "-d, --device=DEVICE"); + printf(" %s\n", _("Select device DEVICE")); + printf(" %s\n", _("Note: if the device is specified without this option, any further option will")); + printf(" %s\n", _("be ignored.")); - printf (" %s\n", "-d, --device=DEVICE"); - printf (" %s\n", _("Select device DEVICE")); - printf (" %s\n", _("Note: if the device is specified without this option, any further option will")); - printf (" %s\n", _("be ignored.")); + printf(UT_VERBOSE); - printf (UT_VERBOSE); + printf("\n"); + printf("%s\n", _("Notes:")); + printf(" %s\n", _("The SMART command modes (-i/--immediate, -0/--auto-off and -1/--auto-on) were")); + printf(" %s\n", _("broken in an underhand manner and have been disabled. You can use smartctl")); + printf(" %s\n", _("instead:")); + printf(" %s\n", _("-0/--auto-off: use \"smartctl --offlineauto=off\"")); + printf(" %s\n", _("-1/--auto-on: use \"smartctl --offlineauto=on\"")); + printf(" %s\n", _("-i/--immediate: use \"smartctl --test=offline\"")); - printf ("\n"); - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("The SMART command modes (-i/--immediate, -0/--auto-off and -1/--auto-on) were")); - printf (" %s\n", _("broken in an underhand manner and have been disabled. You can use smartctl")); - printf (" %s\n", _("instead:")); - printf (" %s\n", _("-0/--auto-off: use \"smartctl --offlineauto=off\"")); - printf (" %s\n", _("-1/--auto-on: use \"smartctl --offlineauto=on\"")); - printf (" %s\n", _("-i/--immediate: use \"smartctl --test=offline\"")); - - printf (UT_SUPPORT); + printf(UT_SUPPORT); } - /* todo : add to the long nanual as example +/* todo : add to the long nanual as example * * Run with: check_ide-smart --nagios [-d] * Where DRIVE is an IDE drive, ie. /dev/hda, /dev/hdb, /dev/hdc @@ -593,10 +516,7 @@ print_help (void) * - Returns -1 not too often */ - -void -print_usage (void) -{ - printf ("%s\n", _("Usage:")); - printf ("%s [-d ] [-v]", progname); +void print_usage(void) { + printf("%s\n", _("Usage:")); + printf("%s [-d ] [-v]", progname); } -- cgit v1.2.3-74-g34f1 From c16bc4024caed74a3ceb9168c7e50ce3ad09dacb Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:49:17 +0100 Subject: check_ide_smart: update copyright --- plugins/check_ide_smart.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c index 00d9eb31..550cd981 100644 --- a/plugins/check_ide_smart.c +++ b/plugins/check_ide_smart.c @@ -7,7 +7,7 @@ * Copyright (C) 1998-1999 Ragnar Hojland Espinosa * 1998 Gadi Oxman * Copyright (c) 2000 Robert Dale - * Copyright (c) 2000-2007 Monitoring Plugins Development Team + * Copyright (c) 2000-2024 Monitoring Plugins Development Team * * Description: * @@ -34,7 +34,7 @@ *****************************************************************************/ const char *progname = "check_ide_smart"; -const char *copyright = "1998-2007"; +const char *copyright = "1998-2024"; const char *email = "devel@monitoring-plugins.org"; #include "common.h" -- cgit v1.2.3-74-g34f1 From 5c6d79dac31b55d78fcbb10c48ab357574307bc0 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:51:37 +0100 Subject: check_ide_smart: do not export local symbols --- plugins/check_ide_smart.c | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c index 550cd981..fc75e53d 100644 --- a/plugins/check_ide_smart.c +++ b/plugins/check_ide_smart.c @@ -40,7 +40,7 @@ const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "utils.h" -void print_help(void); +static void print_help(void); void print_usage(void); #include @@ -118,14 +118,12 @@ struct { char *text; } -offline_status_text[] = {{0x00, "NeverStarted"}, {0x02, "Completed"}, {0x04, "Suspended"}, {0x05, "Aborted"}, {0x06, "Failed"}, {0, 0}}; +static offline_status_text[] = {{0x00, "NeverStarted"}, {0x02, "Completed"}, {0x04, "Suspended"}, {0x05, "Aborted"}, {0x06, "Failed"}, {0, 0}}; -struct { +static struct { __u8 value; char *text; -} - -smart_command[] = {{SMART_ENABLE, "SMART_ENABLE"}, +} smart_command[] = {{SMART_ENABLE, "SMART_ENABLE"}, {SMART_DISABLE, "SMART_DISABLE"}, {SMART_IMMEDIATE_OFFLINE, "SMART_IMMEDIATE_OFFLINE"}, {SMART_AUTO_OFFLINE, "SMART_AUTO_OFFLINE"}}; @@ -138,14 +136,14 @@ enum SmartCommand { SMART_CMD_AUTO_OFFLINE }; -char *get_offline_text(int); -int smart_read_values(int, values_t *); -int nagios(values_t *, thresholds_t *); -void print_value(value_t *, threshold_t *); -void print_values(values_t *, thresholds_t *); -int smart_cmd_simple(int, enum SmartCommand, __u8, bool); -int smart_read_thresholds(int, thresholds_t *); -bool verbose = false; +static char *get_offline_text(int); +static int smart_read_values(int, values_t *); +static int nagios(values_t *, thresholds_t *); +static void print_value(value_t *, threshold_t *); +static void print_values(values_t *, thresholds_t *); +static int smart_cmd_simple(int, enum SmartCommand, __u8, bool); +static int smart_read_thresholds(int, thresholds_t *); +static bool verbose = false; int main(int argc, char *argv[]) { char *device = NULL; -- cgit v1.2.3-74-g34f1 From 4db8808a5120778004b8ade834f30d0f4b3db914 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 03:52:36 +0100 Subject: check_ide_smart: linter fixes --- plugins/check_ide_smart.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c index fc75e53d..cfc7908e 100644 --- a/plugins/check_ide_smart.c +++ b/plugins/check_ide_smart.c @@ -147,7 +147,8 @@ static bool verbose = false; int main(int argc, char *argv[]) { char *device = NULL; - int o, longindex; + int o; + int longindex; int retval = 0; thresholds_t thresholds; -- cgit v1.2.3-74-g34f1 From cc45c9772b4a7df9cd2231fa8f36c33ca09495a7 Mon Sep 17 00:00:00 2001 From: RincewindsHat <12514511+RincewindsHat@users.noreply.github.com> Date: Thu, 31 Oct 2024 12:15:15 +0100 Subject: check_mrtg: clang-format --- plugins/check_mrtg.c | 379 +++++++++++++++++++++++---------------------------- 1 file changed, 172 insertions(+), 207 deletions(-) diff --git a/plugins/check_mrtg.c b/plugins/check_mrtg.c index 826b77e9..e4d32439 100644 --- a/plugins/check_mrtg.c +++ b/plugins/check_mrtg.c @@ -1,33 +1,33 @@ /***************************************************************************** -* -* Monitoring check_mrtg plugin -* -* License: GPL -* Copyright (c) 1999-2007 Monitoring Plugins Development Team -* -* Description: -* -* This file contains the check_mrtg plugin -* -* This plugin will check either the average or maximum value of one of the -* two variables recorded in an MRTG log file. -* -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -* -* -*****************************************************************************/ + * + * Monitoring check_mrtg plugin + * + * License: GPL + * Copyright (c) 1999-2007 Monitoring Plugins Development Team + * + * Description: + * + * This file contains the check_mrtg plugin + * + * This plugin will check either the average or maximum value of one of the + * two variables recorded in an MRTG log file. + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + *****************************************************************************/ const char *progname = "check_mrtg"; const char *copyright = "1999-2007"; @@ -36,10 +36,10 @@ const char *email = "devel@monitoring-plugins.org"; #include "common.h" #include "utils.h" -int process_arguments (int, char **); -int validate_arguments (void); -void print_help (void); -void print_usage (void); +int process_arguments(int, char **); +int validate_arguments(void); +void print_help(void); +void print_usage(void); char *log_file = NULL; int expire_minutes = 0; @@ -50,9 +50,7 @@ unsigned long value_critical_threshold = 0L; char *label; char *units; -int -main (int argc, char **argv) -{ +int main(int argc, char **argv) { int result = STATE_OK; FILE *fp; int line; @@ -64,25 +62,25 @@ main (int argc, char **argv) unsigned long maximum_value_rate = 0L; unsigned long rate = 0L; - setlocale (LC_ALL, ""); - bindtextdomain (PACKAGE, LOCALEDIR); - textdomain (PACKAGE); + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); /* Parse extra opts if any */ - argv=np_extra_opts (&argc, argv, progname); + argv = np_extra_opts(&argc, argv, progname); - if (process_arguments (argc, argv) == ERROR) - usage4 (_("Could not parse arguments\n")); + if (process_arguments(argc, argv) == ERROR) + usage4(_("Could not parse arguments\n")); /* open the MRTG log file for reading */ - fp = fopen (log_file, "r"); + fp = fopen(log_file, "r"); if (fp == NULL) { - printf (_("Unable to open MRTG log file\n")); + printf(_("Unable to open MRTG log file\n")); return STATE_UNKNOWN; } line = 0; - while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) { + while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, fp)) { line++; @@ -95,45 +93,43 @@ main (int argc, char **argv) break; /* grab the timestamp */ - temp_buffer = strtok (input_buffer, " "); - timestamp = strtoul (temp_buffer, NULL, 10); + temp_buffer = strtok(input_buffer, " "); + timestamp = strtoul(temp_buffer, NULL, 10); /* grab the average value 1 rate */ - temp_buffer = strtok (NULL, " "); + temp_buffer = strtok(NULL, " "); if (variable_number == 1) - average_value_rate = strtoul (temp_buffer, NULL, 10); + average_value_rate = strtoul(temp_buffer, NULL, 10); /* grab the average value 2 rate */ - temp_buffer = strtok (NULL, " "); + temp_buffer = strtok(NULL, " "); if (variable_number == 2) - average_value_rate = strtoul (temp_buffer, NULL, 10); + average_value_rate = strtoul(temp_buffer, NULL, 10); /* grab the maximum value 1 rate */ - temp_buffer = strtok (NULL, " "); + temp_buffer = strtok(NULL, " "); if (variable_number == 1) - maximum_value_rate = strtoul (temp_buffer, NULL, 10); + maximum_value_rate = strtoul(temp_buffer, NULL, 10); /* grab the maximum value 2 rate */ - temp_buffer = strtok (NULL, " "); + temp_buffer = strtok(NULL, " "); if (variable_number == 2) - maximum_value_rate = strtoul (temp_buffer, NULL, 10); + maximum_value_rate = strtoul(temp_buffer, NULL, 10); } /* close the log file */ - fclose (fp); + fclose(fp); /* if we couldn't read enough data, return an unknown error */ if (line <= 2) { - printf (_("Unable to process MRTG log file\n")); + printf(_("Unable to process MRTG log file\n")); return STATE_UNKNOWN; } /* make sure the MRTG data isn't too old */ - time (¤t_time); - if (expire_minutes > 0 - && (current_time - timestamp) > (expire_minutes * 60)) { - printf (_("MRTG data has expired (%d minutes old)\n"), - (int) ((current_time - timestamp) / 60)); + time(¤t_time); + if (expire_minutes > 0 && (current_time - timestamp) > (expire_minutes * 60)) { + printf(_("MRTG data has expired (%d minutes old)\n"), (int)((current_time - timestamp) / 60)); return STATE_WARNING; } @@ -148,98 +144,80 @@ main (int argc, char **argv) else if (rate > value_warning_threshold) result = STATE_WARNING; - printf("%s. %s = %lu %s|%s\n", - (use_average) ? _("Avg") : _("Max"), - label, rate, units, - perfdata(label, (long) rate, units, - (int) value_warning_threshold, (long) value_warning_threshold, - (int) value_critical_threshold, (long) value_critical_threshold, - 0, 0, 0, 0)); + printf("%s. %s = %lu %s|%s\n", (use_average) ? _("Avg") : _("Max"), label, rate, units, + perfdata(label, (long)rate, units, (int)value_warning_threshold, (long)value_warning_threshold, (int)value_critical_threshold, + (long)value_critical_threshold, 0, 0, 0, 0)); return result; } - - /* process command-line arguments */ -int -process_arguments (int argc, char **argv) -{ +int process_arguments(int argc, char **argv) { int c; int option = 0; static struct option longopts[] = { - {"logfile", required_argument, 0, 'F'}, - {"expires", required_argument, 0, 'e'}, - {"aggregation", required_argument, 0, 'a'}, - {"variable", required_argument, 0, 'v'}, - {"critical", required_argument, 0, 'c'}, - {"warning", required_argument, 0, 'w'}, - {"label", required_argument, 0, 'l'}, - {"units", required_argument, 0, 'u'}, - {"variable", required_argument, 0, 'v'}, - {"version", no_argument, 0, 'V'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} - }; + {"logfile", required_argument, 0, 'F'}, {"expires", required_argument, 0, 'e'}, {"aggregation", required_argument, 0, 'a'}, + {"variable", required_argument, 0, 'v'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, + {"label", required_argument, 0, 'l'}, {"units", required_argument, 0, 'u'}, {"variable", required_argument, 0, 'v'}, + {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; if (argc < 2) return ERROR; for (c = 1; c < argc; c++) { - if (strcmp ("-to", argv[c]) == 0) - strcpy (argv[c], "-t"); - else if (strcmp ("-wt", argv[c]) == 0) - strcpy (argv[c], "-w"); - else if (strcmp ("-ct", argv[c]) == 0) - strcpy (argv[c], "-c"); + if (strcmp("-to", argv[c]) == 0) + strcpy(argv[c], "-t"); + else if (strcmp("-wt", argv[c]) == 0) + strcpy(argv[c], "-w"); + else if (strcmp("-ct", argv[c]) == 0) + strcpy(argv[c], "-c"); } while (1) { - c = getopt_long (argc, argv, "hVF:e:a:v:c:w:l:u:", longopts, - &option); + c = getopt_long(argc, argv, "hVF:e:a:v:c:w:l:u:", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { - case 'F': /* input file */ + case 'F': /* input file */ log_file = optarg; break; - case 'e': /* ups name */ - expire_minutes = atoi (optarg); + case 'e': /* ups name */ + expire_minutes = atoi(optarg); break; - case 'a': /* port */ - if (!strcmp (optarg, "MAX")) + case 'a': /* port */ + if (!strcmp(optarg, "MAX")) use_average = false; else use_average = true; break; case 'v': - variable_number = atoi (optarg); + variable_number = atoi(optarg); if (variable_number < 1 || variable_number > 2) - usage4 (_("Invalid variable number")); + usage4(_("Invalid variable number")); break; - case 'w': /* critical time threshold */ - value_warning_threshold = strtoul (optarg, NULL, 10); + case 'w': /* critical time threshold */ + value_warning_threshold = strtoul(optarg, NULL, 10); break; - case 'c': /* warning time threshold */ - value_critical_threshold = strtoul (optarg, NULL, 10); + case 'c': /* warning time threshold */ + value_critical_threshold = strtoul(optarg, NULL, 10); break; - case 'l': /* label */ + case 'l': /* label */ label = optarg; break; - case 'u': /* timeout */ + case 'u': /* timeout */ units = optarg; break; - case 'V': /* version */ - print_revision (progname, NP_VERSION); - exit (STATE_UNKNOWN); - case 'h': /* help */ - print_help (); - exit (STATE_UNKNOWN); - case '?': /* help */ - usage5 (); + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + case '?': /* help */ + usage5(); } } @@ -249,137 +227,124 @@ process_arguments (int argc, char **argv) } if (expire_minutes <= 0 && argc > c) { - if (is_intpos (argv[c])) - expire_minutes = atoi (argv[c++]); + if (is_intpos(argv[c])) + expire_minutes = atoi(argv[c++]); else - die (STATE_UNKNOWN, - _("%s is not a valid expiration time\nUse '%s -h' for additional help\n"), - argv[c], progname); + die(STATE_UNKNOWN, _("%s is not a valid expiration time\nUse '%s -h' for additional help\n"), argv[c], progname); } - if (argc > c && strcmp (argv[c], "MAX") == 0) { + if (argc > c && strcmp(argv[c], "MAX") == 0) { use_average = false; c++; - } - else if (argc > c && strcmp (argv[c], "AVG") == 0) { + } else if (argc > c && strcmp(argv[c], "AVG") == 0) { use_average = true; c++; } if (argc > c && variable_number == -1) { - variable_number = atoi (argv[c++]); + variable_number = atoi(argv[c++]); if (variable_number < 1 || variable_number > 2) { - printf ("%s :", argv[c]); - usage (_("Invalid variable number\n")); + printf("%s :", argv[c]); + usage(_("Invalid variable number\n")); } } if (argc > c && value_warning_threshold == 0) { - value_warning_threshold = strtoul (argv[c++], NULL, 10); + value_warning_threshold = strtoul(argv[c++], NULL, 10); } if (argc > c && value_critical_threshold == 0) { - value_critical_threshold = strtoul (argv[c++], NULL, 10); + value_critical_threshold = strtoul(argv[c++], NULL, 10); } - if (argc > c && strlen (label) == 0) { + if (argc > c && strlen(label) == 0) { label = argv[c++]; } - if (argc > c && strlen (units) == 0) { + if (argc > c && strlen(units) == 0) { units = argv[c++]; } - return validate_arguments (); + return validate_arguments(); } -int -validate_arguments (void) -{ +int validate_arguments(void) { if (variable_number == -1) - usage4 (_("You must supply the variable number")); + usage4(_("You must supply the variable number")); if (label == NULL) - label = strdup ("value"); + label = strdup("value"); if (units == NULL) - units = strdup (""); + units = strdup(""); return OK; } - - -void -print_help (void) -{ - print_revision (progname, NP_VERSION); - - printf ("Copyright (c) 1999 Ethan Galstad \n"); - printf (COPYRIGHT, copyright, email); - - printf ("%s\n", _("This plugin will check either the average or maximum value of one of the")); - printf ("%s\n", _("two variables recorded in an MRTG log file.")); - - printf ("\n\n"); - - print_usage (); - - printf (UT_HELP_VRSN); - printf (UT_EXTRA_OPTS); - - printf (" %s\n", "-F, --logfile=FILE"); - printf (" %s\n", _("The MRTG log file containing the data you want to monitor")); - printf (" %s\n", "-e, --expires=MINUTES"); - printf (" %s\n", _("Minutes before MRTG data is considered to be too old")); - printf (" %s\n", "-a, --aggregation=AVG|MAX"); - printf (" %s\n", _("Should we check average or maximum values?")); - printf (" %s\n", "-v, --variable=INTEGER"); - printf (" %s\n", _("Which variable set should we inspect? (1 or 2)")); - printf (" %s\n", "-w, --warning=INTEGER"); - printf (" %s\n", _("Threshold value for data to result in WARNING status")); - printf (" %s\n", "-c, --critical=INTEGER"); - printf (" %s\n", _("Threshold value for data to result in CRITICAL status")); - printf (" %s\n", "-l, --label=STRING"); - printf (" %s\n", _("Type label for data (Examples: Conns, \"Processor Load\", In, Out)")); - printf (" %s\n", "-u, --units=STRING"); - printf (" %s\n", _("Option units label for data (Example: Packets/Sec, Errors/Sec,")); - printf (" %s\n", _("\"Bytes Per Second\", \"%% Utilization\")")); - - printf ("\n"); - printf (" %s\n", _("If the value exceeds the threshold, a WARNING status is returned. If")); - printf (" %s\n", _("the value exceeds the threshold, a CRITICAL status is returned. If")); - printf (" %s\n", _("the data in the log file is older than old, a WARNING")); - printf (" %s\n", _("status is returned and a warning message is printed.")); - - printf ("\n"); - printf (" %s\n", _("This plugin is useful for monitoring MRTG data that does not correspond to")); - printf (" %s\n", _("bandwidth usage. (Use the check_mrtgtraf plugin for monitoring bandwidth).")); - printf (" %s\n", _("It can be used to monitor any kind of data that MRTG is monitoring - errors,")); - printf (" %s\n", _("packets/sec, etc. I use MRTG in conjunction with the Novell NLM that allows")); - printf (" %s\n", _("me to track processor utilization, user connections, drive space, etc and")); - printf (" %s\n\n", _("this plugin works well for monitoring that kind of data as well.")); - - printf ("%s\n", _("Notes:")); - printf (" %s\n", _("- This plugin only monitors one of the two variables stored in the MRTG log")); - printf (" %s\n", _("file. If you want to monitor both values you will have to define two")); - printf (" %s\n", _("commands with different values for the argument. Of course,")); - printf (" %s\n", _("you can always hack the code to make this plugin work for you...")); - printf (" %s\n", _("- MRTG stands for the Multi Router Traffic Grapher. It can be downloaded from")); - printf (" %s\n", "http://ee-staff.ethz.ch/~oetiker/webtools/mrtg/mrtg.html"); - - printf (UT_SUPPORT); +void print_help(void) { + print_revision(progname, NP_VERSION); + + printf("Copyright (c) 1999 Ethan Galstad \n"); + printf(COPYRIGHT, copyright, email); + + printf("%s\n", _("This plugin will check either the average or maximum value of one of the")); + printf("%s\n", _("two variables recorded in an MRTG log file.")); + + printf("\n\n"); + + print_usage(); + + printf(UT_HELP_VRSN); + printf(UT_EXTRA_OPTS); + + printf(" %s\n", "-F, --logfile=FILE"); + printf(" %s\n", _("The MRTG log file containing the data you want to monitor")); + printf(" %s\n", "-e, --expires=MINUTES"); + printf(" %s\n", _("Minutes before MRTG data is considered to be too old")); + printf(" %s\n", "-a, --aggregation=AVG|MAX"); + printf(" %s\n", _("Should we check average or maximum values?")); + printf(" %s\n", "-v, --variable=INTEGER"); + printf(" %s\n", _("Which variable set should we inspect? (1 or 2)")); + printf(" %s\n", "-w, --warning=INTEGER"); + printf(" %s\n", _("Threshold value for data to result in WARNING status")); + printf(" %s\n", "-c, --critical=INTEGER"); + printf(" %s\n", _("Threshold value for data to result in CRITICAL status")); + printf(" %s\n", "-l, --label=STRING"); + printf(" %s\n", _("Type label for data (Examples: Conns, \"Processor Load\", In, Out)")); + printf(" %s\n", "-u, --units=STRING"); + printf(" %s\n", _("Option units label for data (Example: Packets/Sec, Errors/Sec,")); + printf(" %s\n", _("\"Bytes Per Second\", \"%% Utilization\")")); + + printf("\n"); + printf(" %s\n", _("If the value exceeds the threshold, a WARNING status is returned. If")); + printf(" %s\n", _("the value exceeds the threshold, a CRITICAL status is returned. If")); + printf(" %s\n", _("the data in the log file is older than old, a WARNING")); + printf(" %s\n", _("status is returned and a warning message is printed.")); + + printf("\n"); + printf(" %s\n", _("This plugin is useful for monitoring MRTG data that does not correspond to")); + printf(" %s\n", _("bandwidth usage. (Use the check_mrtgtraf plugin for monitoring bandwidth).")); + printf(" %s\n", _("It can be used to monitor any kind of data that MRTG is monitoring - errors,")); + printf(" %s\n", _("packets/sec, etc. I use MRTG in conjunction with the Novell NLM that allows")); + printf(" %s\n", _("me to track processor utilization, user connections, drive space, etc and")); + printf(" %s\n\n", _("this plugin works well for monitoring that kind of data as well.")); + + printf("%s\n", _("Notes:")); + printf(" %s\n", _("- This plugin only monitors one of the two variables stored in the MRTG log")); + printf(" %s\n", _("file. If you want to monitor both values you will have to define two")); + printf(" %s\n", _("commands with different values for the argument. Of course,")); + printf(" %s\n", _("you can always hack the code to make this plugin work for you...")); + printf(" %s\n", _("- MRTG stands for the Multi Router Traffic Grapher. It can be downloaded from")); + printf(" %s\n", "http://ee-staff.ethz.ch/~oetiker/webtools/mrtg/mrtg.html"); + + printf(UT_SUPPORT); } - - /* original command line: