summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>2025-09-15 16:16:14 +0200
committerLorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>2025-09-15 16:16:14 +0200
commitff7305bdfe2f682857ba888c70aec2fc7cee798e (patch)
treeb5b3bdcf41d42d525906b6e8d82cdf143e74ec5d
parentf07f96c3cfaeb30f95eb1898d6cc58b200e70831 (diff)
parent601a48a63e745817cf2a4c7f3ca526e393dd3fb8 (diff)
downloadmonitoring-plugins-ff7305bd.tar.gz
Merge branch 'master' into refactor/check_apt
-rw-r--r--.gitignore10
-rw-r--r--lib/extra_opts.c55
-rw-r--r--lib/maxfd.c6
-rw-r--r--lib/output.c11
-rw-r--r--lib/parse_ini.c239
-rw-r--r--lib/tests/test_base64.c271
-rw-r--r--lib/tests/test_cmd.c41
-rw-r--r--lib/tests/test_generic_output.c6
-rw-r--r--lib/tests/test_ini1.c54
-rw-r--r--lib/tests/test_opts1.c51
-rw-r--r--lib/tests/test_opts2.c86
-rw-r--r--lib/tests/test_tcp.c28
-rw-r--r--lib/utils_base.c6
-rw-r--r--lib/utils_base.h2
-rw-r--r--lib/utils_cmd.c196
-rw-r--r--lib/utils_cmd.h8
-rw-r--r--lib/utils_tcp.c41
-rw-r--r--lib/utils_tcp.h3
-rw-r--r--plugins-root/check_dhcp.c258
-rw-r--r--plugins-root/check_icmp.d/check_icmp_helpers.c4
-rw-r--r--plugins-root/check_icmp.d/config.h2
-rw-r--r--plugins-root/pst3.c441
-rw-r--r--plugins/check_apt.c8
-rw-r--r--plugins/check_by_ssh.c108
-rw-r--r--plugins/check_cluster.c26
-rw-r--r--plugins/check_dbi.c108
-rw-r--r--plugins/check_dig.c18
-rw-r--r--plugins/check_disk.c288
-rw-r--r--plugins/check_disk.d/utils_disk.c35
-rw-r--r--plugins/check_disk.d/utils_disk.h9
-rw-r--r--plugins/check_dns.c133
-rw-r--r--plugins/check_dummy.c15
-rw-r--r--plugins/check_fping.c58
-rw-r--r--plugins/check_fping.d/config.h1
-rw-r--r--plugins/check_game.c68
-rw-r--r--plugins/check_hpjd.c14
-rw-r--r--plugins/check_ldap.c50
-rw-r--r--plugins/check_load.c28
-rw-r--r--plugins/check_mrtg.c53
-rw-r--r--plugins/check_mrtgtraf.c32
-rw-r--r--plugins/check_mysql.c88
-rw-r--r--plugins/check_mysql_query.c37
-rw-r--r--plugins/check_nt.c115
-rw-r--r--plugins/check_ntp.c756
-rw-r--r--plugins/check_ntp_peer.c118
-rw-r--r--plugins/check_ntp_time.c91
-rw-r--r--plugins/check_pgsql.c77
-rw-r--r--plugins/check_ping.c125
-rw-r--r--plugins/check_procs.c93
-rw-r--r--plugins/check_radius.c36
-rw-r--r--plugins/check_real.c28
-rw-r--r--plugins/check_smtp.c119
-rw-r--r--plugins/check_swap.c23
-rw-r--r--plugins/check_swap.d/check_swap.h3
-rw-r--r--plugins/check_swap.d/swap.c18
-rw-r--r--plugins/check_tcp.c147
-rw-r--r--plugins/check_time.c25
-rw-r--r--plugins/check_ups.c47
-rw-r--r--plugins/check_ups.d/config.h1
-rw-r--r--plugins/check_users.c19
-rw-r--r--plugins/check_users.d/users.c6
-rw-r--r--plugins/common.h175
-rw-r--r--plugins/negate.c44
-rw-r--r--plugins/netutils.c224
-rw-r--r--plugins/netutils.h32
-rw-r--r--plugins/picohttpparser/picohttpparser.c243
-rw-r--r--plugins/picohttpparser/picohttpparser.h31
-rw-r--r--plugins/popen.c68
-rw-r--r--plugins/popen.h20
-rw-r--r--plugins/runcmd.c77
-rw-r--r--plugins/runcmd.h47
-rw-r--r--plugins/sslutils.c6
-rw-r--r--plugins/tests/test_check_disk.c48
-rw-r--r--plugins/tests/test_check_swap.c4
-rw-r--r--plugins/urlize.c36
-rw-r--r--plugins/utils.c35
-rw-r--r--plugins/utils.h51
-rw-r--r--tap/tap.c25
-rw-r--r--tap/tap.h43
-rw-r--r--tools/mini_epn.c96
80 files changed, 3615 insertions, 2533 deletions
diff --git a/.gitignore b/.gitignore
index f1fe8b9a..00e19d52 100644
--- a/.gitignore
+++ b/.gitignore
@@ -233,6 +233,14 @@ plugins/check_disk.d/.dirstamp
233/plugins/check_swap.d/.deps 233/plugins/check_swap.d/.deps
234/plugins/check_swap.d/.dirstamp 234/plugins/check_swap.d/.dirstamp
235 235
236# /plugins/check_snmp.d
237/plugins/check_snmp.d/.deps
238/plugins/check_snmp.d/.dirstamp
239
240# /plugins/check_curl.d
241/plugins/check_curl.d/.deps
242/plugins/check_curl.d/.dirstamp
243
236# /plugins-root/ 244# /plugins-root/
237/plugins-root/.deps 245/plugins-root/.deps
238/plugins-root/.libs 246/plugins-root/.libs
@@ -241,6 +249,8 @@ plugins/check_disk.d/.dirstamp
241/plugins-root/check_dhcp 249/plugins-root/check_dhcp
242/plugins-root/check_icmp 250/plugins-root/check_icmp
243/plugins-root/pst3 251/plugins-root/pst3
252/plugins-root/check_icmp.d/.dirstamp
253/plugins-root/check_icmp.d/.deps
244 254
245# /plugins-scripts/ 255# /plugins-scripts/
246/plugins-scripts/Makefile 256/plugins-scripts/Makefile
diff --git a/lib/extra_opts.c b/lib/extra_opts.c
index 88787336..3fe69014 100644
--- a/lib/extra_opts.c
+++ b/lib/extra_opts.c
@@ -27,27 +27,32 @@
27 27
28/* FIXME: copied from utils.h; we should move a bunch of libs! */ 28/* FIXME: copied from utils.h; we should move a bunch of libs! */
29bool is_option2(char *str) { 29bool is_option2(char *str) {
30 if (!str) 30 if (!str) {
31 return false; 31 return false;
32 else if (strspn(str, "-") == 1 || strspn(str, "-") == 2) 32 }
33
34 if (strspn(str, "-") == 1 || strspn(str, "-") == 2) {
33 return true; 35 return true;
34 else 36 }
35 return false; 37
38 return false;
36} 39}
37 40
38/* this is the externally visible function used by plugins */ 41/* this is the externally visible function used by plugins */
39char **np_extra_opts(int *argc, char **argv, const char *plugin_name) { 42char **np_extra_opts(int *argc, char **argv, const char *plugin_name) {
40 np_arg_list *extra_args = NULL, *ea1 = NULL, *ea_tmp = NULL;
41 char **argv_new = NULL;
42 char *argptr = NULL;
43 int i, j, optfound, argc_new, ea_num = *argc;
44
45 if (*argc < 2) { 43 if (*argc < 2) {
46 /* No arguments provided */ 44 /* No arguments provided */
47 return argv; 45 return argv;
48 } 46 }
49 47
50 for (i = 1; i < *argc; i++) { 48 np_arg_list *extra_args = NULL;
49 np_arg_list *ea1 = NULL;
50 np_arg_list *ea_tmp = NULL;
51 char *argptr = NULL;
52 int optfound;
53 size_t ea_num = (size_t)*argc;
54
55 for (int i = 1; i < *argc; i++) {
51 argptr = NULL; 56 argptr = NULL;
52 optfound = 0; 57 optfound = 0;
53 58
@@ -56,8 +61,10 @@ char **np_extra_opts(int *argc, char **argv, const char *plugin_name) {
56 /* It is a single argument with value */ 61 /* It is a single argument with value */
57 argptr = argv[i] + 13; 62 argptr = argv[i] + 13;
58 /* Delete the extra opts argument */ 63 /* Delete the extra opts argument */
59 for (j = i; j < *argc; j++) 64 for (int j = i; j < *argc; j++) {
60 argv[j] = argv[j + 1]; 65 argv[j] = argv[j + 1];
66 }
67
61 i--; 68 i--;
62 *argc -= 1; 69 *argc -= 1;
63 } else if (strcmp(argv[i], "--extra-opts") == 0) { 70 } else if (strcmp(argv[i], "--extra-opts") == 0) {
@@ -65,8 +72,10 @@ char **np_extra_opts(int *argc, char **argv, const char *plugin_name) {
65 /* It is a argument with separate value */ 72 /* It is a argument with separate value */
66 argptr = argv[i + 1]; 73 argptr = argv[i + 1];
67 /* Delete the extra-opts argument/value */ 74 /* Delete the extra-opts argument/value */
68 for (j = i; j < *argc - 1; j++) 75 for (int j = i; j < *argc - 1; j++) {
69 argv[j] = argv[j + 2]; 76 argv[j] = argv[j + 2];
77 }
78
70 i -= 2; 79 i -= 2;
71 *argc -= 2; 80 *argc -= 2;
72 ea_num--; 81 ea_num--;
@@ -74,8 +83,10 @@ char **np_extra_opts(int *argc, char **argv, const char *plugin_name) {
74 /* It has no value */ 83 /* It has no value */
75 optfound = 1; 84 optfound = 1;
76 /* Delete the extra opts argument */ 85 /* Delete the extra opts argument */
77 for (j = i; j < *argc; j++) 86 for (int j = i; j < *argc; j++) {
78 argv[j] = argv[j + 1]; 87 argv[j] = argv[j + 1];
88 }
89
79 i--; 90 i--;
80 *argc -= 1; 91 *argc -= 1;
81 } 92 }
@@ -94,34 +105,37 @@ char **np_extra_opts(int *argc, char **argv, const char *plugin_name) {
94 /* append the list to extra_args */ 105 /* append the list to extra_args */
95 if (extra_args == NULL) { 106 if (extra_args == NULL) {
96 extra_args = ea1; 107 extra_args = ea1;
97 while ((ea1 = ea1->next)) 108 while ((ea1 = ea1->next)) {
98 ea_num++; 109 ea_num++;
110 }
99 } else { 111 } else {
100 ea_tmp = extra_args; 112 ea_tmp = extra_args;
101 while (ea_tmp->next) { 113 while (ea_tmp->next) {
102 ea_tmp = ea_tmp->next; 114 ea_tmp = ea_tmp->next;
103 } 115 }
104 ea_tmp->next = ea1; 116 ea_tmp->next = ea1;
105 while ((ea1 = ea1->next)) 117 while ((ea1 = ea1->next)) {
106 ea_num++; 118 ea_num++;
119 }
107 } 120 }
108 ea1 = ea_tmp = NULL; 121 ea1 = ea_tmp = NULL;
109 } 122 }
110 } /* lather, rince, repeat */ 123 } /* lather, rince, repeat */
111 124
112 if (ea_num == *argc && extra_args == NULL) { 125 if (ea_num == (size_t)*argc && extra_args == NULL) {
113 /* No extra-opts */ 126 /* No extra-opts */
114 return argv; 127 return argv;
115 } 128 }
116 129
117 /* done processing arguments. now create a new argv array... */ 130 /* done processing arguments. now create a new argv array... */
118 argv_new = (char **)malloc((ea_num + 1) * sizeof(char **)); 131 char **argv_new = (char **)malloc((ea_num + 1) * sizeof(char **));
119 if (argv_new == NULL) 132 if (argv_new == NULL) {
120 die(STATE_UNKNOWN, _("malloc() failed!\n")); 133 die(STATE_UNKNOWN, _("malloc() failed!\n"));
134 }
121 135
122 /* starting with program name */ 136 /* starting with program name */
123 argv_new[0] = argv[0]; 137 argv_new[0] = argv[0];
124 argc_new = 1; 138 int argc_new = 1;
125 /* then parsed ini opts (frying them up in the same run) */ 139 /* then parsed ini opts (frying them up in the same run) */
126 while (extra_args) { 140 while (extra_args) {
127 argv_new[argc_new++] = extra_args->arg; 141 argv_new[argc_new++] = extra_args->arg;
@@ -130,8 +144,9 @@ char **np_extra_opts(int *argc, char **argv, const char *plugin_name) {
130 free(ea1); 144 free(ea1);
131 } 145 }
132 /* finally the rest of the argv array */ 146 /* finally the rest of the argv array */
133 for (i = 1; i < *argc; i++) 147 for (int i = 1; i < *argc; i++) {
134 argv_new[argc_new++] = argv[i]; 148 argv_new[argc_new++] = argv[i];
149 }
135 *argc = argc_new; 150 *argc = argc_new;
136 /* and terminate. */ 151 /* and terminate. */
137 argv_new[argc_new] = NULL; 152 argv_new[argc_new] = NULL;
diff --git a/lib/maxfd.c b/lib/maxfd.c
index ca5b6e54..a0f79949 100644
--- a/lib/maxfd.c
+++ b/lib/maxfd.c
@@ -19,7 +19,6 @@
19 *****************************************************************************/ 19 *****************************************************************************/
20 20
21#include "./maxfd.h" 21#include "./maxfd.h"
22#include <errno.h>
23 22
24long mp_open_max(void) { 23long mp_open_max(void) {
25 long maxfd = 0L; 24 long maxfd = 0L;
@@ -31,10 +30,11 @@ long mp_open_max(void) {
31#ifdef _SC_OPEN_MAX 30#ifdef _SC_OPEN_MAX
32 errno = 0; 31 errno = 0;
33 if ((maxfd = sysconf(_SC_OPEN_MAX)) < 0) { 32 if ((maxfd = sysconf(_SC_OPEN_MAX)) < 0) {
34 if (errno == 0) 33 if (errno == 0) {
35 maxfd = DEFAULT_MAXFD; /* it's indeterminate */ 34 maxfd = DEFAULT_MAXFD; /* it's indeterminate */
36 else 35 } else {
37 die(STATE_UNKNOWN, _("sysconf error for _SC_OPEN_MAX\n")); 36 die(STATE_UNKNOWN, _("sysconf error for _SC_OPEN_MAX\n"));
37 }
38 } 38 }
39#elif defined(OPEN_MAX) 39#elif defined(OPEN_MAX)
40 return OPEN_MAX 40 return OPEN_MAX
diff --git a/lib/output.c b/lib/output.c
index 34ff7dab..f283969f 100644
--- a/lib/output.c
+++ b/lib/output.c
@@ -377,7 +377,9 @@ static inline char *fmt_subcheck_output(mp_output_format output_format, mp_subch
377 377
378 while (tmp_string != NULL) { 378 while (tmp_string != NULL) {
379 *tmp_string = '\0'; 379 *tmp_string = '\0';
380 asprintf(&intermediate_string, "%s%s\n%s", intermediate_string,check.output, generate_indentation_string(indentation+1)); // one more indentation to make it look better 380 asprintf(&intermediate_string, "%s%s\n%s", intermediate_string, check.output,
381 generate_indentation_string(
382 indentation + 1)); // one more indentation to make it look better
381 383
382 if (*(tmp_string + 1) != '\0') { 384 if (*(tmp_string + 1) != '\0') {
383 check.output = tmp_string + 1; 385 check.output = tmp_string + 1;
@@ -394,13 +396,14 @@ static inline char *fmt_subcheck_output(mp_output_format output_format, mp_subch
394 // add the rest (if any) 396 // add the rest (if any)
395 if (have_residual_chars) { 397 if (have_residual_chars) {
396 char *tmp = check.output; 398 char *tmp = check.output;
397 xasprintf(&check.output, "%s\n%s%s", intermediate_string, generate_indentation_string(indentation+1), tmp); 399 xasprintf(&check.output, "%s\n%s%s", intermediate_string,
400 generate_indentation_string(indentation + 1), tmp);
398 } else { 401 } else {
399 check.output = intermediate_string; 402 check.output = intermediate_string;
400 } 403 }
401 } 404 }
402 asprintf(&result, "%s\\_[%s] - %s", generate_indentation_string(indentation), state_text(mp_compute_subcheck_state(check)), 405 asprintf(&result, "%s\\_[%s] - %s", generate_indentation_string(indentation),
403 check.output); 406 state_text(mp_compute_subcheck_state(check)), check.output);
404 407
405 subchecks = check.subchecks; 408 subchecks = check.subchecks;
406 409
diff --git a/lib/parse_ini.c b/lib/parse_ini.c
index 1289aae2..db337622 100644
--- a/lib/parse_ini.c
+++ b/lib/parse_ini.c
@@ -40,26 +40,29 @@ typedef struct {
40 char *stanza; 40 char *stanza;
41} np_ini_info; 41} np_ini_info;
42 42
43static char *default_ini_file_names[] = {"monitoring-plugins.ini", "plugins.ini", "nagios-plugins.ini", NULL}; 43static char *default_ini_file_names[] = {"monitoring-plugins.ini", "plugins.ini",
44 "nagios-plugins.ini", NULL};
44 45
45static char *default_ini_path_names[] = { 46static char *default_ini_path_names[] = {
46 "/usr/local/etc/monitoring-plugins/monitoring-plugins.ini", "/usr/local/etc/monitoring-plugins.ini", 47 "/usr/local/etc/monitoring-plugins/monitoring-plugins.ini",
47 "/etc/monitoring-plugins/monitoring-plugins.ini", "/etc/monitoring-plugins.ini", 48 "/usr/local/etc/monitoring-plugins.ini", "/etc/monitoring-plugins/monitoring-plugins.ini",
49 "/etc/monitoring-plugins.ini",
48 /* deprecated path names (for backward compatibility): */ 50 /* deprecated path names (for backward compatibility): */
49 "/etc/nagios/plugins.ini", "/usr/local/nagios/etc/plugins.ini", "/usr/local/etc/nagios/plugins.ini", "/etc/opt/nagios/plugins.ini", 51 "/etc/nagios/plugins.ini", "/usr/local/nagios/etc/plugins.ini",
50 "/etc/nagios-plugins.ini", "/usr/local/etc/nagios-plugins.ini", "/etc/opt/nagios-plugins.ini", NULL}; 52 "/usr/local/etc/nagios/plugins.ini", "/etc/opt/nagios/plugins.ini", "/etc/nagios-plugins.ini",
53 "/usr/local/etc/nagios-plugins.ini", "/etc/opt/nagios-plugins.ini", NULL};
51 54
52/* eat all characters from a FILE pointer until n is encountered */ 55/* eat all characters from a FILE pointer until n is encountered */
53#define GOBBLE_TO(f, c, n) \ 56#define GOBBLE_TO(f, c, n) \
54 do { \ 57 do { \
55 (c) = fgetc((f)); \ 58 (c) = fgetc((f)); \
56 } while ((c) != EOF && (c) != (n)) 59 } while ((c) != EOF && (c) != (n))
57 60
58/* internal function that returns the constructed defaults options */ 61/* internal function that returns the constructed defaults options */
59static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts); 62static bool read_defaults(FILE *defaults_file, const char *stanza, np_arg_list **opts);
60 63
61/* internal function that converts a single line into options format */ 64/* internal function that converts a single line into options format */
62static int add_option(FILE *f, np_arg_list **optlst); 65static int add_option(FILE *filePointer, np_arg_list **optlst);
63 66
64/* internal functions to find default file */ 67/* internal functions to find default file */
65static char *default_file(void); 68static char *default_file(void);
@@ -71,7 +74,8 @@ static char *default_file_in_path(void);
71 * into its separate parts. 74 * into its separate parts.
72 */ 75 */
73static void parse_locator(const char *locator, const char *def_stanza, np_ini_info *i) { 76static void parse_locator(const char *locator, const char *def_stanza, np_ini_info *i) {
74 size_t locator_len = 0, stanza_len = 0; 77 size_t locator_len = 0;
78 size_t stanza_len = 0;
75 79
76 /* if locator is NULL we'll use default values */ 80 /* if locator is NULL we'll use default values */
77 if (locator != NULL) { 81 if (locator != NULL) {
@@ -87,8 +91,9 @@ static void parse_locator(const char *locator, const char *def_stanza, np_ini_in
87 i->stanza = strdup(def_stanza); 91 i->stanza = strdup(def_stanza);
88 } 92 }
89 93
90 if (i->stanza == NULL) 94 if (i->stanza == NULL) {
91 die(STATE_UNKNOWN, _("malloc() failed!\n")); 95 die(STATE_UNKNOWN, _("malloc() failed!\n"));
96 }
92 97
93 /* check whether there's an @file part */ 98 /* check whether there's an @file part */
94 if (stanza_len == locator_len) { 99 if (stanza_len == locator_len) {
@@ -99,39 +104,46 @@ static void parse_locator(const char *locator, const char *def_stanza, np_ini_in
99 i->file_string_on_heap = true; 104 i->file_string_on_heap = true;
100 } 105 }
101 106
102 if (i->file == NULL || i->file[0] == '\0') 107 if (i->file == NULL || i->file[0] == '\0') {
103 die(STATE_UNKNOWN, _("Cannot find config file in any standard location.\n")); 108 die(STATE_UNKNOWN, _("Cannot find config file in any standard location.\n"));
109 }
104} 110}
105 111
106/* 112/*
107 * This is the externally visible function used by extra_opts. 113 * This is the externally visible function used by extra_opts.
108 */ 114 */
109np_arg_list *np_get_defaults(const char *locator, const char *default_section) { 115np_arg_list *np_get_defaults(const char *locator, const char *default_section) {
110 FILE *inifile = NULL;
111 np_arg_list *defaults = NULL;
112 np_ini_info i;
113 int is_suid_plugin = mp_suid(); 116 int is_suid_plugin = mp_suid();
114 117
115 if (is_suid_plugin && idpriv_temp_drop() == -1) 118 if (is_suid_plugin && idpriv_temp_drop() == -1) {
116 die(STATE_UNKNOWN, _("Cannot drop privileges: %s\n"), strerror(errno)); 119 die(STATE_UNKNOWN, _("Cannot drop privileges: %s\n"), strerror(errno));
120 }
117 121
118 parse_locator(locator, default_section, &i); 122 FILE *inifile = NULL;
119 inifile = strcmp(i.file, "-") == 0 ? stdin : fopen(i.file, "r"); 123 np_ini_info ini_info;
124 parse_locator(locator, default_section, &ini_info);
125 inifile = strcmp(ini_info.file, "-") == 0 ? stdin : fopen(ini_info.file, "r");
120 126
121 if (inifile == NULL) 127 if (inifile == NULL) {
122 die(STATE_UNKNOWN, _("Can't read config file: %s\n"), strerror(errno)); 128 die(STATE_UNKNOWN, _("Can't read config file: %s\n"), strerror(errno));
123 if (!read_defaults(inifile, i.stanza, &defaults)) 129 }
124 die(STATE_UNKNOWN, _("Invalid section '%s' in config file '%s'\n"), i.stanza, i.file);
125 130
126 if (i.file_string_on_heap) { 131 np_arg_list *defaults = NULL;
127 free(i.file); 132 if (!read_defaults(inifile, ini_info.stanza, &defaults)) {
133 die(STATE_UNKNOWN, _("Invalid section '%s' in config file '%s'\n"), ini_info.stanza, ini_info.file);
134 }
135
136 if (ini_info.file_string_on_heap) {
137 free(ini_info.file);
128 } 138 }
129 139
130 if (inifile != stdin) 140 if (inifile != stdin) {
131 fclose(inifile); 141 fclose(inifile);
132 free(i.stanza); 142 }
133 if (is_suid_plugin && idpriv_temp_restore() == -1) 143 free(ini_info.stanza);
144 if (is_suid_plugin && idpriv_temp_restore() == -1) {
134 die(STATE_UNKNOWN, _("Cannot restore privileges: %s\n"), strerror(errno)); 145 die(STATE_UNKNOWN, _("Cannot restore privileges: %s\n"), strerror(errno));
146 }
135 147
136 return defaults; 148 return defaults;
137} 149}
@@ -143,54 +155,58 @@ np_arg_list *np_get_defaults(const char *locator, const char *default_section) {
143 * be extra careful about user-supplied input (i.e. avoiding possible 155 * be extra careful about user-supplied input (i.e. avoiding possible
144 * format string vulnerabilities, etc). 156 * format string vulnerabilities, etc).
145 */ 157 */
146static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts) { 158static bool read_defaults(FILE *defaults_file, const char *stanza, np_arg_list **opts) {
147 int c = 0;
148 bool status = false; 159 bool status = false;
149 size_t i, stanza_len;
150 enum { 160 enum {
151 NOSTANZA, 161 NOSTANZA,
152 WRONGSTANZA, 162 WRONGSTANZA,
153 RIGHTSTANZA 163 RIGHTSTANZA
154 } stanzastate = NOSTANZA; 164 } stanzastate = NOSTANZA;
155 165
156 stanza_len = strlen(stanza); 166 size_t stanza_len = strlen(stanza);
157 167
158 /* our little stanza-parsing state machine */ 168 /* our little stanza-parsing state machine */
159 while ((c = fgetc(f)) != EOF) { 169 int current_char = 0;
170 while ((current_char = fgetc(defaults_file)) != EOF) {
160 /* gobble up leading whitespace */ 171 /* gobble up leading whitespace */
161 if (isspace(c)) 172 if (isspace(current_char)) {
162 continue; 173 continue;
163 switch (c) { 174 }
175 switch (current_char) {
164 /* globble up comment lines */ 176 /* globble up comment lines */
165 case ';': 177 case ';':
166 case '#': 178 case '#':
167 GOBBLE_TO(f, c, '\n'); 179 GOBBLE_TO(defaults_file, current_char, '\n');
168 break; 180 break;
169 /* start of a stanza, check to see if it matches */ 181 /* start of a stanza, check to see if it matches */
170 case '[': 182 case '[': {
171 stanzastate = WRONGSTANZA; 183 stanzastate = WRONGSTANZA;
184 size_t i;
172 for (i = 0; i < stanza_len; i++) { 185 for (i = 0; i < stanza_len; i++) {
173 c = fgetc(f); 186 current_char = fgetc(defaults_file);
174 /* strip leading whitespace */ 187 /* strip leading whitespace */
175 if (i == 0) 188 if (i == 0) {
176 for (; isspace(c); c = fgetc(f)) 189 for (; isspace(current_char); current_char = fgetc(defaults_file)) {
177 continue; 190 }
191 }
178 /* nope, read to the end of the line */ 192 /* nope, read to the end of the line */
179 if (c != stanza[i]) { 193 if (current_char != stanza[i]) {
180 GOBBLE_TO(f, c, '\n'); 194 GOBBLE_TO(defaults_file, current_char, '\n');
181 break; 195 break;
182 } 196 }
183 } 197 }
198
184 /* if it matched up to here and the next char is ']'... */ 199 /* if it matched up to here and the next char is ']'... */
185 if (i == stanza_len) { 200 if (i == stanza_len) {
186 c = fgetc(f); 201 current_char = fgetc(defaults_file);
187 /* strip trailing whitespace */ 202 /* strip trailing whitespace */
188 for (; isspace(c); c = fgetc(f)) 203 for (; isspace(current_char); current_char = fgetc(defaults_file)) {
189 continue; 204 }
190 if (c == ']') 205 if (current_char == ']') {
191 stanzastate = RIGHTSTANZA; 206 stanzastate = RIGHTSTANZA;
207 }
192 } 208 }
193 break; 209 } break;
194 /* otherwise, we're in the body of a stanza or a parse error */ 210 /* otherwise, we're in the body of a stanza or a parse error */
195 default: 211 default:
196 switch (stanzastate) { 212 switch (stanzastate) {
@@ -201,12 +217,12 @@ static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts) {
201 die(STATE_UNKNOWN, "%s\n", _("Config file error")); 217 die(STATE_UNKNOWN, "%s\n", _("Config file error"));
202 /* we're in a stanza, but for a different plugin */ 218 /* we're in a stanza, but for a different plugin */
203 case WRONGSTANZA: 219 case WRONGSTANZA:
204 GOBBLE_TO(f, c, '\n'); 220 GOBBLE_TO(defaults_file, current_char, '\n');
205 break; 221 break;
206 /* okay, this is where we start taking the config */ 222 /* okay, this is where we start taking the config */
207 case RIGHTSTANZA: 223 case RIGHTSTANZA:
208 ungetc(c, f); 224 ungetc(current_char, defaults_file);
209 if (add_option(f, opts)) { 225 if (add_option(defaults_file, opts)) {
210 die(STATE_UNKNOWN, "%s\n", _("Config file error")); 226 die(STATE_UNKNOWN, "%s\n", _("Config file error"));
211 } 227 }
212 status = true; 228 status = true;
@@ -225,13 +241,12 @@ static int read_defaults(FILE *f, const char *stanza, np_arg_list **opts) {
225 * --option[=value] 241 * --option[=value]
226 * appending it to the linked list optbuf. 242 * appending it to the linked list optbuf.
227 */ 243 */
228static int add_option(FILE *f, np_arg_list **optlst) { 244static int add_option(FILE *filePointer, np_arg_list **optlst) {
229 np_arg_list *opttmp = *optlst, *optnew; 245 char *linebuf = NULL;
230 char *linebuf = NULL, *lineend = NULL, *optptr = NULL, *optend = NULL; 246 bool done_reading = false;
231 char *eqptr = NULL, *valptr = NULL, *valend = NULL; 247 const size_t read_sz = 8;
232 short done_reading = 0, equals = 0, value = 0; 248 size_t linebuf_sz = 0;
233 size_t cfg_len = 0, read_sz = 8, linebuf_sz = 0, read_pos = 0; 249 size_t read_pos = 0;
234 size_t opt_len = 0, val_len = 0;
235 250
236 /* read one line from the file */ 251 /* read one line from the file */
237 while (!done_reading) { 252 while (!done_reading) {
@@ -239,74 +254,101 @@ static int add_option(FILE *f, np_arg_list **optlst) {
239 if (linebuf == NULL || read_pos + read_sz >= linebuf_sz) { 254 if (linebuf == NULL || read_pos + read_sz >= linebuf_sz) {
240 linebuf_sz = linebuf_sz > 0 ? linebuf_sz << 1 : read_sz; 255 linebuf_sz = linebuf_sz > 0 ? linebuf_sz << 1 : read_sz;
241 linebuf = realloc(linebuf, linebuf_sz); 256 linebuf = realloc(linebuf, linebuf_sz);
242 if (linebuf == NULL) 257 if (linebuf == NULL) {
243 die(STATE_UNKNOWN, _("malloc() failed!\n")); 258 die(STATE_UNKNOWN, _("malloc() failed!\n"));
259 }
244 } 260 }
245 if (fgets(&linebuf[read_pos], (int)read_sz, f) == NULL) 261
246 done_reading = 1; 262 if (fgets(&linebuf[read_pos], (int)read_sz, filePointer) == NULL) {
247 else { 263 done_reading = true;
264 } else {
248 read_pos = strlen(linebuf); 265 read_pos = strlen(linebuf);
249 if (linebuf[read_pos - 1] == '\n') { 266 if (linebuf[read_pos - 1] == '\n') {
250 linebuf[--read_pos] = '\0'; 267 linebuf[--read_pos] = '\0';
251 done_reading = 1; 268 done_reading = true;
252 } 269 }
253 } 270 }
254 } 271 }
255 lineend = &linebuf[read_pos]; 272
273 char *lineend = &linebuf[read_pos];
256 /* all that to read one line, isn't C fun? :) now comes the parsing :/ */ 274 /* all that to read one line, isn't C fun? :) now comes the parsing :/ */
257 275
258 /* skip leading whitespace */ 276 /* skip leading whitespace */
259 for (optptr = linebuf; optptr < lineend && isspace(*optptr); optptr++) 277 char *optptr = NULL;
260 continue; 278 for (optptr = linebuf; optptr < lineend && isspace(*optptr); optptr++) {
279 }
280
261 /* continue to '=' or EOL, watching for spaces that might precede it */ 281 /* continue to '=' or EOL, watching for spaces that might precede it */
282 char *eqptr = NULL;
283 char *optend = NULL;
262 for (eqptr = optptr; eqptr < lineend && *eqptr != '='; eqptr++) { 284 for (eqptr = optptr; eqptr < lineend && *eqptr != '='; eqptr++) {
263 if (isspace(*eqptr) && optend == NULL) 285 if (isspace(*eqptr) && optend == NULL) {
264 optend = eqptr; 286 optend = eqptr;
265 else 287 } else {
266 optend = NULL; 288 optend = NULL;
289 }
267 } 290 }
268 if (optend == NULL) 291
292 if (optend == NULL) {
269 optend = eqptr; 293 optend = eqptr;
294 }
295
270 --optend; 296 --optend;
297
271 /* ^[[:space:]]*=foo is a syntax error */ 298 /* ^[[:space:]]*=foo is a syntax error */
272 if (optptr == eqptr) 299 if (optptr == eqptr) {
273 die(STATE_UNKNOWN, "%s\n", _("Config file error")); 300 die(STATE_UNKNOWN, "%s\n", _("Config file error"));
301 }
302
274 /* continue from '=' to start of value or EOL */ 303 /* continue from '=' to start of value or EOL */
275 for (valptr = eqptr + 1; valptr < lineend && isspace(*valptr); valptr++) 304 char *valptr = NULL;
276 continue; 305 for (valptr = eqptr + 1; valptr < lineend && isspace(*valptr); valptr++) {
306 }
307
277 /* continue to the end of value */ 308 /* continue to the end of value */
278 for (valend = valptr; valend < lineend; valend++) 309 char *valend = NULL;
279 continue; 310 for (valend = valptr; valend < lineend; valend++) {
311 }
312
280 --valend; 313 --valend;
314
281 /* finally trim off trailing spaces */ 315 /* finally trim off trailing spaces */
282 for (; isspace(*valend); valend--) 316 for (; isspace(*valend); valend--) {
283 continue; 317 }
318
284 /* calculate the length of "--foo" */ 319 /* calculate the length of "--foo" */
285 opt_len = (size_t)(1 + optend - optptr); 320 size_t opt_len = (size_t)(1 + optend - optptr);
286 /* 1-character params needs only one dash */ 321 /* 1-character params needs only one dash */
287 if (opt_len == 1) 322 size_t cfg_len = 0;
323 if (opt_len == 1) {
288 cfg_len = 1 + (opt_len); 324 cfg_len = 1 + (opt_len);
289 else 325 } else {
290 cfg_len = 2 + (opt_len); 326 cfg_len = 2 + (opt_len);
327 }
328
329 size_t val_len = 0;
330 bool equals = false;
331 bool value = false;
291 /* if valptr<lineend then we have to also allocate space for "=bar" */ 332 /* if valptr<lineend then we have to also allocate space for "=bar" */
292 if (valptr < lineend) { 333 if (valptr < lineend) {
293 equals = value = 1; 334 equals = value = true;
294 val_len = (size_t)(1 + valend - valptr); 335 val_len = (size_t)(1 + valend - valptr);
295 cfg_len += 1 + val_len; 336 cfg_len += 1 + val_len;
296 } 337 } else if (valptr == lineend) {
297 /* if valptr==valend then we have "=" but no "bar" */ 338 /* if valptr==valend then we have "=" but no "bar" */
298 else if (valptr == lineend) { 339 equals = true;
299 equals = 1;
300 cfg_len += 1; 340 cfg_len += 1;
301 } 341 }
342
302 /* a line with no equal sign isn't valid */ 343 /* a line with no equal sign isn't valid */
303 if (equals == 0) 344 if (!equals) {
304 die(STATE_UNKNOWN, "%s\n", _("Config file error")); 345 die(STATE_UNKNOWN, "%s\n", _("Config file error"));
346 }
305 347
306 /* okay, now we have all the info we need, so we create a new np_arg_list 348 /* okay, now we have all the info we need, so we create a new np_arg_list
307 * element and set the argument... 349 * element and set the argument...
308 */ 350 */
309 optnew = malloc(sizeof(np_arg_list)); 351 np_arg_list *optnew = malloc(sizeof(np_arg_list));
310 optnew->next = NULL; 352 optnew->next = NULL;
311 353
312 read_pos = 0; 354 read_pos = 0;
@@ -329,11 +371,13 @@ static int add_option(FILE *f, np_arg_list **optlst) {
329 optnew->arg[read_pos] = '\0'; 371 optnew->arg[read_pos] = '\0';
330 372
331 /* ...and put that to the end of the list */ 373 /* ...and put that to the end of the list */
332 if (*optlst == NULL) 374 if (*optlst == NULL) {
333 *optlst = optnew; 375 *optlst = optnew;
334 else { 376 } else {
335 while (opttmp->next != NULL) 377 np_arg_list *opttmp = *optlst;
378 while (opttmp->next != NULL) {
336 opttmp = opttmp->next; 379 opttmp = opttmp->next;
380 }
337 opttmp->next = optnew; 381 opttmp->next = optnew;
338 } 382 }
339 383
@@ -344,7 +388,8 @@ static int add_option(FILE *f, np_arg_list **optlst) {
344static char *default_file(void) { 388static char *default_file(void) {
345 char *ini_file; 389 char *ini_file;
346 390
347 if ((ini_file = getenv("MP_CONFIG_FILE")) != NULL || (ini_file = default_file_in_path()) != NULL) { 391 if ((ini_file = getenv("MP_CONFIG_FILE")) != NULL ||
392 (ini_file = default_file_in_path()) != NULL) {
348 return ini_file; 393 return ini_file;
349 } 394 }
350 395
@@ -357,19 +402,25 @@ static char *default_file(void) {
357} 402}
358 403
359static char *default_file_in_path(void) { 404static char *default_file_in_path(void) {
360 char *config_path, **file; 405 char *config_path;
361 char *dir, *ini_file, *tokens; 406 char **file;
407 char *dir;
408 char *ini_file;
409 char *tokens;
362 410
363 if ((config_path = getenv("NAGIOS_CONFIG_PATH")) == NULL) 411 if ((config_path = getenv("NAGIOS_CONFIG_PATH")) == NULL) {
364 return NULL; 412 return NULL;
413 }
365 /* shall we spit out a warning that NAGIOS_CONFIG_PATH is deprecated? */ 414 /* shall we spit out a warning that NAGIOS_CONFIG_PATH is deprecated? */
366 415
367 if ((tokens = strdup(config_path)) == NULL) 416 if ((tokens = strdup(config_path)) == NULL) {
368 die(STATE_UNKNOWN, "%s\n", _("Insufficient Memory")); 417 die(STATE_UNKNOWN, "%s\n", _("Insufficient Memory"));
418 }
369 for (dir = strtok(tokens, ":"); dir != NULL; dir = strtok(NULL, ":")) { 419 for (dir = strtok(tokens, ":"); dir != NULL; dir = strtok(NULL, ":")) {
370 for (file = default_ini_file_names; *file != NULL; file++) { 420 for (file = default_ini_file_names; *file != NULL; file++) {
371 if ((asprintf(&ini_file, "%s/%s", dir, *file)) < 0) 421 if ((asprintf(&ini_file, "%s/%s", dir, *file)) < 0) {
372 die(STATE_UNKNOWN, "%s\n", _("Insufficient Memory")); 422 die(STATE_UNKNOWN, "%s\n", _("Insufficient Memory"));
423 }
373 if (access(ini_file, F_OK) == 0) { 424 if (access(ini_file, F_OK) == 0) {
374 free(tokens); 425 free(tokens);
375 return ini_file; 426 return ini_file;
diff --git a/lib/tests/test_base64.c b/lib/tests/test_base64.c
index 94cb5aa9..798244da 100644
--- a/lib/tests/test_base64.c
+++ b/lib/tests/test_base64.c
@@ -180,117 +180,168 @@ int main(int argc, char **argv) {
180#endif 180#endif
181 181
182 char random[1024] = { 182 char random[1024] = {
183 0x0b, 0x30, 0x44, 0x62, 0x7c, 0x22, 0x1f, 0x0d, 0x05, 0x67, 0x2c, 0x2a, 0x39, 0x21, 0x46, 0x08, 0x50, 0x66, 0x34, 0x37, 0x0b, 0x45, 183 0x0b, 0x30, 0x44, 0x62, 0x7c, 0x22, 0x1f, 0x0d, 0x05, 0x67, 0x2c, 0x2a, 0x39, 0x21, 0x46,
184 0x4b, 0x38, 0x32, 0x06, 0x7a, 0x3e, 0x7f, 0x0c, 0x40, 0x18, 0x6b, 0x2d, 0x60, 0x4c, 0x60, 0x0c, 0x23, 0x43, 0x3b, 0x3e, 0x1b, 0x16, 184 0x08, 0x50, 0x66, 0x34, 0x37, 0x0b, 0x45, 0x4b, 0x38, 0x32, 0x06, 0x7a, 0x3e, 0x7f, 0x0c,
185 0x04, 0x46, 0x58, 0x3f, 0x40, 0x6a, 0x11, 0x05, 0x63, 0x71, 0x14, 0x35, 0x47, 0x79, 0x13, 0x6f, 0x6b, 0x27, 0x18, 0x5b, 0x48, 0x27, 185 0x40, 0x18, 0x6b, 0x2d, 0x60, 0x4c, 0x60, 0x0c, 0x23, 0x43, 0x3b, 0x3e, 0x1b, 0x16, 0x04,
186 0x3e, 0x6f, 0x15, 0x33, 0x4f, 0x3e, 0x5e, 0x51, 0x73, 0x68, 0x25, 0x0f, 0x06, 0x5b, 0x7c, 0x72, 0x75, 0x3e, 0x3f, 0x1b, 0x5c, 0x6d, 186 0x46, 0x58, 0x3f, 0x40, 0x6a, 0x11, 0x05, 0x63, 0x71, 0x14, 0x35, 0x47, 0x79, 0x13, 0x6f,
187 0x6a, 0x39, 0x7c, 0x63, 0x63, 0x60, 0x6c, 0x7a, 0x33, 0x76, 0x52, 0x13, 0x25, 0x33, 0x7d, 0x65, 0x23, 0x27, 0x11, 0x06, 0x06, 0x47, 187 0x6b, 0x27, 0x18, 0x5b, 0x48, 0x27, 0x3e, 0x6f, 0x15, 0x33, 0x4f, 0x3e, 0x5e, 0x51, 0x73,
188 0x71, 0x1e, 0x14, 0x74, 0x63, 0x70, 0x2d, 0x15, 0x27, 0x18, 0x51, 0x06, 0x05, 0x33, 0x11, 0x2c, 0x6b, 0x00, 0x2d, 0x77, 0x20, 0x48, 188 0x68, 0x25, 0x0f, 0x06, 0x5b, 0x7c, 0x72, 0x75, 0x3e, 0x3f, 0x1b, 0x5c, 0x6d, 0x6a, 0x39,
189 0x0d, 0x73, 0x51, 0x45, 0x25, 0x7f, 0x7f, 0x35, 0x26, 0x2e, 0x26, 0x53, 0x24, 0x68, 0x1e, 0x0e, 0x58, 0x3a, 0x59, 0x50, 0x56, 0x37, 189 0x7c, 0x63, 0x63, 0x60, 0x6c, 0x7a, 0x33, 0x76, 0x52, 0x13, 0x25, 0x33, 0x7d, 0x65, 0x23,
190 0x5f, 0x66, 0x01, 0x4c, 0x5a, 0x64, 0x32, 0x50, 0x7b, 0x6a, 0x20, 0x72, 0x2b, 0x1d, 0x7e, 0x43, 0x7b, 0x61, 0x42, 0x0b, 0x61, 0x73, 190 0x27, 0x11, 0x06, 0x06, 0x47, 0x71, 0x1e, 0x14, 0x74, 0x63, 0x70, 0x2d, 0x15, 0x27, 0x18,
191 0x24, 0x79, 0x3a, 0x6b, 0x4a, 0x79, 0x6e, 0x09, 0x0f, 0x27, 0x2d, 0x0c, 0x5e, 0x32, 0x4b, 0x0d, 0x79, 0x46, 0x39, 0x21, 0x0a, 0x26, 191 0x51, 0x06, 0x05, 0x33, 0x11, 0x2c, 0x6b, 0x00, 0x2d, 0x77, 0x20, 0x48, 0x0d, 0x73, 0x51,
192 0x5f, 0x3a, 0x00, 0x26, 0x3f, 0x13, 0x2e, 0x7e, 0x50, 0x2b, 0x67, 0x46, 0x72, 0x3f, 0x3b, 0x01, 0x46, 0x1b, 0x0b, 0x35, 0x49, 0x39, 192 0x45, 0x25, 0x7f, 0x7f, 0x35, 0x26, 0x2e, 0x26, 0x53, 0x24, 0x68, 0x1e, 0x0e, 0x58, 0x3a,
193 0x19, 0x70, 0x3d, 0x02, 0x41, 0x0e, 0x38, 0x05, 0x76, 0x65, 0x4f, 0x31, 0x6c, 0x5e, 0x17, 0x04, 0x15, 0x36, 0x26, 0x64, 0x34, 0x14, 193 0x59, 0x50, 0x56, 0x37, 0x5f, 0x66, 0x01, 0x4c, 0x5a, 0x64, 0x32, 0x50, 0x7b, 0x6a, 0x20,
194 0x17, 0x7c, 0x0e, 0x0b, 0x5b, 0x55, 0x53, 0x6b, 0x00, 0x42, 0x41, 0x4f, 0x02, 0x5c, 0x13, 0x0a, 0x2c, 0x2c, 0x3e, 0x10, 0x14, 0x33, 194 0x72, 0x2b, 0x1d, 0x7e, 0x43, 0x7b, 0x61, 0x42, 0x0b, 0x61, 0x73, 0x24, 0x79, 0x3a, 0x6b,
195 0x45, 0x7c, 0x7a, 0x5a, 0x31, 0x61, 0x39, 0x08, 0x22, 0x6a, 0x1e, 0x0f, 0x6f, 0x1b, 0x6c, 0x13, 0x5e, 0x79, 0x20, 0x79, 0x50, 0x62, 195 0x4a, 0x79, 0x6e, 0x09, 0x0f, 0x27, 0x2d, 0x0c, 0x5e, 0x32, 0x4b, 0x0d, 0x79, 0x46, 0x39,
196 0x06, 0x2c, 0x76, 0x17, 0x04, 0x2b, 0x2a, 0x75, 0x1f, 0x0c, 0x37, 0x4e, 0x0f, 0x7b, 0x2d, 0x34, 0x75, 0x60, 0x31, 0x74, 0x2e, 0x0a, 196 0x21, 0x0a, 0x26, 0x5f, 0x3a, 0x00, 0x26, 0x3f, 0x13, 0x2e, 0x7e, 0x50, 0x2b, 0x67, 0x46,
197 0x4a, 0x11, 0x6c, 0x49, 0x25, 0x01, 0x3a, 0x3d, 0x22, 0x1e, 0x6d, 0x18, 0x51, 0x78, 0x2d, 0x62, 0x31, 0x4c, 0x50, 0x40, 0x17, 0x4b, 197 0x72, 0x3f, 0x3b, 0x01, 0x46, 0x1b, 0x0b, 0x35, 0x49, 0x39, 0x19, 0x70, 0x3d, 0x02, 0x41,
198 0x6f, 0x22, 0x00, 0x7f, 0x61, 0x2a, 0x34, 0x3e, 0x00, 0x5f, 0x2f, 0x5f, 0x2f, 0x14, 0x2a, 0x55, 0x27, 0x1f, 0x46, 0x1f, 0x12, 0x46, 198 0x0e, 0x38, 0x05, 0x76, 0x65, 0x4f, 0x31, 0x6c, 0x5e, 0x17, 0x04, 0x15, 0x36, 0x26, 0x64,
199 0x5e, 0x1e, 0x0c, 0x7c, 0x38, 0x01, 0x61, 0x64, 0x76, 0x22, 0x6e, 0x08, 0x20, 0x38, 0x4f, 0x73, 0x72, 0x55, 0x12, 0x42, 0x19, 0x50, 199 0x34, 0x14, 0x17, 0x7c, 0x0e, 0x0b, 0x5b, 0x55, 0x53, 0x6b, 0x00, 0x42, 0x41, 0x4f, 0x02,
200 0x61, 0x43, 0x77, 0x7d, 0x41, 0x2e, 0x35, 0x4f, 0x3d, 0x31, 0x28, 0x58, 0x67, 0x1b, 0x03, 0x51, 0x20, 0x32, 0x1c, 0x08, 0x6e, 0x37, 200 0x5c, 0x13, 0x0a, 0x2c, 0x2c, 0x3e, 0x10, 0x14, 0x33, 0x45, 0x7c, 0x7a, 0x5a, 0x31, 0x61,
201 0x75, 0x37, 0x44, 0x4f, 0x68, 0x19, 0x07, 0x64, 0x14, 0x28, 0x25, 0x2b, 0x69, 0x35, 0x18, 0x27, 0x26, 0x14, 0x13, 0x70, 0x42, 0x19, 201 0x39, 0x08, 0x22, 0x6a, 0x1e, 0x0f, 0x6f, 0x1b, 0x6c, 0x13, 0x5e, 0x79, 0x20, 0x79, 0x50,
202 0x12, 0x75, 0x3e, 0x02, 0x5d, 0x7c, 0x13, 0x1f, 0x16, 0x53, 0x3b, 0x74, 0x48, 0x3c, 0x5e, 0x39, 0x6c, 0x1c, 0x1c, 0x74, 0x39, 0x1f, 202 0x62, 0x06, 0x2c, 0x76, 0x17, 0x04, 0x2b, 0x2a, 0x75, 0x1f, 0x0c, 0x37, 0x4e, 0x0f, 0x7b,
203 0x00, 0x1b, 0x06, 0x0a, 0x68, 0x3b, 0x52, 0x4f, 0x1e, 0x6e, 0x3c, 0x35, 0x0c, 0x38, 0x0e, 0x0b, 0x3b, 0x1a, 0x76, 0x23, 0x29, 0x53, 203 0x2d, 0x34, 0x75, 0x60, 0x31, 0x74, 0x2e, 0x0a, 0x4a, 0x11, 0x6c, 0x49, 0x25, 0x01, 0x3a,
204 0x1e, 0x5f, 0x41, 0x0c, 0x4b, 0x0a, 0x65, 0x28, 0x78, 0x67, 0x48, 0x59, 0x26, 0x6d, 0x31, 0x76, 0x23, 0x70, 0x61, 0x64, 0x3b, 0x38, 204 0x3d, 0x22, 0x1e, 0x6d, 0x18, 0x51, 0x78, 0x2d, 0x62, 0x31, 0x4c, 0x50, 0x40, 0x17, 0x4b,
205 0x79, 0x66, 0x74, 0x53, 0x2c, 0x64, 0x64, 0x54, 0x03, 0x54, 0x65, 0x44, 0x4c, 0x18, 0x4f, 0x48, 0x20, 0x4f, 0x72, 0x10, 0x3f, 0x0c, 205 0x6f, 0x22, 0x00, 0x7f, 0x61, 0x2a, 0x34, 0x3e, 0x00, 0x5f, 0x2f, 0x5f, 0x2f, 0x14, 0x2a,
206 0x52, 0x2d, 0x03, 0x14, 0x03, 0x51, 0x42, 0x10, 0x77, 0x6a, 0x34, 0x06, 0x32, 0x03, 0x72, 0x14, 0x7c, 0x08, 0x5d, 0x52, 0x1a, 0x62, 206 0x55, 0x27, 0x1f, 0x46, 0x1f, 0x12, 0x46, 0x5e, 0x1e, 0x0c, 0x7c, 0x38, 0x01, 0x61, 0x64,
207 0x7c, 0x3e, 0x30, 0x7e, 0x5f, 0x7f, 0x54, 0x0f, 0x44, 0x49, 0x5d, 0x5e, 0x10, 0x6a, 0x06, 0x2b, 0x06, 0x53, 0x10, 0x39, 0x37, 0x32, 207 0x76, 0x22, 0x6e, 0x08, 0x20, 0x38, 0x4f, 0x73, 0x72, 0x55, 0x12, 0x42, 0x19, 0x50, 0x61,
208 0x4a, 0x4e, 0x3d, 0x2b, 0x65, 0x38, 0x39, 0x07, 0x72, 0x54, 0x64, 0x4d, 0x56, 0x6a, 0x03, 0x22, 0x70, 0x7b, 0x5f, 0x60, 0x0b, 0x2a, 208 0x43, 0x77, 0x7d, 0x41, 0x2e, 0x35, 0x4f, 0x3d, 0x31, 0x28, 0x58, 0x67, 0x1b, 0x03, 0x51,
209 0x0b, 0x6b, 0x10, 0x64, 0x14, 0x05, 0x22, 0x00, 0x73, 0x40, 0x23, 0x5b, 0x51, 0x1f, 0x2b, 0x1a, 0x5d, 0x69, 0x7a, 0x46, 0x0c, 0x5f, 209 0x20, 0x32, 0x1c, 0x08, 0x6e, 0x37, 0x75, 0x37, 0x44, 0x4f, 0x68, 0x19, 0x07, 0x64, 0x14,
210 0x32, 0x4b, 0x4a, 0x28, 0x52, 0x79, 0x5b, 0x12, 0x42, 0x18, 0x00, 0x5d, 0x27, 0x31, 0x53, 0x3c, 0x4c, 0x36, 0x4e, 0x38, 0x3f, 0x72, 210 0x28, 0x25, 0x2b, 0x69, 0x35, 0x18, 0x27, 0x26, 0x14, 0x13, 0x70, 0x42, 0x19, 0x12, 0x75,
211 0x03, 0x71, 0x02, 0x5b, 0x36, 0x59, 0x7f, 0x75, 0x6e, 0x08, 0x54, 0x0d, 0x34, 0x1c, 0x34, 0x57, 0x5d, 0x69, 0x48, 0x00, 0x3b, 0x05, 211 0x3e, 0x02, 0x5d, 0x7c, 0x13, 0x1f, 0x16, 0x53, 0x3b, 0x74, 0x48, 0x3c, 0x5e, 0x39, 0x6c,
212 0x07, 0x6e, 0x27, 0x65, 0x6e, 0x40, 0x3d, 0x3a, 0x4f, 0x72, 0x5d, 0x39, 0x16, 0x0f, 0x63, 0x12, 0x12, 0x15, 0x3a, 0x70, 0x0d, 0x57, 212 0x1c, 0x1c, 0x74, 0x39, 0x1f, 0x00, 0x1b, 0x06, 0x0a, 0x68, 0x3b, 0x52, 0x4f, 0x1e, 0x6e,
213 0x18, 0x0d, 0x5e, 0x3d, 0x22, 0x68, 0x68, 0x7c, 0x6d, 0x4f, 0x0c, 0x7b, 0x09, 0x2d, 0x4a, 0x73, 0x20, 0x47, 0x07, 0x57, 0x75, 0x5d, 213 0x3c, 0x35, 0x0c, 0x38, 0x0e, 0x0b, 0x3b, 0x1a, 0x76, 0x23, 0x29, 0x53, 0x1e, 0x5f, 0x41,
214 0x53, 0x70, 0x34, 0x21, 0x40, 0x57, 0x51, 0x5e, 0x49, 0x44, 0x00, 0x54, 0x27, 0x04, 0x68, 0x7e, 0x59, 0x56, 0x58, 0x74, 0x14, 0x3c, 214 0x0c, 0x4b, 0x0a, 0x65, 0x28, 0x78, 0x67, 0x48, 0x59, 0x26, 0x6d, 0x31, 0x76, 0x23, 0x70,
215 0x16, 0x33, 0x41, 0x16, 0x4b, 0x2f, 0x49, 0x37, 0x0a, 0x54, 0x08, 0x08, 0x1f, 0x39, 0x67, 0x76, 0x28, 0x28, 0x07, 0x1d, 0x61, 0x47, 215 0x61, 0x64, 0x3b, 0x38, 0x79, 0x66, 0x74, 0x53, 0x2c, 0x64, 0x64, 0x54, 0x03, 0x54, 0x65,
216 0x51, 0x4d, 0x75, 0x26, 0x52, 0x47, 0x47, 0x0c, 0x57, 0x58, 0x74, 0x3e, 0x62, 0x6c, 0x58, 0x3a, 0x44, 0x1e, 0x16, 0x2e, 0x21, 0x1c, 216 0x44, 0x4c, 0x18, 0x4f, 0x48, 0x20, 0x4f, 0x72, 0x10, 0x3f, 0x0c, 0x52, 0x2d, 0x03, 0x14,
217 0x73, 0x45, 0x67, 0x74, 0x4f, 0x33, 0x66, 0x0e, 0x74, 0x66, 0x26, 0x1f, 0x2e, 0x38, 0x44, 0x40, 0x7e, 0x2a, 0x50, 0x52, 0x5e, 0x43, 217 0x03, 0x51, 0x42, 0x10, 0x77, 0x6a, 0x34, 0x06, 0x32, 0x03, 0x72, 0x14, 0x7c, 0x08, 0x5d,
218 0x01, 0x7a, 0x38, 0x49, 0x3c, 0x55, 0x4d, 0x5a, 0x44, 0x08, 0x26, 0x59, 0x4d, 0x45, 0x0b, 0x48, 0x0a, 0x33, 0x5e, 0x4a, 0x4d, 0x75, 218 0x52, 0x1a, 0x62, 0x7c, 0x3e, 0x30, 0x7e, 0x5f, 0x7f, 0x54, 0x0f, 0x44, 0x49, 0x5d, 0x5e,
219 0x16, 0x17, 0x63, 0x46, 0x01, 0x2a, 0x55, 0x7b, 0x0f, 0x02, 0x73, 0x6a, 0x4b, 0x7f, 0x75, 0x65, 0x3c, 0x4c, 0x33, 0x39, 0x6c, 0x74, 219 0x10, 0x6a, 0x06, 0x2b, 0x06, 0x53, 0x10, 0x39, 0x37, 0x32, 0x4a, 0x4e, 0x3d, 0x2b, 0x65,
220 0x05, 0x60, 0x0f, 0x7f, 0x2d, 0x41, 0x4d, 0x4d, 0x46, 0x71, 0x09, 0x6f, 0x4f, 0x60, 0x15, 0x0f, 0x46, 0x73, 0x63, 0x4c, 0x5e, 0x74, 220 0x38, 0x39, 0x07, 0x72, 0x54, 0x64, 0x4d, 0x56, 0x6a, 0x03, 0x22, 0x70, 0x7b, 0x5f, 0x60,
221 0x30, 0x0d, 0x28, 0x43, 0x08, 0x72, 0x32, 0x04, 0x2e, 0x31, 0x29, 0x27, 0x44, 0x6d, 0x13, 0x17, 0x48, 0x0f, 0x49, 0x52, 0x10, 0x13, 221 0x0b, 0x2a, 0x0b, 0x6b, 0x10, 0x64, 0x14, 0x05, 0x22, 0x00, 0x73, 0x40, 0x23, 0x5b, 0x51,
222 0x7f, 0x17, 0x16, 0x62, 0x79, 0x35, 0x78, 0x3e, 0x01, 0x7c, 0x2e, 0x0f, 0x76, 0x3e, 0x5e, 0x53, 0x6c, 0x5b, 0x5f, 0x7c, 0x19, 0x41, 222 0x1f, 0x2b, 0x1a, 0x5d, 0x69, 0x7a, 0x46, 0x0c, 0x5f, 0x32, 0x4b, 0x4a, 0x28, 0x52, 0x79,
223 0x02, 0x2f, 0x17, 0x64, 0x41, 0x75, 0x10, 0x04, 0x47, 0x7c, 0x3d, 0x4b, 0x52, 0x00, 0x10, 0x5d, 0x51, 0x4e, 0x7a, 0x27, 0x25, 0x55, 223 0x5b, 0x12, 0x42, 0x18, 0x00, 0x5d, 0x27, 0x31, 0x53, 0x3c, 0x4c, 0x36, 0x4e, 0x38, 0x3f,
224 0x40, 0x12, 0x35, 0x60, 0x05, 0x1b, 0x34, 0x2d, 0x04, 0x7a, 0x6a, 0x69, 0x02, 0x79, 0x03, 0x3a, 0x2f, 0x06, 0x0a, 0x79, 0x7b, 0x12, 224 0x72, 0x03, 0x71, 0x02, 0x5b, 0x36, 0x59, 0x7f, 0x75, 0x6e, 0x08, 0x54, 0x0d, 0x34, 0x1c,
225 0x5d, 0x7c, 0x52, 0x29, 0x47, 0x58, 0x12, 0x73, 0x3f, 0x27, 0x56, 0x05, 0x0c, 0x48, 0x32, 0x58, 0x6b, 0x57, 0x5c, 0x03, 0x64, 0x56, 225 0x34, 0x57, 0x5d, 0x69, 0x48, 0x00, 0x3b, 0x05, 0x07, 0x6e, 0x27, 0x65, 0x6e, 0x40, 0x3d,
226 0x11, 0x52, 0x7a, 0x30, 0x36, 0x29, 0x17, 0x3b, 0x68, 0x7a, 0x7c, 0x05, 0x6b, 0x6b, 0x13, 0x6a, 0x24, 0x5c, 0x68, 0x42, 0x18, 0x32, 226 0x3a, 0x4f, 0x72, 0x5d, 0x39, 0x16, 0x0f, 0x63, 0x12, 0x12, 0x15, 0x3a, 0x70, 0x0d, 0x57,
227 0x03, 0x73, 0x6e, 0x04, 0x21, 0x2e, 0x01, 0x04, 0x63, 0x7d, 0x44, 0x41, 0x12, 0x31, 0x0b, 0x15, 0x1f, 0x70, 0x00, 0x2e, 0x66, 0x14, 227 0x18, 0x0d, 0x5e, 0x3d, 0x22, 0x68, 0x68, 0x7c, 0x6d, 0x4f, 0x0c, 0x7b, 0x09, 0x2d, 0x4a,
228 0x3c, 0x7f, 0x2b, 0x00, 0x1f, 0x0c, 0x28, 0x59, 0x0a, 0x16, 0x49, 0x5a, 0x5c, 0x64, 0x65, 0x4b, 0x11, 0x29, 0x15, 0x36, 0x5a, 0x65, 228 0x73, 0x20, 0x47, 0x07, 0x57, 0x75, 0x5d, 0x53, 0x70, 0x34, 0x21, 0x40, 0x57, 0x51, 0x5e,
229 0x19, 0x4f, 0x60, 0x23, 0x3a, 0x3a, 0x13, 0x25, 0x02, 0x78, 0x4c, 0x54}; 229 0x49, 0x44, 0x00, 0x54, 0x27, 0x04, 0x68, 0x7e, 0x59, 0x56, 0x58, 0x74, 0x14, 0x3c, 0x16,
230 0x33, 0x41, 0x16, 0x4b, 0x2f, 0x49, 0x37, 0x0a, 0x54, 0x08, 0x08, 0x1f, 0x39, 0x67, 0x76,
231 0x28, 0x28, 0x07, 0x1d, 0x61, 0x47, 0x51, 0x4d, 0x75, 0x26, 0x52, 0x47, 0x47, 0x0c, 0x57,
232 0x58, 0x74, 0x3e, 0x62, 0x6c, 0x58, 0x3a, 0x44, 0x1e, 0x16, 0x2e, 0x21, 0x1c, 0x73, 0x45,
233 0x67, 0x74, 0x4f, 0x33, 0x66, 0x0e, 0x74, 0x66, 0x26, 0x1f, 0x2e, 0x38, 0x44, 0x40, 0x7e,
234 0x2a, 0x50, 0x52, 0x5e, 0x43, 0x01, 0x7a, 0x38, 0x49, 0x3c, 0x55, 0x4d, 0x5a, 0x44, 0x08,
235 0x26, 0x59, 0x4d, 0x45, 0x0b, 0x48, 0x0a, 0x33, 0x5e, 0x4a, 0x4d, 0x75, 0x16, 0x17, 0x63,
236 0x46, 0x01, 0x2a, 0x55, 0x7b, 0x0f, 0x02, 0x73, 0x6a, 0x4b, 0x7f, 0x75, 0x65, 0x3c, 0x4c,
237 0x33, 0x39, 0x6c, 0x74, 0x05, 0x60, 0x0f, 0x7f, 0x2d, 0x41, 0x4d, 0x4d, 0x46, 0x71, 0x09,
238 0x6f, 0x4f, 0x60, 0x15, 0x0f, 0x46, 0x73, 0x63, 0x4c, 0x5e, 0x74, 0x30, 0x0d, 0x28, 0x43,
239 0x08, 0x72, 0x32, 0x04, 0x2e, 0x31, 0x29, 0x27, 0x44, 0x6d, 0x13, 0x17, 0x48, 0x0f, 0x49,
240 0x52, 0x10, 0x13, 0x7f, 0x17, 0x16, 0x62, 0x79, 0x35, 0x78, 0x3e, 0x01, 0x7c, 0x2e, 0x0f,
241 0x76, 0x3e, 0x5e, 0x53, 0x6c, 0x5b, 0x5f, 0x7c, 0x19, 0x41, 0x02, 0x2f, 0x17, 0x64, 0x41,
242 0x75, 0x10, 0x04, 0x47, 0x7c, 0x3d, 0x4b, 0x52, 0x00, 0x10, 0x5d, 0x51, 0x4e, 0x7a, 0x27,
243 0x25, 0x55, 0x40, 0x12, 0x35, 0x60, 0x05, 0x1b, 0x34, 0x2d, 0x04, 0x7a, 0x6a, 0x69, 0x02,
244 0x79, 0x03, 0x3a, 0x2f, 0x06, 0x0a, 0x79, 0x7b, 0x12, 0x5d, 0x7c, 0x52, 0x29, 0x47, 0x58,
245 0x12, 0x73, 0x3f, 0x27, 0x56, 0x05, 0x0c, 0x48, 0x32, 0x58, 0x6b, 0x57, 0x5c, 0x03, 0x64,
246 0x56, 0x11, 0x52, 0x7a, 0x30, 0x36, 0x29, 0x17, 0x3b, 0x68, 0x7a, 0x7c, 0x05, 0x6b, 0x6b,
247 0x13, 0x6a, 0x24, 0x5c, 0x68, 0x42, 0x18, 0x32, 0x03, 0x73, 0x6e, 0x04, 0x21, 0x2e, 0x01,
248 0x04, 0x63, 0x7d, 0x44, 0x41, 0x12, 0x31, 0x0b, 0x15, 0x1f, 0x70, 0x00, 0x2e, 0x66, 0x14,
249 0x3c, 0x7f, 0x2b, 0x00, 0x1f, 0x0c, 0x28, 0x59, 0x0a, 0x16, 0x49, 0x5a, 0x5c, 0x64, 0x65,
250 0x4b, 0x11, 0x29, 0x15, 0x36, 0x5a, 0x65, 0x19, 0x4f, 0x60, 0x23, 0x3a, 0x3a, 0x13, 0x25,
251 0x02, 0x78, 0x4c, 0x54};
230 char b64_known[1369] = { 252 char b64_known[1369] = {
231 0x43, 0x7a, 0x42, 0x45, 0x59, 0x6e, 0x77, 0x69, 0x48, 0x77, 0x30, 0x46, 0x5a, 0x79, 0x77, 0x71, 0x4f, 0x53, 0x46, 0x47, 0x43, 0x46, 253 0x43, 0x7a, 0x42, 0x45, 0x59, 0x6e, 0x77, 0x69, 0x48, 0x77, 0x30, 0x46, 0x5a, 0x79, 0x77,
232 0x42, 0x6d, 0x4e, 0x44, 0x63, 0x4c, 0x52, 0x55, 0x73, 0x34, 0x4d, 0x67, 0x5a, 0x36, 0x50, 0x6e, 0x38, 0x4d, 0x51, 0x42, 0x68, 0x72, 254 0x71, 0x4f, 0x53, 0x46, 0x47, 0x43, 0x46, 0x42, 0x6d, 0x4e, 0x44, 0x63, 0x4c, 0x52, 0x55,
233 0x4c, 0x57, 0x42, 0x4d, 0x59, 0x41, 0x77, 0x6a, 0x51, 0x7a, 0x73, 0x2b, 0x47, 0x78, 0x59, 0x45, 0x52, 0x6c, 0x67, 0x2f, 0x51, 0x47, 255 0x73, 0x34, 0x4d, 0x67, 0x5a, 0x36, 0x50, 0x6e, 0x38, 0x4d, 0x51, 0x42, 0x68, 0x72, 0x4c,
234 0x6f, 0x52, 0x42, 0x57, 0x4e, 0x78, 0x46, 0x44, 0x56, 0x48, 0x65, 0x52, 0x4e, 0x76, 0x61, 0x79, 0x63, 0x59, 0x57, 0x30, 0x67, 0x6e, 256 0x57, 0x42, 0x4d, 0x59, 0x41, 0x77, 0x6a, 0x51, 0x7a, 0x73, 0x2b, 0x47, 0x78, 0x59, 0x45,
235 0x50, 0x6d, 0x38, 0x56, 0x4d, 0x30, 0x38, 0x2b, 0x58, 0x6c, 0x46, 0x7a, 0x61, 0x43, 0x55, 0x50, 0x42, 0x6c, 0x74, 0x38, 0x63, 0x6e, 257 0x52, 0x6c, 0x67, 0x2f, 0x51, 0x47, 0x6f, 0x52, 0x42, 0x57, 0x4e, 0x78, 0x46, 0x44, 0x56,
236 0x55, 0x2b, 0x50, 0x78, 0x74, 0x63, 0x62, 0x57, 0x6f, 0x35, 0x66, 0x47, 0x4e, 0x6a, 0x59, 0x47, 0x78, 0x36, 0x4d, 0x33, 0x5a, 0x53, 258 0x48, 0x65, 0x52, 0x4e, 0x76, 0x61, 0x79, 0x63, 0x59, 0x57, 0x30, 0x67, 0x6e, 0x50, 0x6d,
237 0x45, 0x79, 0x55, 0x7a, 0x66, 0x57, 0x55, 0x6a, 0x4a, 0x78, 0x45, 0x47, 0x42, 0x6b, 0x64, 0x78, 0x48, 0x68, 0x52, 0x30, 0x59, 0x33, 259 0x38, 0x56, 0x4d, 0x30, 0x38, 0x2b, 0x58, 0x6c, 0x46, 0x7a, 0x61, 0x43, 0x55, 0x50, 0x42,
238 0x41, 0x74, 0x46, 0x53, 0x63, 0x59, 0x55, 0x51, 0x59, 0x46, 0x4d, 0x78, 0x45, 0x73, 0x61, 0x77, 0x41, 0x74, 0x64, 0x79, 0x42, 0x49, 260 0x6c, 0x74, 0x38, 0x63, 0x6e, 0x55, 0x2b, 0x50, 0x78, 0x74, 0x63, 0x62, 0x57, 0x6f, 0x35,
239 0x44, 0x58, 0x4e, 0x52, 0x52, 0x53, 0x56, 0x2f, 0x66, 0x7a, 0x55, 0x6d, 0x4c, 0x69, 0x5a, 0x54, 0x4a, 0x47, 0x67, 0x65, 0x44, 0x6c, 261 0x66, 0x47, 0x4e, 0x6a, 0x59, 0x47, 0x78, 0x36, 0x4d, 0x33, 0x5a, 0x53, 0x45, 0x79, 0x55,
240 0x67, 0x36, 0x57, 0x56, 0x42, 0x57, 0x4e, 0x31, 0x39, 0x6d, 0x41, 0x55, 0x78, 0x61, 0x5a, 0x44, 0x4a, 0x51, 0x65, 0x32, 0x6f, 0x67, 262 0x7a, 0x66, 0x57, 0x55, 0x6a, 0x4a, 0x78, 0x45, 0x47, 0x42, 0x6b, 0x64, 0x78, 0x48, 0x68,
241 0x63, 0x69, 0x73, 0x64, 0x66, 0x6b, 0x4e, 0x37, 0x59, 0x55, 0x49, 0x4c, 0x59, 0x58, 0x4d, 0x6b, 0x65, 0x54, 0x70, 0x72, 0x53, 0x6e, 263 0x52, 0x30, 0x59, 0x33, 0x41, 0x74, 0x46, 0x53, 0x63, 0x59, 0x55, 0x51, 0x59, 0x46, 0x4d,
242 0x6c, 0x75, 0x43, 0x51, 0x38, 0x6e, 0x4c, 0x51, 0x78, 0x65, 0x4d, 0x6b, 0x73, 0x4e, 0x65, 0x55, 0x59, 0x35, 0x49, 0x51, 0x6f, 0x6d, 264 0x78, 0x45, 0x73, 0x61, 0x77, 0x41, 0x74, 0x64, 0x79, 0x42, 0x49, 0x44, 0x58, 0x4e, 0x52,
243 0x58, 0x7a, 0x6f, 0x41, 0x4a, 0x6a, 0x38, 0x54, 0x4c, 0x6e, 0x35, 0x51, 0x4b, 0x32, 0x64, 0x47, 0x63, 0x6a, 0x38, 0x37, 0x41, 0x55, 265 0x52, 0x53, 0x56, 0x2f, 0x66, 0x7a, 0x55, 0x6d, 0x4c, 0x69, 0x5a, 0x54, 0x4a, 0x47, 0x67,
244 0x59, 0x62, 0x43, 0x7a, 0x56, 0x4a, 0x4f, 0x52, 0x6c, 0x77, 0x50, 0x51, 0x4a, 0x42, 0x44, 0x6a, 0x67, 0x46, 0x64, 0x6d, 0x56, 0x50, 266 0x65, 0x44, 0x6c, 0x67, 0x36, 0x57, 0x56, 0x42, 0x57, 0x4e, 0x31, 0x39, 0x6d, 0x41, 0x55,
245 0x4d, 0x57, 0x78, 0x65, 0x46, 0x77, 0x51, 0x56, 0x4e, 0x69, 0x5a, 0x6b, 0x4e, 0x42, 0x51, 0x58, 0x66, 0x41, 0x34, 0x4c, 0x57, 0x31, 267 0x78, 0x61, 0x5a, 0x44, 0x4a, 0x51, 0x65, 0x32, 0x6f, 0x67, 0x63, 0x69, 0x73, 0x64, 0x66,
246 0x56, 0x54, 0x61, 0x77, 0x42, 0x43, 0x51, 0x55, 0x38, 0x43, 0x58, 0x42, 0x4d, 0x4b, 0x4c, 0x43, 0x77, 0x2b, 0x45, 0x42, 0x51, 0x7a, 268 0x6b, 0x4e, 0x37, 0x59, 0x55, 0x49, 0x4c, 0x59, 0x58, 0x4d, 0x6b, 0x65, 0x54, 0x70, 0x72,
247 0x52, 0x58, 0x78, 0x36, 0x57, 0x6a, 0x46, 0x68, 0x4f, 0x51, 0x67, 0x69, 0x61, 0x68, 0x34, 0x50, 0x62, 0x78, 0x74, 0x73, 0x45, 0x31, 269 0x53, 0x6e, 0x6c, 0x75, 0x43, 0x51, 0x38, 0x6e, 0x4c, 0x51, 0x78, 0x65, 0x4d, 0x6b, 0x73,
248 0x35, 0x35, 0x49, 0x48, 0x6c, 0x51, 0x59, 0x67, 0x59, 0x73, 0x64, 0x68, 0x63, 0x45, 0x4b, 0x79, 0x70, 0x31, 0x48, 0x77, 0x77, 0x33, 270 0x4e, 0x65, 0x55, 0x59, 0x35, 0x49, 0x51, 0x6f, 0x6d, 0x58, 0x7a, 0x6f, 0x41, 0x4a, 0x6a,
249 0x54, 0x67, 0x39, 0x37, 0x4c, 0x54, 0x52, 0x31, 0x59, 0x44, 0x46, 0x30, 0x4c, 0x67, 0x70, 0x4b, 0x45, 0x57, 0x78, 0x4a, 0x4a, 0x51, 271 0x38, 0x54, 0x4c, 0x6e, 0x35, 0x51, 0x4b, 0x32, 0x64, 0x47, 0x63, 0x6a, 0x38, 0x37, 0x41,
250 0x45, 0x36, 0x50, 0x53, 0x49, 0x65, 0x62, 0x52, 0x68, 0x52, 0x65, 0x43, 0x31, 0x69, 0x4d, 0x55, 0x78, 0x51, 0x51, 0x42, 0x64, 0x4c, 272 0x55, 0x59, 0x62, 0x43, 0x7a, 0x56, 0x4a, 0x4f, 0x52, 0x6c, 0x77, 0x50, 0x51, 0x4a, 0x42,
251 0x62, 0x79, 0x49, 0x41, 0x66, 0x32, 0x45, 0x71, 0x4e, 0x44, 0x34, 0x41, 0x58, 0x79, 0x39, 0x66, 0x4c, 0x78, 0x51, 0x71, 0x56, 0x53, 273 0x44, 0x6a, 0x67, 0x46, 0x64, 0x6d, 0x56, 0x50, 0x4d, 0x57, 0x78, 0x65, 0x46, 0x77, 0x51,
252 0x63, 0x66, 0x52, 0x68, 0x38, 0x53, 0x52, 0x6c, 0x34, 0x65, 0x44, 0x48, 0x77, 0x34, 0x41, 0x57, 0x46, 0x6b, 0x64, 0x69, 0x4a, 0x75, 274 0x56, 0x4e, 0x69, 0x5a, 0x6b, 0x4e, 0x42, 0x51, 0x58, 0x66, 0x41, 0x34, 0x4c, 0x57, 0x31,
253 0x43, 0x43, 0x41, 0x34, 0x54, 0x33, 0x4e, 0x79, 0x56, 0x52, 0x4a, 0x43, 0x47, 0x56, 0x42, 0x68, 0x51, 0x33, 0x64, 0x39, 0x51, 0x53, 275 0x56, 0x54, 0x61, 0x77, 0x42, 0x43, 0x51, 0x55, 0x38, 0x43, 0x58, 0x42, 0x4d, 0x4b, 0x4c,
254 0x34, 0x31, 0x54, 0x7a, 0x30, 0x78, 0x4b, 0x46, 0x68, 0x6e, 0x47, 0x77, 0x4e, 0x52, 0x49, 0x44, 0x49, 0x63, 0x43, 0x47, 0x34, 0x33, 276 0x43, 0x77, 0x2b, 0x45, 0x42, 0x51, 0x7a, 0x52, 0x58, 0x78, 0x36, 0x57, 0x6a, 0x46, 0x68,
255 0x64, 0x54, 0x64, 0x45, 0x54, 0x32, 0x67, 0x5a, 0x42, 0x32, 0x51, 0x55, 0x4b, 0x43, 0x55, 0x72, 0x61, 0x54, 0x55, 0x59, 0x4a, 0x79, 277 0x4f, 0x51, 0x67, 0x69, 0x61, 0x68, 0x34, 0x50, 0x62, 0x78, 0x74, 0x73, 0x45, 0x31, 0x35,
256 0x59, 0x55, 0x45, 0x33, 0x42, 0x43, 0x47, 0x52, 0x4a, 0x31, 0x50, 0x67, 0x4a, 0x64, 0x66, 0x42, 0x4d, 0x66, 0x46, 0x6c, 0x4d, 0x37, 278 0x35, 0x49, 0x48, 0x6c, 0x51, 0x59, 0x67, 0x59, 0x73, 0x64, 0x68, 0x63, 0x45, 0x4b, 0x79,
257 0x64, 0x45, 0x67, 0x38, 0x58, 0x6a, 0x6c, 0x73, 0x48, 0x42, 0x78, 0x30, 0x4f, 0x52, 0x38, 0x41, 0x47, 0x77, 0x59, 0x4b, 0x61, 0x44, 279 0x70, 0x31, 0x48, 0x77, 0x77, 0x33, 0x54, 0x67, 0x39, 0x37, 0x4c, 0x54, 0x52, 0x31, 0x59,
258 0x74, 0x53, 0x54, 0x78, 0x35, 0x75, 0x50, 0x44, 0x55, 0x4d, 0x4f, 0x41, 0x34, 0x4c, 0x4f, 0x78, 0x70, 0x32, 0x49, 0x79, 0x6c, 0x54, 280 0x44, 0x46, 0x30, 0x4c, 0x67, 0x70, 0x4b, 0x45, 0x57, 0x78, 0x4a, 0x4a, 0x51, 0x45, 0x36,
259 0x48, 0x6c, 0x39, 0x42, 0x44, 0x45, 0x73, 0x4b, 0x5a, 0x53, 0x68, 0x34, 0x5a, 0x30, 0x68, 0x5a, 0x4a, 0x6d, 0x30, 0x78, 0x64, 0x69, 281 0x50, 0x53, 0x49, 0x65, 0x62, 0x52, 0x68, 0x52, 0x65, 0x43, 0x31, 0x69, 0x4d, 0x55, 0x78,
260 0x4e, 0x77, 0x59, 0x57, 0x51, 0x37, 0x4f, 0x48, 0x6c, 0x6d, 0x64, 0x46, 0x4d, 0x73, 0x5a, 0x47, 0x52, 0x55, 0x41, 0x31, 0x52, 0x6c, 282 0x51, 0x51, 0x42, 0x64, 0x4c, 0x62, 0x79, 0x49, 0x41, 0x66, 0x32, 0x45, 0x71, 0x4e, 0x44,
261 0x52, 0x45, 0x77, 0x59, 0x54, 0x30, 0x67, 0x67, 0x54, 0x33, 0x49, 0x51, 0x50, 0x77, 0x78, 0x53, 0x4c, 0x51, 0x4d, 0x55, 0x41, 0x31, 283 0x34, 0x41, 0x58, 0x79, 0x39, 0x66, 0x4c, 0x78, 0x51, 0x71, 0x56, 0x53, 0x63, 0x66, 0x52,
262 0x46, 0x43, 0x45, 0x48, 0x64, 0x71, 0x4e, 0x41, 0x59, 0x79, 0x41, 0x33, 0x49, 0x55, 0x66, 0x41, 0x68, 0x64, 0x55, 0x68, 0x70, 0x69, 284 0x68, 0x38, 0x53, 0x52, 0x6c, 0x34, 0x65, 0x44, 0x48, 0x77, 0x34, 0x41, 0x57, 0x46, 0x6b,
263 0x66, 0x44, 0x34, 0x77, 0x66, 0x6c, 0x39, 0x2f, 0x56, 0x41, 0x39, 0x45, 0x53, 0x56, 0x31, 0x65, 0x45, 0x47, 0x6f, 0x47, 0x4b, 0x77, 285 0x64, 0x69, 0x4a, 0x75, 0x43, 0x43, 0x41, 0x34, 0x54, 0x33, 0x4e, 0x79, 0x56, 0x52, 0x4a,
264 0x5a, 0x54, 0x45, 0x44, 0x6b, 0x33, 0x4d, 0x6b, 0x70, 0x4f, 0x50, 0x53, 0x74, 0x6c, 0x4f, 0x44, 0x6b, 0x48, 0x63, 0x6c, 0x52, 0x6b, 286 0x43, 0x47, 0x56, 0x42, 0x68, 0x51, 0x33, 0x64, 0x39, 0x51, 0x53, 0x34, 0x31, 0x54, 0x7a,
265 0x54, 0x56, 0x5a, 0x71, 0x41, 0x79, 0x4a, 0x77, 0x65, 0x31, 0x39, 0x67, 0x43, 0x79, 0x6f, 0x4c, 0x61, 0x78, 0x42, 0x6b, 0x46, 0x41, 287 0x30, 0x78, 0x4b, 0x46, 0x68, 0x6e, 0x47, 0x77, 0x4e, 0x52, 0x49, 0x44, 0x49, 0x63, 0x43,
266 0x55, 0x69, 0x41, 0x48, 0x4e, 0x41, 0x49, 0x31, 0x74, 0x52, 0x48, 0x79, 0x73, 0x61, 0x58, 0x57, 0x6c, 0x36, 0x52, 0x67, 0x78, 0x66, 288 0x47, 0x34, 0x33, 0x64, 0x54, 0x64, 0x45, 0x54, 0x32, 0x67, 0x5a, 0x42, 0x32, 0x51, 0x55,
267 0x4d, 0x6b, 0x74, 0x4b, 0x4b, 0x46, 0x4a, 0x35, 0x57, 0x78, 0x4a, 0x43, 0x47, 0x41, 0x42, 0x64, 0x4a, 0x7a, 0x46, 0x54, 0x50, 0x45, 289 0x4b, 0x43, 0x55, 0x72, 0x61, 0x54, 0x55, 0x59, 0x4a, 0x79, 0x59, 0x55, 0x45, 0x33, 0x42,
268 0x77, 0x32, 0x54, 0x6a, 0x67, 0x2f, 0x63, 0x67, 0x4e, 0x78, 0x41, 0x6c, 0x73, 0x32, 0x57, 0x58, 0x39, 0x31, 0x62, 0x67, 0x68, 0x55, 290 0x43, 0x47, 0x52, 0x4a, 0x31, 0x50, 0x67, 0x4a, 0x64, 0x66, 0x42, 0x4d, 0x66, 0x46, 0x6c,
269 0x44, 0x54, 0x51, 0x63, 0x4e, 0x46, 0x64, 0x64, 0x61, 0x55, 0x67, 0x41, 0x4f, 0x77, 0x55, 0x48, 0x62, 0x69, 0x64, 0x6c, 0x62, 0x6b, 291 0x4d, 0x37, 0x64, 0x45, 0x67, 0x38, 0x58, 0x6a, 0x6c, 0x73, 0x48, 0x42, 0x78, 0x30, 0x4f,
270 0x41, 0x39, 0x4f, 0x6b, 0x39, 0x79, 0x58, 0x54, 0x6b, 0x57, 0x44, 0x32, 0x4d, 0x53, 0x45, 0x68, 0x55, 0x36, 0x63, 0x41, 0x31, 0x58, 292 0x52, 0x38, 0x41, 0x47, 0x77, 0x59, 0x4b, 0x61, 0x44, 0x74, 0x53, 0x54, 0x78, 0x35, 0x75,
271 0x47, 0x41, 0x31, 0x65, 0x50, 0x53, 0x4a, 0x6f, 0x61, 0x48, 0x78, 0x74, 0x54, 0x77, 0x78, 0x37, 0x43, 0x53, 0x31, 0x4b, 0x63, 0x79, 293 0x50, 0x44, 0x55, 0x4d, 0x4f, 0x41, 0x34, 0x4c, 0x4f, 0x78, 0x70, 0x32, 0x49, 0x79, 0x6c,
272 0x42, 0x48, 0x42, 0x31, 0x64, 0x31, 0x58, 0x56, 0x4e, 0x77, 0x4e, 0x43, 0x46, 0x41, 0x56, 0x31, 0x46, 0x65, 0x53, 0x55, 0x51, 0x41, 294 0x54, 0x48, 0x6c, 0x39, 0x42, 0x44, 0x45, 0x73, 0x4b, 0x5a, 0x53, 0x68, 0x34, 0x5a, 0x30,
273 0x56, 0x43, 0x63, 0x45, 0x61, 0x48, 0x35, 0x5a, 0x56, 0x6c, 0x68, 0x30, 0x46, 0x44, 0x77, 0x57, 0x4d, 0x30, 0x45, 0x57, 0x53, 0x79, 295 0x68, 0x5a, 0x4a, 0x6d, 0x30, 0x78, 0x64, 0x69, 0x4e, 0x77, 0x59, 0x57, 0x51, 0x37, 0x4f,
274 0x39, 0x4a, 0x4e, 0x77, 0x70, 0x55, 0x43, 0x41, 0x67, 0x66, 0x4f, 0x57, 0x64, 0x32, 0x4b, 0x43, 0x67, 0x48, 0x48, 0x57, 0x46, 0x48, 296 0x48, 0x6c, 0x6d, 0x64, 0x46, 0x4d, 0x73, 0x5a, 0x47, 0x52, 0x55, 0x41, 0x31, 0x52, 0x6c,
275 0x55, 0x55, 0x31, 0x31, 0x4a, 0x6c, 0x4a, 0x48, 0x52, 0x77, 0x78, 0x58, 0x57, 0x48, 0x51, 0x2b, 0x59, 0x6d, 0x78, 0x59, 0x4f, 0x6b, 297 0x52, 0x45, 0x77, 0x59, 0x54, 0x30, 0x67, 0x67, 0x54, 0x33, 0x49, 0x51, 0x50, 0x77, 0x78,
276 0x51, 0x65, 0x46, 0x69, 0x34, 0x68, 0x48, 0x48, 0x4e, 0x46, 0x5a, 0x33, 0x52, 0x50, 0x4d, 0x32, 0x59, 0x4f, 0x64, 0x47, 0x59, 0x6d, 298 0x53, 0x4c, 0x51, 0x4d, 0x55, 0x41, 0x31, 0x46, 0x43, 0x45, 0x48, 0x64, 0x71, 0x4e, 0x41,
277 0x48, 0x79, 0x34, 0x34, 0x52, 0x45, 0x42, 0x2b, 0x4b, 0x6c, 0x42, 0x53, 0x58, 0x6b, 0x4d, 0x42, 0x65, 0x6a, 0x68, 0x4a, 0x50, 0x46, 299 0x59, 0x79, 0x41, 0x33, 0x49, 0x55, 0x66, 0x41, 0x68, 0x64, 0x55, 0x68, 0x70, 0x69, 0x66,
278 0x56, 0x4e, 0x57, 0x6b, 0x51, 0x49, 0x4a, 0x6c, 0x6c, 0x4e, 0x52, 0x51, 0x74, 0x49, 0x43, 0x6a, 0x4e, 0x65, 0x53, 0x6b, 0x31, 0x31, 300 0x44, 0x34, 0x77, 0x66, 0x6c, 0x39, 0x2f, 0x56, 0x41, 0x39, 0x45, 0x53, 0x56, 0x31, 0x65,
279 0x46, 0x68, 0x64, 0x6a, 0x52, 0x67, 0x45, 0x71, 0x56, 0x58, 0x73, 0x50, 0x41, 0x6e, 0x4e, 0x71, 0x53, 0x33, 0x39, 0x31, 0x5a, 0x54, 301 0x45, 0x47, 0x6f, 0x47, 0x4b, 0x77, 0x5a, 0x54, 0x45, 0x44, 0x6b, 0x33, 0x4d, 0x6b, 0x70,
280 0x78, 0x4d, 0x4d, 0x7a, 0x6c, 0x73, 0x64, 0x41, 0x56, 0x67, 0x44, 0x33, 0x38, 0x74, 0x51, 0x55, 0x31, 0x4e, 0x52, 0x6e, 0x45, 0x4a, 302 0x4f, 0x50, 0x53, 0x74, 0x6c, 0x4f, 0x44, 0x6b, 0x48, 0x63, 0x6c, 0x52, 0x6b, 0x54, 0x56,
281 0x62, 0x30, 0x39, 0x67, 0x46, 0x51, 0x39, 0x47, 0x63, 0x32, 0x4e, 0x4d, 0x58, 0x6e, 0x51, 0x77, 0x44, 0x53, 0x68, 0x44, 0x43, 0x48, 303 0x5a, 0x71, 0x41, 0x79, 0x4a, 0x77, 0x65, 0x31, 0x39, 0x67, 0x43, 0x79, 0x6f, 0x4c, 0x61,
282 0x49, 0x79, 0x42, 0x43, 0x34, 0x78, 0x4b, 0x53, 0x64, 0x45, 0x62, 0x52, 0x4d, 0x58, 0x53, 0x41, 0x39, 0x4a, 0x55, 0x68, 0x41, 0x54, 304 0x78, 0x42, 0x6b, 0x46, 0x41, 0x55, 0x69, 0x41, 0x48, 0x4e, 0x41, 0x49, 0x31, 0x74, 0x52,
283 0x66, 0x78, 0x63, 0x57, 0x59, 0x6e, 0x6b, 0x31, 0x65, 0x44, 0x34, 0x42, 0x66, 0x43, 0x34, 0x50, 0x64, 0x6a, 0x35, 0x65, 0x55, 0x32, 305 0x48, 0x79, 0x73, 0x61, 0x58, 0x57, 0x6c, 0x36, 0x52, 0x67, 0x78, 0x66, 0x4d, 0x6b, 0x74,
284 0x78, 0x62, 0x58, 0x33, 0x77, 0x5a, 0x51, 0x51, 0x49, 0x76, 0x46, 0x32, 0x52, 0x42, 0x64, 0x52, 0x41, 0x45, 0x52, 0x33, 0x77, 0x39, 306 0x4b, 0x4b, 0x46, 0x4a, 0x35, 0x57, 0x78, 0x4a, 0x43, 0x47, 0x41, 0x42, 0x64, 0x4a, 0x7a,
285 0x53, 0x31, 0x49, 0x41, 0x45, 0x46, 0x31, 0x52, 0x54, 0x6e, 0x6f, 0x6e, 0x4a, 0x56, 0x56, 0x41, 0x45, 0x6a, 0x56, 0x67, 0x42, 0x52, 307 0x46, 0x54, 0x50, 0x45, 0x77, 0x32, 0x54, 0x6a, 0x67, 0x2f, 0x63, 0x67, 0x4e, 0x78, 0x41,
286 0x73, 0x30, 0x4c, 0x51, 0x52, 0x36, 0x61, 0x6d, 0x6b, 0x43, 0x65, 0x51, 0x4d, 0x36, 0x4c, 0x77, 0x59, 0x4b, 0x65, 0x58, 0x73, 0x53, 308 0x6c, 0x73, 0x32, 0x57, 0x58, 0x39, 0x31, 0x62, 0x67, 0x68, 0x55, 0x44, 0x54, 0x51, 0x63,
287 0x58, 0x58, 0x78, 0x53, 0x4b, 0x55, 0x64, 0x59, 0x45, 0x6e, 0x4d, 0x2f, 0x4a, 0x31, 0x59, 0x46, 0x44, 0x45, 0x67, 0x79, 0x57, 0x47, 309 0x4e, 0x46, 0x64, 0x64, 0x61, 0x55, 0x67, 0x41, 0x4f, 0x77, 0x55, 0x48, 0x62, 0x69, 0x64,
288 0x74, 0x58, 0x58, 0x41, 0x4e, 0x6b, 0x56, 0x68, 0x46, 0x53, 0x65, 0x6a, 0x41, 0x32, 0x4b, 0x52, 0x63, 0x37, 0x61, 0x48, 0x70, 0x38, 310 0x6c, 0x62, 0x6b, 0x41, 0x39, 0x4f, 0x6b, 0x39, 0x79, 0x58, 0x54, 0x6b, 0x57, 0x44, 0x32,
289 0x42, 0x57, 0x74, 0x72, 0x45, 0x32, 0x6f, 0x6b, 0x58, 0x47, 0x68, 0x43, 0x47, 0x44, 0x49, 0x44, 0x63, 0x32, 0x34, 0x45, 0x49, 0x53, 311 0x4d, 0x53, 0x45, 0x68, 0x55, 0x36, 0x63, 0x41, 0x31, 0x58, 0x47, 0x41, 0x31, 0x65, 0x50,
290 0x34, 0x42, 0x42, 0x47, 0x4e, 0x39, 0x52, 0x45, 0x45, 0x53, 0x4d, 0x51, 0x73, 0x56, 0x48, 0x33, 0x41, 0x41, 0x4c, 0x6d, 0x59, 0x55, 312 0x53, 0x4a, 0x6f, 0x61, 0x48, 0x78, 0x74, 0x54, 0x77, 0x78, 0x37, 0x43, 0x53, 0x31, 0x4b,
291 0x50, 0x48, 0x38, 0x72, 0x41, 0x42, 0x38, 0x4d, 0x4b, 0x46, 0x6b, 0x4b, 0x46, 0x6b, 0x6c, 0x61, 0x58, 0x47, 0x52, 0x6c, 0x53, 0x78, 313 0x63, 0x79, 0x42, 0x48, 0x42, 0x31, 0x64, 0x31, 0x58, 0x56, 0x4e, 0x77, 0x4e, 0x43, 0x46,
292 0x45, 0x70, 0x46, 0x54, 0x5a, 0x61, 0x5a, 0x52, 0x6c, 0x50, 0x59, 0x43, 0x4d, 0x36, 0x4f, 0x68, 0x4d, 0x6c, 0x41, 0x6e, 0x68, 0x4d, 314 0x41, 0x56, 0x31, 0x46, 0x65, 0x53, 0x55, 0x51, 0x41, 0x56, 0x43, 0x63, 0x45, 0x61, 0x48,
293 0x56, 0x41, 0x3d, 0x3d, 0x00}; 315 0x35, 0x5a, 0x56, 0x6c, 0x68, 0x30, 0x46, 0x44, 0x77, 0x57, 0x4d, 0x30, 0x45, 0x57, 0x53,
316 0x79, 0x39, 0x4a, 0x4e, 0x77, 0x70, 0x55, 0x43, 0x41, 0x67, 0x66, 0x4f, 0x57, 0x64, 0x32,
317 0x4b, 0x43, 0x67, 0x48, 0x48, 0x57, 0x46, 0x48, 0x55, 0x55, 0x31, 0x31, 0x4a, 0x6c, 0x4a,
318 0x48, 0x52, 0x77, 0x78, 0x58, 0x57, 0x48, 0x51, 0x2b, 0x59, 0x6d, 0x78, 0x59, 0x4f, 0x6b,
319 0x51, 0x65, 0x46, 0x69, 0x34, 0x68, 0x48, 0x48, 0x4e, 0x46, 0x5a, 0x33, 0x52, 0x50, 0x4d,
320 0x32, 0x59, 0x4f, 0x64, 0x47, 0x59, 0x6d, 0x48, 0x79, 0x34, 0x34, 0x52, 0x45, 0x42, 0x2b,
321 0x4b, 0x6c, 0x42, 0x53, 0x58, 0x6b, 0x4d, 0x42, 0x65, 0x6a, 0x68, 0x4a, 0x50, 0x46, 0x56,
322 0x4e, 0x57, 0x6b, 0x51, 0x49, 0x4a, 0x6c, 0x6c, 0x4e, 0x52, 0x51, 0x74, 0x49, 0x43, 0x6a,
323 0x4e, 0x65, 0x53, 0x6b, 0x31, 0x31, 0x46, 0x68, 0x64, 0x6a, 0x52, 0x67, 0x45, 0x71, 0x56,
324 0x58, 0x73, 0x50, 0x41, 0x6e, 0x4e, 0x71, 0x53, 0x33, 0x39, 0x31, 0x5a, 0x54, 0x78, 0x4d,
325 0x4d, 0x7a, 0x6c, 0x73, 0x64, 0x41, 0x56, 0x67, 0x44, 0x33, 0x38, 0x74, 0x51, 0x55, 0x31,
326 0x4e, 0x52, 0x6e, 0x45, 0x4a, 0x62, 0x30, 0x39, 0x67, 0x46, 0x51, 0x39, 0x47, 0x63, 0x32,
327 0x4e, 0x4d, 0x58, 0x6e, 0x51, 0x77, 0x44, 0x53, 0x68, 0x44, 0x43, 0x48, 0x49, 0x79, 0x42,
328 0x43, 0x34, 0x78, 0x4b, 0x53, 0x64, 0x45, 0x62, 0x52, 0x4d, 0x58, 0x53, 0x41, 0x39, 0x4a,
329 0x55, 0x68, 0x41, 0x54, 0x66, 0x78, 0x63, 0x57, 0x59, 0x6e, 0x6b, 0x31, 0x65, 0x44, 0x34,
330 0x42, 0x66, 0x43, 0x34, 0x50, 0x64, 0x6a, 0x35, 0x65, 0x55, 0x32, 0x78, 0x62, 0x58, 0x33,
331 0x77, 0x5a, 0x51, 0x51, 0x49, 0x76, 0x46, 0x32, 0x52, 0x42, 0x64, 0x52, 0x41, 0x45, 0x52,
332 0x33, 0x77, 0x39, 0x53, 0x31, 0x49, 0x41, 0x45, 0x46, 0x31, 0x52, 0x54, 0x6e, 0x6f, 0x6e,
333 0x4a, 0x56, 0x56, 0x41, 0x45, 0x6a, 0x56, 0x67, 0x42, 0x52, 0x73, 0x30, 0x4c, 0x51, 0x52,
334 0x36, 0x61, 0x6d, 0x6b, 0x43, 0x65, 0x51, 0x4d, 0x36, 0x4c, 0x77, 0x59, 0x4b, 0x65, 0x58,
335 0x73, 0x53, 0x58, 0x58, 0x78, 0x53, 0x4b, 0x55, 0x64, 0x59, 0x45, 0x6e, 0x4d, 0x2f, 0x4a,
336 0x31, 0x59, 0x46, 0x44, 0x45, 0x67, 0x79, 0x57, 0x47, 0x74, 0x58, 0x58, 0x41, 0x4e, 0x6b,
337 0x56, 0x68, 0x46, 0x53, 0x65, 0x6a, 0x41, 0x32, 0x4b, 0x52, 0x63, 0x37, 0x61, 0x48, 0x70,
338 0x38, 0x42, 0x57, 0x74, 0x72, 0x45, 0x32, 0x6f, 0x6b, 0x58, 0x47, 0x68, 0x43, 0x47, 0x44,
339 0x49, 0x44, 0x63, 0x32, 0x34, 0x45, 0x49, 0x53, 0x34, 0x42, 0x42, 0x47, 0x4e, 0x39, 0x52,
340 0x45, 0x45, 0x53, 0x4d, 0x51, 0x73, 0x56, 0x48, 0x33, 0x41, 0x41, 0x4c, 0x6d, 0x59, 0x55,
341 0x50, 0x48, 0x38, 0x72, 0x41, 0x42, 0x38, 0x4d, 0x4b, 0x46, 0x6b, 0x4b, 0x46, 0x6b, 0x6c,
342 0x61, 0x58, 0x47, 0x52, 0x6c, 0x53, 0x78, 0x45, 0x70, 0x46, 0x54, 0x5a, 0x61, 0x5a, 0x52,
343 0x6c, 0x50, 0x59, 0x43, 0x4d, 0x36, 0x4f, 0x68, 0x4d, 0x6c, 0x41, 0x6e, 0x68, 0x4d, 0x56,
344 0x41, 0x3d, 0x3d, 0x00};
294 char *b64_test; 345 char *b64_test;
295 346
296 plan_tests(1); 347 plan_tests(1);
diff --git a/lib/tests/test_cmd.c b/lib/tests/test_cmd.c
index c8867dfb..d51016cc 100644
--- a/lib/tests/test_cmd.c
+++ b/lib/tests/test_cmd.c
@@ -38,36 +38,35 @@ char *get_command(char *const *line) {
38} 38}
39 39
40int main(int argc, char **argv) { 40int main(int argc, char **argv) {
41 char **command_line = malloc(sizeof(char *) * COMMAND_LINE);
42 char *command = NULL;
43 char *perl;
44 output chld_out, chld_err;
45 int c;
46 int result = UNSET;
47
48 plan_tests(51); 41 plan_tests(51);
49 42
50 diag("Running plain echo command, set one"); 43 diag("Running plain echo command, set one");
51 44
52 /* ensure everything is empty before we begin */ 45 /* ensure everything is empty before we begin */
46
47 output chld_out;
53 memset(&chld_out, 0, sizeof(output)); 48 memset(&chld_out, 0, sizeof(output));
49 output chld_err;
54 memset(&chld_err, 0, sizeof(output)); 50 memset(&chld_err, 0, sizeof(output));
55 ok(chld_out.lines == 0, "(initialised) Checking stdout is reset"); 51 ok(chld_out.lines == 0, "(initialised) Checking stdout is reset");
56 ok(chld_err.lines == 0, "(initialised) Checking stderr is reset"); 52 ok(chld_err.lines == 0, "(initialised) Checking stderr is reset");
53 int result = UNSET;
57 ok(result == UNSET, "(initialised) Checking exit code is reset"); 54 ok(result == UNSET, "(initialised) Checking exit code is reset");
58 55
56 char **command_line = malloc(sizeof(char *) * COMMAND_LINE);
59 command_line[0] = strdup("/bin/echo"); 57 command_line[0] = strdup("/bin/echo");
60 command_line[1] = strdup("this"); 58 command_line[1] = strdup("this");
61 command_line[2] = strdup("is"); 59 command_line[2] = strdup("is");
62 command_line[3] = strdup("test"); 60 command_line[3] = strdup("test");
63 command_line[4] = strdup("one"); 61 command_line[4] = strdup("one");
64 62
65 command = get_command(command_line); 63 char *command = get_command(command_line);
66 64
67 result = cmd_run_array(command_line, &chld_out, &chld_err, 0); 65 result = cmd_run_array(command_line, &chld_out, &chld_err, 0);
68 ok(chld_out.lines == 1, "(array) Check for expected number of stdout lines"); 66 ok(chld_out.lines == 1, "(array) Check for expected number of stdout lines");
69 ok(chld_err.lines == 0, "(array) Check for expected number of stderr lines"); 67 ok(chld_err.lines == 0, "(array) Check for expected number of stderr lines");
70 ok(strcmp(chld_out.line[0], "this is test one") == 0, "(array) Check for expected stdout output"); 68 ok(strcmp(chld_out.line[0], "this is test one") == 0,
69 "(array) Check for expected stdout output");
71 ok(result == 0, "(array) Checking exit code"); 70 ok(result == 0, "(array) Checking exit code");
72 71
73 /* ensure everything is empty again */ 72 /* ensure everything is empty again */
@@ -82,7 +81,8 @@ int main(int argc, char **argv) {
82 81
83 ok(chld_out.lines == 1, "(string) Check for expected number of stdout lines"); 82 ok(chld_out.lines == 1, "(string) Check for expected number of stdout lines");
84 ok(chld_err.lines == 0, "(string) Check for expected number of stderr lines"); 83 ok(chld_err.lines == 0, "(string) Check for expected number of stderr lines");
85 ok(strcmp(chld_out.line[0], "this is test one") == 0, "(string) Check for expected stdout output"); 84 ok(strcmp(chld_out.line[0], "this is test one") == 0,
85 "(string) Check for expected stdout output");
86 ok(result == 0, "(string) Checking exit code"); 86 ok(result == 0, "(string) Checking exit code");
87 87
88 diag("Running plain echo command, set two"); 88 diag("Running plain echo command, set two");
@@ -104,7 +104,8 @@ int main(int argc, char **argv) {
104 result = cmd_run_array(command_line, &chld_out, &chld_err, 0); 104 result = cmd_run_array(command_line, &chld_out, &chld_err, 0);
105 ok(chld_out.lines == 1, "(array) Check for expected number of stdout lines"); 105 ok(chld_out.lines == 1, "(array) Check for expected number of stdout lines");
106 ok(chld_err.lines == 0, "(array) Check for expected number of stderr lines"); 106 ok(chld_err.lines == 0, "(array) Check for expected number of stderr lines");
107 ok(strcmp(chld_out.line[0], "this is test two") == 0, "(array) Check for expected stdout output"); 107 ok(strcmp(chld_out.line[0], "this is test two") == 0,
108 "(array) Check for expected stdout output");
108 ok(result == 0, "(array) Checking exit code"); 109 ok(result == 0, "(array) Checking exit code");
109 110
110 /* ensure everything is empty again */ 111 /* ensure everything is empty again */
@@ -119,7 +120,8 @@ int main(int argc, char **argv) {
119 120
120 ok(chld_out.lines == 1, "(string) Check for expected number of stdout lines"); 121 ok(chld_out.lines == 1, "(string) Check for expected number of stdout lines");
121 ok(chld_err.lines == 0, "(string) Check for expected number of stderr lines"); 122 ok(chld_err.lines == 0, "(string) Check for expected number of stderr lines");
122 ok(strcmp(chld_out.line[0], "this is test one") == 0, "(string) Check for expected stdout output"); 123 ok(strcmp(chld_out.line[0], "this is test one") == 0,
124 "(string) Check for expected stdout output");
123 ok(result == 0, "(string) Checking exit code"); 125 ok(result == 0, "(string) Checking exit code");
124 126
125 /* ensure everything is empty again */ 127 /* ensure everything is empty again */
@@ -130,7 +132,8 @@ int main(int argc, char **argv) {
130 ok(chld_err.lines == 0, "(initialised) Checking stderr is reset"); 132 ok(chld_err.lines == 0, "(initialised) Checking stderr is reset");
131 ok(result == UNSET, "(initialised) Checking exit code is reset"); 133 ok(result == UNSET, "(initialised) Checking exit code is reset");
132 134
133 /* Pass linefeeds via parameters through - those should be evaluated by echo to give multi line output */ 135 /* Pass linefeeds via parameters through - those should be evaluated by echo to give multi line
136 * output */
134 command_line[0] = strdup("/bin/echo"); 137 command_line[0] = strdup("/bin/echo");
135 command_line[1] = strdup("this is a test via echo\nline two\nit's line 3"); 138 command_line[1] = strdup("this is a test via echo\nline two\nit's line 3");
136 command_line[2] = strdup("and (note space between '3' and 'and') $$ will not get evaluated"); 139 command_line[2] = strdup("and (note space between '3' and 'and') $$ will not get evaluated");
@@ -138,9 +141,12 @@ int main(int argc, char **argv) {
138 result = cmd_run_array(command_line, &chld_out, &chld_err, 0); 141 result = cmd_run_array(command_line, &chld_out, &chld_err, 0);
139 ok(chld_out.lines == 3, "(array) Check for expected number of stdout lines"); 142 ok(chld_out.lines == 3, "(array) Check for expected number of stdout lines");
140 ok(chld_err.lines == 0, "(array) Check for expected number of stderr lines"); 143 ok(chld_err.lines == 0, "(array) Check for expected number of stderr lines");
141 ok(strcmp(chld_out.line[0], "this is a test via echo") == 0, "(array) Check line 1 for expected stdout output"); 144 ok(strcmp(chld_out.line[0], "this is a test via echo") == 0,
142 ok(strcmp(chld_out.line[1], "line two") == 0, "(array) Check line 2 for expected stdout output"); 145 "(array) Check line 1 for expected stdout output");
143 ok(strcmp(chld_out.line[2], "it's line 3 and (note space between '3' and 'and') $$ will not get evaluated") == 0, 146 ok(strcmp(chld_out.line[1], "line two") == 0,
147 "(array) Check line 2 for expected stdout output");
148 ok(strcmp(chld_out.line[2],
149 "it's line 3 and (note space between '3' and 'and') $$ will not get evaluated") == 0,
144 "(array) Check line 3 for expected stdout output"); 150 "(array) Check line 3 for expected stdout output");
145 ok(result == 0, "(array) Checking exit code"); 151 ok(result == 0, "(array) Checking exit code");
146 152
@@ -171,7 +177,8 @@ int main(int argc, char **argv) {
171 177
172 ok(chld_out.lines == 0, "/bin/sh returns no stdout when file is missing..."); 178 ok(chld_out.lines == 0, "/bin/sh returns no stdout when file is missing...");
173 ok(chld_err.lines == 1, "...but does give an error line"); 179 ok(chld_err.lines == 1, "...but does give an error line");
174 ok(strstr(chld_err.line[0], "non-existent-file") != NULL, "And missing filename is in error message"); 180 ok(strstr(chld_err.line[0], "non-existent-file") != NULL,
181 "And missing filename is in error message");
175 ok(result != 0, "Get non-zero return code from /bin/sh"); 182 ok(result != 0, "Get non-zero return code from /bin/sh");
176 183
177 /* ensure everything is empty again */ 184 /* ensure everything is empty again */
diff --git a/lib/tests/test_generic_output.c b/lib/tests/test_generic_output.c
index e67aefc9..e4a78bcd 100644
--- a/lib/tests/test_generic_output.c
+++ b/lib/tests/test_generic_output.c
@@ -110,7 +110,8 @@ void test_two_subchecks(void) {
110 sc1.output = "foobar"; 110 sc1.output = "foobar";
111 sc1 = mp_set_subcheck_state(sc1, STATE_WARNING); 111 sc1 = mp_set_subcheck_state(sc1, STATE_WARNING);
112 112
113 ok(mp_compute_subcheck_state(sc1) == STATE_WARNING, "Test subcheck state directly after setting it"); 113 ok(mp_compute_subcheck_state(sc1) == STATE_WARNING,
114 "Test subcheck state directly after setting it");
114 115
115 mp_perfdata pd1 = perfdata_init(); 116 mp_perfdata pd1 = perfdata_init();
116 117
@@ -129,7 +130,8 @@ void test_two_subchecks(void) {
129 130
130 mp_add_subcheck_to_subcheck(&sc1, sc2); 131 mp_add_subcheck_to_subcheck(&sc1, sc2);
131 132
132 ok(mp_compute_subcheck_state(sc1) == STATE_WARNING, "Test subcheck state after adding a subcheck"); 133 ok(mp_compute_subcheck_state(sc1) == STATE_WARNING,
134 "Test subcheck state after adding a subcheck");
133 135
134 mp_check check = mp_check_init(); 136 mp_check check = mp_check_init();
135 mp_add_subcheck_to_check(&check, sc1); 137 mp_add_subcheck_to_check(&check, sc1);
diff --git a/lib/tests/test_ini1.c b/lib/tests/test_ini1.c
index 246c1250..de983764 100644
--- a/lib/tests/test_ini1.c
+++ b/lib/tests/test_ini1.c
@@ -42,27 +42,30 @@ char *list2str(np_arg_list *optlst) {
42 free(optltmp); 42 free(optltmp);
43 } 43 }
44 /* Strip last whitespace */ 44 /* Strip last whitespace */
45 if (strlen(optstr) > 1) 45 if (strlen(optstr) > 1) {
46 optstr[strlen(optstr) - 1] = '\0'; 46 optstr[strlen(optstr) - 1] = '\0';
47 }
47 48
48 return optstr; 49 return optstr;
49} 50}
50 51
51int main(int argc, char **argv) { 52int main(int argc, char **argv) {
52 char *optstr = NULL;
53 53
54 plan_tests(12); 54 plan_tests(12);
55 55
56 optstr = list2str(np_get_defaults("section@./config-tiny.ini", "check_disk")); 56 char *optstr = list2str(np_get_defaults("section@./config-tiny.ini", "check_disk"));
57 ok(!strcmp(optstr, "--one=two --Foo=Bar --this=Your Mother! --blank"), "config-tiny.ini's section as expected"); 57 ok(!strcmp(optstr, "--one=two --Foo=Bar --this=Your Mother! --blank"),
58 "config-tiny.ini's section as expected");
58 my_free(optstr); 59 my_free(optstr);
59 60
60 optstr = list2str(np_get_defaults("@./config-tiny.ini", "section")); 61 optstr = list2str(np_get_defaults("@./config-tiny.ini", "section"));
61 ok(!strcmp(optstr, "--one=two --Foo=Bar --this=Your Mother! --blank"), "Used default section name, without specific"); 62 ok(!strcmp(optstr, "--one=two --Foo=Bar --this=Your Mother! --blank"),
63 "Used default section name, without specific");
62 my_free(optstr); 64 my_free(optstr);
63 65
64 optstr = list2str(np_get_defaults("Section Two@./config-tiny.ini", "check_disk")); 66 optstr = list2str(np_get_defaults("Section Two@./config-tiny.ini", "check_disk"));
65 ok(!strcmp(optstr, "--something else=blah --remove=whitespace"), "config-tiny.ini's Section Two as expected"); 67 ok(!strcmp(optstr, "--something else=blah --remove=whitespace"),
68 "config-tiny.ini's Section Two as expected");
66 my_free(optstr); 69 my_free(optstr);
67 70
68 optstr = list2str(np_get_defaults("/path/to/file.txt@./config-tiny.ini", "check_disk")); 71 optstr = list2str(np_get_defaults("/path/to/file.txt@./config-tiny.ini", "check_disk"));
@@ -70,15 +73,18 @@ int main(int argc, char **argv) {
70 my_free(optstr); 73 my_free(optstr);
71 74
72 optstr = list2str(np_get_defaults("section2@./config-tiny.ini", "check_disk")); 75 optstr = list2str(np_get_defaults("section2@./config-tiny.ini", "check_disk"));
73 ok(!strcmp(optstr, "--this=that"), "config-tiny.ini's section2 with whitespace before section name"); 76 ok(!strcmp(optstr, "--this=that"),
77 "config-tiny.ini's section2 with whitespace before section name");
74 my_free(optstr); 78 my_free(optstr);
75 79
76 optstr = list2str(np_get_defaults("section3@./config-tiny.ini", "check_disk")); 80 optstr = list2str(np_get_defaults("section3@./config-tiny.ini", "check_disk"));
77 ok(!strcmp(optstr, "--this=that"), "config-tiny.ini's section3 with whitespace after section name"); 81 ok(!strcmp(optstr, "--this=that"),
82 "config-tiny.ini's section3 with whitespace after section name");
78 my_free(optstr); 83 my_free(optstr);
79 84
80 optstr = list2str(np_get_defaults("check_mysql@./plugin.ini", "check_disk")); 85 optstr = list2str(np_get_defaults("check_mysql@./plugin.ini", "check_disk"));
81 ok(!strcmp(optstr, "--username=operator --password=secret"), "plugin.ini's check_mysql as expected"); 86 ok(!strcmp(optstr, "--username=operator --password=secret"),
87 "plugin.ini's check_mysql as expected");
82 my_free(optstr); 88 my_free(optstr);
83 89
84 optstr = list2str(np_get_defaults("check_mysql2@./plugin.ini", "check_disk")); 90 optstr = list2str(np_get_defaults("check_mysql2@./plugin.ini", "check_disk"));
@@ -90,29 +96,39 @@ int main(int argc, char **argv) {
90 my_free(optstr); 96 my_free(optstr);
91 97
92 optstr = list2str(np_get_defaults("Section Two@./config-dos.ini", "check_disk")); 98 optstr = list2str(np_get_defaults("Section Two@./config-dos.ini", "check_disk"));
93 ok(!strcmp(optstr, "--something else=blah --remove=whitespace"), "config-dos.ini's Section Two as expected"); 99 ok(!strcmp(optstr, "--something else=blah --remove=whitespace"),
100 "config-dos.ini's Section Two as expected");
94 my_free(optstr); 101 my_free(optstr);
95 102
96 optstr = list2str(np_get_defaults("section_twice@./plugin.ini", "check_disk")); 103 optstr = list2str(np_get_defaults("section_twice@./plugin.ini", "check_disk"));
97 ok(!strcmp(optstr, "--foo=bar --bar=foo"), "plugin.ini's section_twice defined twice in the file"); 104 ok(!strcmp(optstr, "--foo=bar --bar=foo"),
105 "plugin.ini's section_twice defined twice in the file");
98 my_free(optstr); 106 my_free(optstr);
99 107
100 optstr = list2str(np_get_defaults("tcp_long_lines@plugins.ini", "check_tcp")); 108 optstr = list2str(np_get_defaults("tcp_long_lines@plugins.ini", "check_tcp"));
101 ok(!strcmp(optstr, "--escape --send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar " 109 ok(!strcmp(optstr, "--escape --send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
110 "yadda Foo bar BAZ yadda yadda yadda Foo bar "
102 "BAZ yadda yadda yadda Foo bar BAZ yadda yadda " 111 "BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
103 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " 112 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar "
113 "BAZ yadda yadda yadda Foo bar BAZ yadda "
104 "yadda yadda Foo bar BAZ yadda yadda yadda Foo " 114 "yadda yadda Foo bar BAZ yadda yadda yadda Foo "
105 "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " 115 "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda "
116 "yadda yadda Foo bar BAZ yadda yadda "
106 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " 117 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ "
107 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda --expect=Foo bar BAZ yadda yadda " 118 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
119 "yadda --expect=Foo bar BAZ yadda yadda "
108 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " 120 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ "
109 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo " 121 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
122 "yadda Foo bar BAZ yadda yadda yadda Foo "
110 "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " 123 "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
111 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " 124 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar "
125 "BAZ yadda yadda yadda Foo bar BAZ yadda "
112 "yadda yadda Foo bar BAZ yadda yadda yadda Foo " 126 "yadda yadda Foo bar BAZ yadda yadda yadda Foo "
113 "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " 127 "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda "
128 "yadda yadda Foo bar BAZ yadda yadda "
114 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " 129 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ "
115 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo " 130 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
131 "yadda Foo bar BAZ yadda yadda yadda Foo "
116 "bar BAZ yadda yadda yadda --jail"), 132 "bar BAZ yadda yadda yadda --jail"),
117 "Long options"); 133 "Long options");
118 my_free(optstr); 134 my_free(optstr);
diff --git a/lib/tests/test_opts1.c b/lib/tests/test_opts1.c
index 984183d3..fa95c4d4 100644
--- a/lib/tests/test_opts1.c
+++ b/lib/tests/test_opts1.c
@@ -40,37 +40,40 @@ void my_free(int *argc, char **newargv, char **argv) {
40#else 40#else
41void my_free(int *argc, char **newargv, char **argv) { 41void my_free(int *argc, char **newargv, char **argv) {
42 /* Free stuff (and print while we're at it) */ 42 /* Free stuff (and print while we're at it) */
43 int i, freeflag = 1; 43 bool freeflag = true;
44 printf(" Arg(%i): ", *argc + 1); 44 printf(" Arg(%i): ", *argc + 1);
45 printf("'%s' ", newargv[0]); 45 printf("'%s' ", newargv[0]);
46 for (i = 1; i < *argc; i++) { 46
47 for (int i = 1; i < *argc; i++) {
47 printf("'%s' ", newargv[i]); 48 printf("'%s' ", newargv[i]);
48 /* Stop freeing when we get to the start of the original array */ 49 /* Stop freeing when we get to the start of the original array */
49 if (freeflag) { 50 if (freeflag) {
50 if (newargv[i] == argv[1]) 51 if (newargv[i] == argv[1]) {
51 freeflag = 0; 52 freeflag = false;
52 else 53 } else {
53 free(newargv[i]); 54 free(newargv[i]);
55 }
54 } 56 }
55 } 57 }
56 printf("\n"); 58 printf("\n");
57 /* Free only if it's a different array */ 59 /* Free only if it's a different array */
58 if (newargv != argv) 60 if (newargv != argv) {
59 free(newargv); 61 free(newargv);
62 }
60 *argc = 0; 63 *argc = 0;
61} 64}
62#endif 65#endif
63 66
64int array_diff(int i1, char **a1, int i2, char **a2) { 67int array_diff(int i1, char **a1, int i2, char **a2) {
65 int i;
66
67 if (i1 != i2) { 68 if (i1 != i2) {
68 printf(" Argument count doesn't match!\n"); 69 printf(" Argument count doesn't match!\n");
69 return 0; 70 return 0;
70 } 71 }
71 for (i = 0; i <= i1; i++) { 72
72 if (a1[i] == NULL && a2[i] == NULL) 73 for (int i = 0; i <= i1; i++) {
74 if (a1[i] == NULL && a2[i] == NULL) {
73 continue; 75 continue;
76 }
74 if (a1[i] == NULL || a2[i] == NULL) { 77 if (a1[i] == NULL || a2[i] == NULL) {
75 printf(" Argument # %i null in one array!\n", i); 78 printf(" Argument # %i null in one array!\n", i);
76 return 0; 79 return 0;
@@ -84,11 +87,10 @@ int array_diff(int i1, char **a1, int i2, char **a2) {
84} 87}
85 88
86int main(int argc, char **argv) { 89int main(int argc, char **argv) {
87 char **argv_new = NULL;
88 int i, argc_test;
89
90 plan_tests(5); 90 plan_tests(5);
91 91
92 char **argv_new = NULL;
93 int argc_test;
92 { 94 {
93 char *argv_test[] = {"prog_name", (char *)NULL}; 95 char *argv_test[] = {"prog_name", (char *)NULL};
94 argc_test = 1; 96 argc_test = 1;
@@ -110,27 +112,36 @@ int main(int argc, char **argv) {
110 { 112 {
111 char *argv_test[] = {"prog_name", "--extra-opts=@./config-opts.ini", (char *)NULL}; 113 char *argv_test[] = {"prog_name", "--extra-opts=@./config-opts.ini", (char *)NULL};
112 argc_test = 2; 114 argc_test = 2;
113 char *argv_known[] = {"prog_name", "--foo=Bar", "--this=Your Mother!", "--blank", (char *)NULL}; 115 char *argv_known[] = {"prog_name", "--foo=Bar", "--this=Your Mother!", "--blank",
116 (char *)NULL};
114 argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); 117 argv_new = np_extra_opts(&argc_test, argv_test, "check_disk");
115 ok(array_diff(argc_test, argv_new, 4, argv_known), "Only extra opts using default section"); 118 ok(array_diff(argc_test, argv_new, 4, argv_known), "Only extra opts using default section");
116 my_free(&argc_test, argv_new, argv_test); 119 my_free(&argc_test, argv_new, argv_test);
117 } 120 }
118 121
119 { 122 {
120 char *argv_test[] = {"prog_name", "--extra-opts=sect1@./config-opts.ini", "--extra-opts", "sect2@./config-opts.ini", (char *)NULL}; 123 char *argv_test[] = {"prog_name", "--extra-opts=sect1@./config-opts.ini", "--extra-opts",
124 "sect2@./config-opts.ini", (char *)NULL};
121 argc_test = 4; 125 argc_test = 4;
122 char *argv_known[] = {"prog_name", "--one=two", "--something else=oops", "--this=that", (char *)NULL}; 126 char *argv_known[] = {"prog_name", "--one=two", "--something else=oops", "--this=that",
127 (char *)NULL};
123 argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); 128 argv_new = np_extra_opts(&argc_test, argv_test, "check_disk");
124 ok(array_diff(argc_test, argv_new, 4, argv_known), "Only extra opts specified twice"); 129 ok(array_diff(argc_test, argv_new, 4, argv_known), "Only extra opts specified twice");
125 my_free(&argc_test, argv_new, argv_test); 130 my_free(&argc_test, argv_new, argv_test);
126 } 131 }
127 132
128 { 133 {
129 char *argv_test[] = {"prog_name", "--arg1=val1", "--extra-opts=@./config-opts.ini", "--extra-opts", "sect1@./config-opts.ini", 134 char *argv_test[] = {"prog_name",
130 "--arg2", (char *)NULL}; 135 "--arg1=val1",
136 "--extra-opts=@./config-opts.ini",
137 "--extra-opts",
138 "sect1@./config-opts.ini",
139 "--arg2",
140 (char *)NULL};
131 argc_test = 6; 141 argc_test = 6;
132 char *argv_known[] = {"prog_name", "--foo=Bar", "--this=Your Mother!", "--blank", "--one=two", 142 char *argv_known[] = {"prog_name", "--foo=Bar", "--this=Your Mother!",
133 "--arg1=val1", "--arg2", (char *)NULL}; 143 "--blank", "--one=two", "--arg1=val1",
144 "--arg2", (char *)NULL};
134 argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); 145 argv_new = np_extra_opts(&argc_test, argv_test, "check_disk");
135 ok(array_diff(argc_test, argv_new, 7, argv_known), "twice extra opts using two sections"); 146 ok(array_diff(argc_test, argv_new, 7, argv_known), "twice extra opts using two sections");
136 my_free(&argc_test, argv_new, argv_test); 147 my_free(&argc_test, argv_new, argv_test);
diff --git a/lib/tests/test_opts2.c b/lib/tests/test_opts2.c
index 23496617..3dd1b039 100644
--- a/lib/tests/test_opts2.c
+++ b/lib/tests/test_opts2.c
@@ -23,36 +23,39 @@
23 23
24void my_free(int *argc, char **newargv, char **argv) { 24void my_free(int *argc, char **newargv, char **argv) {
25 /* Free stuff (and print while we're at it) */ 25 /* Free stuff (and print while we're at it) */
26 int i, freeflag = 1; 26 bool freeflag = true;
27
27 printf(" Arg(%i): ", *argc + 1); 28 printf(" Arg(%i): ", *argc + 1);
28 printf("'%s' ", newargv[0]); 29 printf("'%s' ", newargv[0]);
29 for (i = 1; i < *argc; i++) { 30 for (int i = 1; i < *argc; i++) {
30 printf("'%s' ", newargv[i]); 31 printf("'%s' ", newargv[i]);
31 /* Stop freeing when we get to the start of the original array */ 32 /* Stop freeing when we get to the start of the original array */
32 if (freeflag) { 33 if (freeflag) {
33 if (newargv[i] == argv[1]) 34 if (newargv[i] == argv[1]) {
34 freeflag = 0; 35 freeflag = false;
35 else 36 } else {
36 free(newargv[i]); 37 free(newargv[i]);
38 }
37 } 39 }
38 } 40 }
39 printf("\n"); 41 printf("\n");
40 /* Free only if it's a different array */ 42 /* Free only if it's a different array */
41 if (newargv != argv) 43 if (newargv != argv) {
42 free(newargv); 44 free(newargv);
45 }
43 *argc = 0; 46 *argc = 0;
44} 47}
45 48
46int array_diff(int i1, char **a1, int i2, char **a2) { 49int array_diff(int i1, char **a1, int i2, char **a2) {
47 int i;
48
49 if (i1 != i2) { 50 if (i1 != i2) {
50 printf(" Argument count doesn't match!\n"); 51 printf(" Argument count doesn't match!\n");
51 return 0; 52 return 0;
52 } 53 }
53 for (i = 0; i <= i1; i++) { 54
54 if (a1[i] == NULL && a2[i] == NULL) 55 for (int i = 0; i <= i1; i++) {
56 if (a1[i] == NULL && a2[i] == NULL) {
55 continue; 57 continue;
58 }
56 if (a1[i] == NULL || a2[i] == NULL) { 59 if (a1[i] == NULL || a2[i] == NULL) {
57 printf(" Argument # %i null in one array!\n", i); 60 printf(" Argument # %i null in one array!\n", i);
58 return 0; 61 return 0;
@@ -66,11 +69,10 @@ int array_diff(int i1, char **a1, int i2, char **a2) {
66} 69}
67 70
68int main(int argc, char **argv) { 71int main(int argc, char **argv) {
69 char **argv_new = NULL;
70 int i, argc_test;
71
72 plan_tests(5); 72 plan_tests(5);
73 73
74 char **argv_new = NULL;
75 int argc_test;
74 { 76 {
75 char *argv_test[] = {"prog_name", "arg1", "--extra-opts", "--arg3", "val2", (char *)NULL}; 77 char *argv_test[] = {"prog_name", "arg1", "--extra-opts", "--arg3", "val2", (char *)NULL};
76 argc_test = 5; 78 argc_test = 5;
@@ -90,7 +92,8 @@ int main(int argc, char **argv) {
90 } 92 }
91 93
92 { 94 {
93 char *argv_test[] = {"prog_name", "arg1", "--extra-opts=section1", "--arg3", "val2", (char *)NULL}; 95 char *argv_test[] = {"prog_name", "arg1", "--extra-opts=section1",
96 "--arg3", "val2", (char *)NULL};
94 argc_test = 5; 97 argc_test = 5;
95 char *argv_known[] = {"prog_name", "--foobar=baz", "arg1", "--arg3", "val2", (char *)NULL}; 98 char *argv_known[] = {"prog_name", "--foobar=baz", "arg1", "--arg3", "val2", (char *)NULL};
96 argv_new = np_extra_opts(&argc_test, argv_test, "check_disk"); 99 argv_new = np_extra_opts(&argc_test, argv_test, "check_disk");
@@ -108,30 +111,39 @@ int main(int argc, char **argv) {
108 } 111 }
109 112
110 { 113 {
111 char *argv_test[] = {"check_tcp", "--extra-opts", "--extra-opts=tcp_long_lines", (char *)NULL}; 114 char *argv_test[] = {"check_tcp", "--extra-opts", "--extra-opts=tcp_long_lines",
115 (char *)NULL};
112 argc_test = 3; 116 argc_test = 3;
113 char *argv_known[] = { 117 char *argv_known[] = {"check_tcp",
114 "check_tcp", 118 "--timeout=10",
115 "--timeout=10", 119 "--escape",
116 "--escape", 120 "--send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda "
117 "--send=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " 121 "Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
118 "yadda Foo bar BAZ yadda " 122 "yadda Foo bar BAZ yadda "
119 "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " 123 "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
120 "yadda Foo bar BAZ " 124 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
121 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " 125 "yadda Foo bar BAZ "
122 "yadda yadda Foo bar " 126 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda "
123 "BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda", 127 "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda "
124 "--expect=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " 128 "yadda yadda Foo bar "
125 "yadda Foo bar BAZ yadda " 129 "BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ "
126 "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda " 130 "yadda yadda yadda Foo bar BAZ yadda yadda yadda",
127 "yadda Foo bar BAZ " 131 "--expect=Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
128 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda " 132 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
129 "yadda yadda Foo bar " 133 "yadda Foo bar BAZ yadda "
130 "BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ " 134 "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
131 "yadda yadda yadda Foo " 135 "yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda "
132 "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda", 136 "yadda Foo bar BAZ "
133 "--jail", 137 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda "
134 (char *)NULL}; 138 "yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ yadda "
139 "yadda yadda Foo bar "
140 "BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ "
141 "yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ "
142 "yadda yadda yadda Foo "
143 "bar BAZ yadda yadda yadda Foo bar BAZ yadda yadda yadda Foo bar BAZ "
144 "yadda yadda yadda Foo bar BAZ yadda yadda yadda",
145 "--jail",
146 (char *)NULL};
135 argv_new = np_extra_opts(&argc_test, argv_test, "check_tcp"); 147 argv_new = np_extra_opts(&argc_test, argv_test, "check_tcp");
136 ok(array_diff(argc_test, argv_new, 6, argv_known), "Long lines test"); 148 ok(array_diff(argc_test, argv_new, 6, argv_known), "Long lines test");
137 my_free(&argc_test, argv_new, argv_test); 149 my_free(&argc_test, argv_new, argv_test);
diff --git a/lib/tests/test_tcp.c b/lib/tests/test_tcp.c
index 1b3003e9..37c818c9 100644
--- a/lib/tests/test_tcp.c
+++ b/lib/tests/test_tcp.c
@@ -21,30 +21,38 @@
21#include "tap.h" 21#include "tap.h"
22 22
23int main(void) { 23int main(void) {
24 char **server_expect;
25 int server_expect_count = 3;
26
27 plan_tests(9); 24 plan_tests(9);
28 25
26 char **server_expect;
27 const int server_expect_count = 3;
29 server_expect = malloc(sizeof(char *) * server_expect_count); 28 server_expect = malloc(sizeof(char *) * server_expect_count);
30 29
31 server_expect[0] = strdup("AA"); 30 server_expect[0] = strdup("AA");
32 server_expect[1] = strdup("bb"); 31 server_expect[1] = strdup("bb");
33 server_expect[2] = strdup("CC"); 32 server_expect[2] = strdup("CC");
34 33
35 ok(np_expect_match("AA bb CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_SUCCESS, 34 ok(np_expect_match("AA bb CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) ==
35 NP_MATCH_SUCCESS,
36 "Test matching any string at the beginning (first expect string)"); 36 "Test matching any string at the beginning (first expect string)");
37 ok(np_expect_match("bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_SUCCESS, 37 ok(np_expect_match("bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) ==
38 NP_MATCH_SUCCESS,
38 "Test matching any string at the beginning (second expect string)"); 39 "Test matching any string at the beginning (second expect string)");
39 ok(np_expect_match("b", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_RETRY, 40 ok(np_expect_match("b", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_RETRY,
40 "Test matching any string at the beginning (substring match)"); 41 "Test matching any string at the beginning (substring match)");
41 ok(np_expect_match("XX bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_FAILURE, 42 ok(np_expect_match("XX bb AA CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) ==
43 NP_MATCH_FAILURE,
42 "Test with strings not matching at the beginning"); 44 "Test with strings not matching at the beginning");
43 ok(np_expect_match("XX CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) == NP_MATCH_FAILURE, "Test matching any string"); 45 ok(np_expect_match("XX CC XX", server_expect, server_expect_count, NP_MATCH_EXACT) ==
44 ok(np_expect_match("XX", server_expect, server_expect_count, 0) == NP_MATCH_RETRY, "Test not matching any string"); 46 NP_MATCH_FAILURE,
45 ok(np_expect_match("XX AA bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_SUCCESS, 47 "Test matching any string");
48 ok(np_expect_match("XX", server_expect, server_expect_count, 0) == NP_MATCH_RETRY,
49 "Test not matching any string");
50 ok(np_expect_match("XX AA bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) ==
51 NP_MATCH_SUCCESS,
46 "Test matching all strings"); 52 "Test matching all strings");
47 ok(np_expect_match("XX bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_RETRY, "Test not matching all strings"); 53 ok(np_expect_match("XX bb CC XX", server_expect, server_expect_count, NP_MATCH_ALL) ==
54 NP_MATCH_RETRY,
55 "Test not matching all strings");
48 ok(np_expect_match("XX XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_RETRY, 56 ok(np_expect_match("XX XX", server_expect, server_expect_count, NP_MATCH_ALL) == NP_MATCH_RETRY,
49 "Test not matching any string (testing all)"); 57 "Test not matching any string (testing all)");
50 58
diff --git a/lib/utils_base.c b/lib/utils_base.c
index e95eeaf0..28e6dc47 100644
--- a/lib/utils_base.c
+++ b/lib/utils_base.c
@@ -44,7 +44,7 @@
44 44
45monitoring_plugin *this_monitoring_plugin = NULL; 45monitoring_plugin *this_monitoring_plugin = NULL;
46 46
47int timeout_state = STATE_CRITICAL; 47mp_state_enum timeout_state = STATE_CRITICAL;
48unsigned int timeout_interval = DEFAULT_SOCKET_TIMEOUT; 48unsigned int timeout_interval = DEFAULT_SOCKET_TIMEOUT;
49 49
50bool _np_state_read_file(FILE *state_file); 50bool _np_state_read_file(FILE *state_file);
@@ -254,7 +254,7 @@ bool check_range(double value, range *my_range) {
254 yes = false; 254 yes = false;
255 } 255 }
256 256
257 if (!my_range->end_infinity&& !my_range->start_infinity) { 257 if (!my_range->end_infinity && !my_range->start_infinity) {
258 if ((my_range->start <= value) && (value <= my_range->end)) { 258 if ((my_range->start <= value) && (value <= my_range->end)) {
259 return no; 259 return no;
260 } 260 }
@@ -268,7 +268,7 @@ bool check_range(double value, range *my_range) {
268 return yes; 268 return yes;
269 } 269 }
270 270
271 if (my_range->start_infinity && !my_range->end_infinity ) { 271 if (my_range->start_infinity && !my_range->end_infinity) {
272 if (value <= my_range->end) { 272 if (value <= my_range->end) {
273 return no; 273 return no;
274 } 274 }
diff --git a/lib/utils_base.h b/lib/utils_base.h
index f31299c4..27884bf0 100644
--- a/lib/utils_base.h
+++ b/lib/utils_base.h
@@ -41,7 +41,7 @@ bool mp_check_range(mp_perfdata_value, mp_range);
41mp_state_enum get_status(double, thresholds *); 41mp_state_enum get_status(double, thresholds *);
42 42
43/* Handle timeouts */ 43/* Handle timeouts */
44extern int timeout_state; 44extern mp_state_enum timeout_state;
45extern unsigned int timeout_interval; 45extern unsigned int timeout_interval;
46 46
47/* All possible characters in a threshold range */ 47/* All possible characters in a threshold range */
diff --git a/lib/utils_cmd.c b/lib/utils_cmd.c
index 9b222409..35b83297 100644
--- a/lib/utils_cmd.c
+++ b/lib/utils_cmd.c
@@ -40,7 +40,6 @@
40 40
41/** includes **/ 41/** includes **/
42#include "common.h" 42#include "common.h"
43#include "utils.h"
44#include "utils_cmd.h" 43#include "utils_cmd.h"
45/* This variable must be global, since there's no way the caller 44/* This variable must be global, since there's no way the caller
46 * can forcibly slay a dead or ungainly running program otherwise. 45 * can forcibly slay a dead or ungainly running program otherwise.
@@ -62,16 +61,13 @@ static pid_t *_cmd_pids = NULL;
62# include <sys/wait.h> 61# include <sys/wait.h>
63#endif 62#endif
64 63
65/* used in _cmd_open to pass the environment to commands */
66extern char **environ;
67
68/** macros **/ 64/** macros **/
69#ifndef WEXITSTATUS 65#ifndef WEXITSTATUS
70# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) 66# define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
71#endif 67#endif
72 68
73#ifndef WIFEXITED 69#ifndef WIFEXITED
74# define WIFEXITED(stat_val) (((stat_val)&255) == 0) 70# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
75#endif 71#endif
76 72
77/* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */ 73/* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
@@ -80,14 +76,12 @@ extern char **environ;
80#endif 76#endif
81 77
82/** prototypes **/ 78/** prototypes **/
83static int _cmd_open(char *const *, int *, int *) __attribute__((__nonnull__(1, 2, 3))); 79static int _cmd_open(char *const *argv, int *pfd, int *pfderr)
84 80 __attribute__((__nonnull__(1, 2, 3)));
85static int _cmd_fetch_output(int, output *, int) __attribute__((__nonnull__(2)));
86 81
87static int _cmd_close(int); 82static int _cmd_fetch_output(int fileDescriptor, output *cmd_output, int flags) __attribute__((__nonnull__(2)));
88 83
89/* prototype imported from utils.h */ 84static int _cmd_close(int fileDescriptor);
90extern void die(int, const char *, ...) __attribute__((__noreturn__, __format__(__printf__, 2, 3)));
91 85
92/* this function is NOT async-safe. It is exported so multithreaded 86/* this function is NOT async-safe. It is exported so multithreaded
93 * plugins (or other apps) can call it prior to running any commands 87 * plugins (or other apps) can call it prior to running any commands
@@ -103,26 +97,29 @@ void cmd_init(void) {
103 maxfd = MAXFD_LIMIT; 97 maxfd = MAXFD_LIMIT;
104 } 98 }
105 99
106 if (!_cmd_pids) 100 if (!_cmd_pids) {
107 _cmd_pids = calloc(maxfd, sizeof(pid_t)); 101 _cmd_pids = calloc(maxfd, sizeof(pid_t));
102 }
108} 103}
109 104
110/* Start running a command, array style */ 105/* Start running a command, array style */
111static int _cmd_open(char *const *argv, int *pfd, int *pfderr) { 106static int _cmd_open(char *const *argv, int *pfd, int *pfderr) {
112 pid_t pid;
113#ifdef RLIMIT_CORE 107#ifdef RLIMIT_CORE
114 struct rlimit limit; 108 struct rlimit limit;
115#endif 109#endif
116 110
117 int i = 0; 111 int i = 0;
118 112
119 if (!_cmd_pids) 113 if (!_cmd_pids) {
120 CMD_INIT; 114 CMD_INIT;
115 }
121 116
122 setenv("LC_ALL", "C", 1); 117 setenv("LC_ALL", "C", 1);
123 118
124 if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0) 119 pid_t pid;
120 if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0) {
125 return -1; /* errno set by the failing function */ 121 return -1; /* errno set by the failing function */
122 }
126 123
127 /* child runs exceve() and _exit. */ 124 /* child runs exceve() and _exit. */
128 if (pid == 0) { 125 if (pid == 0) {
@@ -147,9 +144,11 @@ static int _cmd_open(char *const *argv, int *pfd, int *pfderr) {
147 * This is executed in a separate address space (pure child), 144 * This is executed in a separate address space (pure child),
148 * so we don't have to worry about async safety */ 145 * so we don't have to worry about async safety */
149 long maxfd = mp_open_max(); 146 long maxfd = mp_open_max();
150 for (i = 0; i < maxfd; i++) 147 for (i = 0; i < maxfd; i++) {
151 if (_cmd_pids[i] > 0) 148 if (_cmd_pids[i] > 0) {
152 close(i); 149 close(i);
150 }
151 }
153 152
154 execve(argv[0], argv, environ); 153 execve(argv[0], argv, environ);
155 _exit(STATE_UNKNOWN); 154 _exit(STATE_UNKNOWN);
@@ -166,87 +165,94 @@ static int _cmd_open(char *const *argv, int *pfd, int *pfderr) {
166 return pfd[0]; 165 return pfd[0];
167} 166}
168 167
169static int _cmd_close(int fd) { 168static int _cmd_close(int fileDescriptor) {
170 int status;
171 pid_t pid; 169 pid_t pid;
172 170
173 /* make sure the provided fd was opened */ 171 /* make sure the provided fd was opened */
174 long maxfd = mp_open_max(); 172 long maxfd = mp_open_max();
175 if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0) 173 if (fileDescriptor < 0 || fileDescriptor > maxfd || !_cmd_pids ||
174 (pid = _cmd_pids[fileDescriptor]) == 0) {
176 return -1; 175 return -1;
176 }
177 177
178 _cmd_pids[fd] = 0; 178 _cmd_pids[fileDescriptor] = 0;
179 if (close(fd) == -1) 179 if (close(fileDescriptor) == -1) {
180 return -1; 180 return -1;
181 }
181 182
182 /* EINTR is ok (sort of), everything else is bad */ 183 /* EINTR is ok (sort of), everything else is bad */
183 while (waitpid(pid, &status, 0) < 0) 184 int status;
184 if (errno != EINTR) 185 while (waitpid(pid, &status, 0) < 0) {
186 if (errno != EINTR) {
185 return -1; 187 return -1;
188 }
189 }
186 190
187 /* return child's termination status */ 191 /* return child's termination status */
188 return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1; 192 return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
189} 193}
190 194
191static int _cmd_fetch_output(int fd, output *op, int flags) { 195static int _cmd_fetch_output(int fileDescriptor, output *cmd_output, int flags) {
192 size_t len = 0, i = 0, lineno = 0;
193 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
194 char *buf = NULL;
195 int ret;
196 char tmpbuf[4096]; 196 char tmpbuf[4096];
197 197 cmd_output->buf = NULL;
198 op->buf = NULL; 198 cmd_output->buflen = 0;
199 op->buflen = 0; 199 ssize_t ret;
200 while ((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) { 200 while ((ret = read(fileDescriptor, tmpbuf, sizeof(tmpbuf))) > 0) {
201 len = (size_t)ret; 201 size_t len = (size_t)ret;
202 op->buf = realloc(op->buf, op->buflen + len + 1); 202 cmd_output->buf = realloc(cmd_output->buf, cmd_output->buflen + len + 1);
203 memcpy(op->buf + op->buflen, tmpbuf, len); 203 memcpy(cmd_output->buf + cmd_output->buflen, tmpbuf, len);
204 op->buflen += len; 204 cmd_output->buflen += len;
205 i++;
206 } 205 }
207 206
208 if (ret < 0) { 207 if (ret < 0) {
209 printf("read() returned %d: %s\n", ret, strerror(errno)); 208 printf("read() returned %zd: %s\n", ret, strerror(errno));
210 return ret; 209 return ret;
211 } 210 }
212 211
213 /* some plugins may want to keep output unbroken, and some commands 212 /* some plugins may want to keep output unbroken, and some commands
214 * will yield no output, so return here for those */ 213 * will yield no output, so return here for those */
215 if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen) 214 if (flags & CMD_NO_ARRAYS || !cmd_output->buf || !cmd_output->buflen) {
216 return op->buflen; 215 return cmd_output->buflen;
216 }
217 217
218 /* and some may want both */ 218 /* and some may want both */
219 char *buf = NULL;
219 if (flags & CMD_NO_ASSOC) { 220 if (flags & CMD_NO_ASSOC) {
220 buf = malloc(op->buflen); 221 buf = malloc(cmd_output->buflen);
221 memcpy(buf, op->buf, op->buflen); 222 memcpy(buf, cmd_output->buf, cmd_output->buflen);
222 } else 223 } else {
223 buf = op->buf; 224 buf = cmd_output->buf;
224 225 }
225 op->line = NULL; 226
226 op->lens = NULL; 227 cmd_output->line = NULL;
227 i = 0; 228 cmd_output->lens = NULL;
228 while (i < op->buflen) { 229 size_t i = 0;
230 size_t ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
231 size_t rsf = 6;
232 size_t lineno = 0;
233 while (i < cmd_output->buflen) {
229 /* make sure we have enough memory */ 234 /* make sure we have enough memory */
230 if (lineno >= ary_size) { 235 if (lineno >= ary_size) {
231 /* ary_size must never be zero */ 236 /* ary_size must never be zero */
232 do { 237 do {
233 ary_size = op->buflen >> --rsf; 238 ary_size = cmd_output->buflen >> --rsf;
234 } while (!ary_size); 239 } while (!ary_size);
235 240
236 op->line = realloc(op->line, ary_size * sizeof(char *)); 241 cmd_output->line = realloc(cmd_output->line, ary_size * sizeof(char *));
237 op->lens = realloc(op->lens, ary_size * sizeof(size_t)); 242 cmd_output->lens = realloc(cmd_output->lens, ary_size * sizeof(size_t));
238 } 243 }
239 244
240 /* set the pointer to the string */ 245 /* set the pointer to the string */
241 op->line[lineno] = &buf[i]; 246 cmd_output->line[lineno] = &buf[i];
242 247
243 /* hop to next newline or end of buffer */ 248 /* hop to next newline or end of buffer */
244 while (buf[i] != '\n' && i < op->buflen) 249 while (buf[i] != '\n' && i < cmd_output->buflen) {
245 i++; 250 i++;
251 }
246 buf[i] = '\0'; 252 buf[i] = '\0';
247 253
248 /* calculate the string length using pointer difference */ 254 /* calculate the string length using pointer difference */
249 op->lens[lineno] = (size_t)&buf[i] - (size_t)op->line[lineno]; 255 cmd_output->lens[lineno] = (size_t)&buf[i] - (size_t)cmd_output->line[lineno];
250 256
251 lineno++; 257 lineno++;
252 i++; 258 i++;
@@ -256,41 +262,42 @@ static int _cmd_fetch_output(int fd, output *op, int flags) {
256} 262}
257 263
258int cmd_run(const char *cmdstring, output *out, output *err, int flags) { 264int cmd_run(const char *cmdstring, output *out, output *err, int flags) {
259 int i = 0, argc; 265 if (cmdstring == NULL) {
260 size_t cmdlen;
261 char **argv = NULL;
262 char *cmd = NULL;
263 char *str = NULL;
264
265 if (cmdstring == NULL)
266 return -1; 266 return -1;
267 }
267 268
268 /* initialize the structs */ 269 /* initialize the structs */
269 if (out) 270 if (out) {
270 memset(out, 0, sizeof(output)); 271 memset(out, 0, sizeof(output));
271 if (err) 272 }
273 if (err) {
272 memset(err, 0, sizeof(output)); 274 memset(err, 0, sizeof(output));
275 }
273 276
274 /* make copy of command string so strtok() doesn't silently modify it */ 277 /* make copy of command string so strtok() doesn't silently modify it */
275 /* (the calling program may want to access it later) */ 278 /* (the calling program may want to access it later) */
276 cmdlen = strlen(cmdstring); 279 size_t cmdlen = strlen(cmdstring);
277 if ((cmd = malloc(cmdlen + 1)) == NULL) 280 char *cmd = NULL;
281 if ((cmd = malloc(cmdlen + 1)) == NULL) {
278 return -1; 282 return -1;
283 }
279 memcpy(cmd, cmdstring, cmdlen); 284 memcpy(cmd, cmdstring, cmdlen);
280 cmd[cmdlen] = '\0'; 285 cmd[cmdlen] = '\0';
281 286
282 /* This is not a shell, so we don't handle "???" */ 287 /* This is not a shell, so we don't handle "???" */
283 if (strstr(cmdstring, "\"")) 288 if (strstr(cmdstring, "\"")) {
284 return -1; 289 return -1;
290 }
285 291
286 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */ 292 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
287 if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) 293 if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) {
288 return -1; 294 return -1;
295 }
289 296
290 /* each arg must be whitespace-separated, so args can be a maximum 297 /* each arg must be whitespace-separated, so args can be a maximum
291 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */ 298 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
292 argc = (cmdlen >> 1) + 2; 299 int argc = (cmdlen >> 1) + 2;
293 argv = calloc((size_t)argc, sizeof(char *)); 300 char **argv = calloc((size_t)argc, sizeof(char *));
294 301
295 if (argv == NULL) { 302 if (argv == NULL) {
296 printf("%s\n", _("Could not malloc argv array in popen()")); 303 printf("%s\n", _("Could not malloc argv array in popen()"));
@@ -298,14 +305,16 @@ int cmd_run(const char *cmdstring, output *out, output *err, int flags) {
298 } 305 }
299 306
300 /* get command arguments (stupidly, but fairly quickly) */ 307 /* get command arguments (stupidly, but fairly quickly) */
308 int i = 0;
301 while (cmd) { 309 while (cmd) {
302 str = cmd; 310 char *str = cmd;
303 str += strspn(str, " \t\r\n"); /* trim any leading whitespace */ 311 str += strspn(str, " \t\r\n"); /* trim any leading whitespace */
304 312
305 if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */ 313 if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */
306 str++; 314 str++;
307 if (!strstr(str, "'")) 315 if (!strstr(str, "'")) {
308 return -1; /* balanced? */ 316 return -1; /* balanced? */
317 }
309 cmd = 1 + strstr(str, "'"); 318 cmd = 1 + strstr(str, "'");
310 str[strcspn(str, "'")] = 0; 319 str[strcspn(str, "'")] = 0;
311 } else { 320 } else {
@@ -317,8 +326,9 @@ int cmd_run(const char *cmdstring, output *out, output *err, int flags) {
317 } 326 }
318 } 327 }
319 328
320 if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) 329 if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) {
321 cmd = NULL; 330 cmd = NULL;
331 }
322 332
323 argv[i++] = str; 333 argv[i++] = str;
324 } 334 }
@@ -327,53 +337,65 @@ int cmd_run(const char *cmdstring, output *out, output *err, int flags) {
327} 337}
328 338
329int cmd_run_array(char *const *argv, output *out, output *err, int flags) { 339int cmd_run_array(char *const *argv, output *out, output *err, int flags) {
330 int fd, pfd_out[2], pfd_err[2];
331
332 /* initialize the structs */ 340 /* initialize the structs */
333 if (out) 341 if (out) {
334 memset(out, 0, sizeof(output)); 342 memset(out, 0, sizeof(output));
335 if (err) 343 }
344 if (err) {
336 memset(err, 0, sizeof(output)); 345 memset(err, 0, sizeof(output));
346 }
337 347
338 if ((fd = _cmd_open(argv, pfd_out, pfd_err)) == -1) 348 int fd;
349 int pfd_out[2];
350 int pfd_err[2];
351 if ((fd = _cmd_open(argv, pfd_out, pfd_err)) == -1) {
339 die(STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]); 352 die(STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
353 }
340 354
341 if (out) 355 if (out) {
342 out->lines = _cmd_fetch_output(pfd_out[0], out, flags); 356 out->lines = _cmd_fetch_output(pfd_out[0], out, flags);
343 if (err) 357 }
358 if (err) {
344 err->lines = _cmd_fetch_output(pfd_err[0], err, flags); 359 err->lines = _cmd_fetch_output(pfd_err[0], err, flags);
360 }
345 361
346 return _cmd_close(fd); 362 return _cmd_close(fd);
347} 363}
348 364
349int cmd_file_read(const char *filename, output *out, int flags) { 365int cmd_file_read(const char *filename, output *out, int flags) {
350 int fd; 366 int fd;
351 if (out) 367 if (out) {
352 memset(out, 0, sizeof(output)); 368 memset(out, 0, sizeof(output));
369 }
353 370
354 if ((fd = open(filename, O_RDONLY)) == -1) { 371 if ((fd = open(filename, O_RDONLY)) == -1) {
355 die(STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno)); 372 die(STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno));
356 } 373 }
357 374
358 if (out) 375 if (out) {
359 out->lines = _cmd_fetch_output(fd, out, flags); 376 out->lines = _cmd_fetch_output(fd, out, flags);
377 }
360 378
361 if (close(fd) == -1) 379 if (close(fd) == -1) {
362 die(STATE_UNKNOWN, _("Error closing %s: %s"), filename, strerror(errno)); 380 die(STATE_UNKNOWN, _("Error closing %s: %s"), filename, strerror(errno));
381 }
363 382
364 return 0; 383 return 0;
365} 384}
366 385
367void timeout_alarm_handler(int signo) { 386void timeout_alarm_handler(int signo) {
368 if (signo == SIGALRM) { 387 if (signo == SIGALRM) {
369 printf(_("%s - Plugin timed out after %d seconds\n"), state_text(timeout_state), timeout_interval); 388 printf(_("%s - Plugin timed out after %d seconds\n"), state_text(timeout_state),
389 timeout_interval);
370 390
371 long maxfd = mp_open_max(); 391 long maxfd = mp_open_max();
372 if (_cmd_pids) 392 if (_cmd_pids) {
373 for (long int i = 0; i < maxfd; i++) { 393 for (long int i = 0; i < maxfd; i++) {
374 if (_cmd_pids[i] != 0) 394 if (_cmd_pids[i] != 0) {
375 kill(_cmd_pids[i], SIGKILL); 395 kill(_cmd_pids[i], SIGKILL);
396 }
376 } 397 }
398 }
377 399
378 exit(timeout_state); 400 exit(timeout_state);
379 } 401 }
diff --git a/lib/utils_cmd.h b/lib/utils_cmd.h
index 728ece23..3672cdc9 100644
--- a/lib/utils_cmd.h
+++ b/lib/utils_cmd.h
@@ -5,17 +5,17 @@
5 * Header file for Monitoring Plugins utils_cmd.c 5 * Header file for Monitoring Plugins utils_cmd.c
6 * 6 *
7 */ 7 */
8#include "../config.h"
9#include <stddef.h>
8 10
9/** types **/ 11/** types **/
10struct output { 12typedef struct {
11 char *buf; /* output buffer */ 13 char *buf; /* output buffer */
12 size_t buflen; /* output buffer content length */ 14 size_t buflen; /* output buffer content length */
13 char **line; /* array of lines (points to buf) */ 15 char **line; /* array of lines (points to buf) */
14 size_t *lens; /* string lengths */ 16 size_t *lens; /* string lengths */
15 size_t lines; /* lines of output */ 17 size_t lines; /* lines of output */
16}; 18} output;
17
18typedef struct output output;
19 19
20/** prototypes **/ 20/** prototypes **/
21int cmd_run(const char *, output *, output *, int); 21int cmd_run(const char *, output *, output *, int);
diff --git a/lib/utils_tcp.c b/lib/utils_tcp.c
index daae1d54..a82d5a3f 100644
--- a/lib/utils_tcp.c
+++ b/lib/utils_tcp.c
@@ -26,28 +26,35 @@
26 * 26 *
27 *****************************************************************************/ 27 *****************************************************************************/
28 28
29#include "common.h" 29#include "../config.h"
30#include "utils_tcp.h" 30#include "utils_tcp.h"
31#include <stdio.h>
32#include <string.h>
31 33
32#define VERBOSE(message) \ 34#define VERBOSE(message) \
33 do { \ 35 do { \
34 if (flags & NP_MATCH_VERBOSE) \ 36 if (flags & NP_MATCH_VERBOSE) \
35 puts(message); \ 37 puts(message); \
36 } while (0) 38 } while (0)
37 39
38enum np_match_result np_expect_match(char *status, char **server_expect, int expect_count, int flags) { 40enum np_match_result np_expect_match(char *status, char **server_expect, int expect_count,
39 int i, match = 0, partial = 0; 41 int flags) {
40 42 int match = 0;
41 for (i = 0; i < expect_count; i++) { 43 int partial = 0;
42 if (flags & NP_MATCH_VERBOSE) 44 for (int i = 0; i < expect_count; i++) {
43 printf("looking for [%s] %s [%s]\n", server_expect[i], (flags & NP_MATCH_EXACT) ? "in beginning of" : "anywhere in", status); 45 if (flags & NP_MATCH_VERBOSE) {
46 printf("looking for [%s] %s [%s]\n", server_expect[i],
47 (flags & NP_MATCH_EXACT) ? "in beginning of" : "anywhere in", status);
48 }
44 49
45 if (flags & NP_MATCH_EXACT) { 50 if (flags & NP_MATCH_EXACT) {
46 if (strncmp(status, server_expect[i], strlen(server_expect[i])) == 0) { 51 if (strncmp(status, server_expect[i], strlen(server_expect[i])) == 0) {
47 VERBOSE("found it"); 52 VERBOSE("found it");
48 match++; 53 match++;
49 continue; 54 continue;
50 } else if (strncmp(status, server_expect[i], strlen(status)) == 0) { 55 }
56
57 if (strncmp(status, server_expect[i], strlen(status)) == 0) {
51 VERBOSE("found a substring"); 58 VERBOSE("found a substring");
52 partial++; 59 partial++;
53 continue; 60 continue;
@@ -60,10 +67,12 @@ enum np_match_result np_expect_match(char *status, char **server_expect, int exp
60 VERBOSE("couldn't find it"); 67 VERBOSE("couldn't find it");
61 } 68 }
62 69
63 if ((flags & NP_MATCH_ALL && match == expect_count) || (!(flags & NP_MATCH_ALL) && match >= 1)) 70 if ((flags & NP_MATCH_ALL && match == expect_count) ||
71 (!(flags & NP_MATCH_ALL) && match >= 1)) {
64 return NP_MATCH_SUCCESS; 72 return NP_MATCH_SUCCESS;
65 else if (partial > 0 || !(flags & NP_MATCH_EXACT)) 73 }
74 if (partial > 0 || !(flags & NP_MATCH_EXACT)) {
66 return NP_MATCH_RETRY; 75 return NP_MATCH_RETRY;
67 else 76 }
68 return NP_MATCH_FAILURE; 77 return NP_MATCH_FAILURE;
69} 78}
diff --git a/lib/utils_tcp.h b/lib/utils_tcp.h
index a7d83c59..e5cdbb82 100644
--- a/lib/utils_tcp.h
+++ b/lib/utils_tcp.h
@@ -17,4 +17,5 @@ enum np_match_result {
17 NP_MATCH_RETRY 17 NP_MATCH_RETRY
18}; 18};
19 19
20enum np_match_result np_expect_match(char *status, char **server_expect, int server_expect_count, int flags); 20enum np_match_result np_expect_match(char *status, char **server_expect, int server_expect_count,
21 int flags);
diff --git a/plugins-root/check_dhcp.c b/plugins-root/check_dhcp.c
index daed9cb0..9a96547f 100644
--- a/plugins-root/check_dhcp.c
+++ b/plugins-root/check_dhcp.c
@@ -127,17 +127,17 @@ static long mac_addr_dlpi(const char *, int, u_char *);
127#define MAX_DHCP_OPTIONS_LENGTH 312 127#define MAX_DHCP_OPTIONS_LENGTH 312
128 128
129typedef struct dhcp_packet_struct { 129typedef struct dhcp_packet_struct {
130 uint8_t op; /* packet type */ 130 uint8_t op; /* packet type */
131 uint8_t htype; /* type of hardware address for this machine (Ethernet, etc) */ 131 uint8_t htype; /* type of hardware address for this machine (Ethernet, etc) */
132 uint8_t hlen; /* length of hardware address (of this machine) */ 132 uint8_t hlen; /* length of hardware address (of this machine) */
133 uint8_t hops; /* hops */ 133 uint8_t hops; /* hops */
134 uint32_t xid; /* random transaction id number - chosen by this machine */ 134 uint32_t xid; /* random transaction id number - chosen by this machine */
135 uint16_t secs; /* seconds used in timing */ 135 uint16_t secs; /* seconds used in timing */
136 uint16_t flags; /* flags */ 136 uint16_t flags; /* flags */
137 struct in_addr ciaddr; /* IP address of this machine (if we already have one) */ 137 struct in_addr ciaddr; /* IP address of this machine (if we already have one) */
138 struct in_addr yiaddr; /* IP address of this machine (offered by the DHCP server) */ 138 struct in_addr yiaddr; /* IP address of this machine (offered by the DHCP server) */
139 struct in_addr siaddr; /* IP address of next server */ 139 struct in_addr siaddr; /* IP address of next server */
140 struct in_addr giaddr; /* IP address of DHCP relay */ 140 struct in_addr giaddr; /* IP address of DHCP relay */
141 unsigned char chaddr[MAX_DHCP_CHADDR_LENGTH]; /* hardware address of this machine */ 141 unsigned char chaddr[MAX_DHCP_CHADDR_LENGTH]; /* hardware address of this machine */
142 char sname[MAX_DHCP_SNAME_LENGTH]; /* name of DHCP server */ 142 char sname[MAX_DHCP_SNAME_LENGTH]; /* name of DHCP server */
143 char file[MAX_DHCP_FILE_LENGTH]; /* boot file name (used for diskless booting?) */ 143 char file[MAX_DHCP_FILE_LENGTH]; /* boot file name (used for diskless booting?) */
@@ -199,7 +199,8 @@ static void print_help(void);
199static void resolve_host(const char * /*in*/, struct in_addr * /*out*/); 199static void resolve_host(const char * /*in*/, struct in_addr * /*out*/);
200static unsigned char *mac_aton(const char * /*string*/); 200static unsigned char *mac_aton(const char * /*string*/);
201static void print_hardware_address(const unsigned char * /*address*/); 201static void print_hardware_address(const unsigned char * /*address*/);
202static int get_hardware_address(int /*sock*/, char * /*interface_name*/, unsigned char *client_hardware_address); 202static int get_hardware_address(int /*sock*/, char * /*interface_name*/,
203 unsigned char *client_hardware_address);
203 204
204typedef struct get_ip_address_wrapper { 205typedef struct get_ip_address_wrapper {
205 int error; 206 int error;
@@ -211,32 +212,40 @@ typedef struct send_dhcp_discover_wrapper {
211 int error; 212 int error;
212 uint32_t packet_xid; 213 uint32_t packet_xid;
213} send_dhcp_discover_wrapper; 214} send_dhcp_discover_wrapper;
214static send_dhcp_discover_wrapper send_dhcp_discover(int socket, bool unicast, struct in_addr dhcp_ip, struct in_addr requested_address, 215static send_dhcp_discover_wrapper
215 bool request_specific_address, struct in_addr my_ip, 216send_dhcp_discover(int socket, bool unicast, struct in_addr dhcp_ip,
216 unsigned char *client_hardware_address); 217 struct in_addr requested_address, bool request_specific_address,
218 struct in_addr my_ip, unsigned char *client_hardware_address);
217typedef struct get_dhcp_offer_wrapper { 219typedef struct get_dhcp_offer_wrapper {
218 int error; 220 int error;
219 int valid_responses; 221 int valid_responses;
220 dhcp_offer *dhcp_offer_list; 222 dhcp_offer *dhcp_offer_list;
221} get_dhcp_offer_wrapper; 223} get_dhcp_offer_wrapper;
222static get_dhcp_offer_wrapper get_dhcp_offer(int /*sock*/, int dhcpoffer_timeout, uint32_t packet_xid, dhcp_offer *dhcp_offer_list, 224static get_dhcp_offer_wrapper get_dhcp_offer(int /*sock*/, int dhcpoffer_timeout,
225 uint32_t packet_xid, dhcp_offer *dhcp_offer_list,
223 const unsigned char *client_hardware_address); 226 const unsigned char *client_hardware_address);
224 227
225static mp_subcheck get_results(bool exclusive, int requested_servers, struct in_addr requested_address, bool request_specific_address, 228static mp_subcheck get_results(bool exclusive, int requested_servers,
226 requested_server *requested_server_list, int valid_responses, dhcp_offer *dhcp_offer_list); 229 struct in_addr requested_address, bool request_specific_address,
230 requested_server *requested_server_list, int valid_responses,
231 dhcp_offer *dhcp_offer_list);
227 232
228typedef struct add_dhcp_offer_wrapper { 233typedef struct add_dhcp_offer_wrapper {
229 int error; 234 int error;
230 dhcp_offer *dhcp_offer_list; 235 dhcp_offer *dhcp_offer_list;
231} add_dhcp_offer_wrapper; 236} add_dhcp_offer_wrapper;
232static add_dhcp_offer_wrapper add_dhcp_offer(struct in_addr /*source*/, dhcp_packet * /*offer_packet*/, dhcp_offer *dhcp_offer_list); 237static add_dhcp_offer_wrapper add_dhcp_offer(struct in_addr /*source*/,
238 dhcp_packet * /*offer_packet*/,
239 dhcp_offer *dhcp_offer_list);
233static int free_dhcp_offer_list(dhcp_offer *dhcp_offer_list); 240static int free_dhcp_offer_list(dhcp_offer *dhcp_offer_list);
234static int free_requested_server_list(requested_server *requested_server_list); 241static int free_requested_server_list(requested_server *requested_server_list);
235 242
236static int create_dhcp_socket(bool /*unicast*/, char *network_interface_name); 243static int create_dhcp_socket(bool /*unicast*/, char *network_interface_name);
237static int close_dhcp_socket(int /*sock*/); 244static int close_dhcp_socket(int /*sock*/);
238static int send_dhcp_packet(void * /*buffer*/, int /*buffer_size*/, int /*sock*/, struct sockaddr_in * /*dest*/); 245static int send_dhcp_packet(void * /*buffer*/, int /*buffer_size*/, int /*sock*/,
239static int receive_dhcp_packet(void * /*buffer*/, int /*buffer_size*/, int /*sock*/, int /*timeout*/, struct sockaddr_in * /*address*/); 246 struct sockaddr_in * /*dest*/);
247static int receive_dhcp_packet(void * /*buffer*/, int /*buffer_size*/, int /*sock*/,
248 int /*timeout*/, struct sockaddr_in * /*address*/);
240 249
241int main(int argc, char **argv) { 250int main(int argc, char **argv) {
242 setlocale(LC_ALL, ""); 251 setlocale(LC_ALL, "");
@@ -271,7 +280,8 @@ int main(int argc, char **argv) {
271 struct in_addr my_ip = {0}; 280 struct in_addr my_ip = {0};
272 281
273 if (config.unicast_mode) { /* get IP address of client machine */ 282 if (config.unicast_mode) { /* get IP address of client machine */
274 get_ip_address_wrapper tmp_get_ip = get_ip_address(dhcp_socket, config.network_interface_name); 283 get_ip_address_wrapper tmp_get_ip =
284 get_ip_address(dhcp_socket, config.network_interface_name);
275 if (tmp_get_ip.error == OK) { 285 if (tmp_get_ip.error == OK) {
276 my_ip = tmp_get_ip.my_ip; 286 my_ip = tmp_get_ip.my_ip;
277 } else { 287 } else {
@@ -281,8 +291,9 @@ int main(int argc, char **argv) {
281 } 291 }
282 292
283 /* send DHCPDISCOVER packet */ 293 /* send DHCPDISCOVER packet */
284 send_dhcp_discover_wrapper disco_res = send_dhcp_discover(dhcp_socket, config.unicast_mode, config.dhcp_ip, config.requested_address, 294 send_dhcp_discover_wrapper disco_res = send_dhcp_discover(
285 config.request_specific_address, my_ip, client_hardware_address); 295 dhcp_socket, config.unicast_mode, config.dhcp_ip, config.requested_address,
296 config.request_specific_address, my_ip, client_hardware_address);
286 297
287 if (disco_res.error != OK) { 298 if (disco_res.error != OK) {
288 // DO something? 299 // DO something?
@@ -290,8 +301,8 @@ int main(int argc, char **argv) {
290 } 301 }
291 302
292 /* wait for a DHCPOFFER packet */ 303 /* wait for a DHCPOFFER packet */
293 get_dhcp_offer_wrapper offer_res = 304 get_dhcp_offer_wrapper offer_res = get_dhcp_offer(
294 get_dhcp_offer(dhcp_socket, config.dhcpoffer_timeout, disco_res.packet_xid, NULL, client_hardware_address); 305 dhcp_socket, config.dhcpoffer_timeout, disco_res.packet_xid, NULL, client_hardware_address);
295 306
296 int valid_responses = 0; 307 int valid_responses = 0;
297 dhcp_offer *dhcp_offer_list = NULL; 308 dhcp_offer *dhcp_offer_list = NULL;
@@ -308,8 +319,10 @@ int main(int argc, char **argv) {
308 mp_check overall = mp_check_init(); 319 mp_check overall = mp_check_init();
309 320
310 /* determine state/plugin output to return */ 321 /* determine state/plugin output to return */
311 mp_subcheck sc_res = get_results(config.exclusive_mode, config.num_of_requested_servers, config.requested_address, 322 mp_subcheck sc_res =
312 config.request_specific_address, config.requested_server_list, valid_responses, dhcp_offer_list); 323 get_results(config.exclusive_mode, config.num_of_requested_servers,
324 config.requested_address, config.request_specific_address,
325 config.requested_server_list, valid_responses, dhcp_offer_list);
313 mp_add_subcheck_to_check(&overall, sc_res); 326 mp_add_subcheck_to_check(&overall, sc_res);
314 /* free allocated memory */ 327 /* free allocated memory */
315 free_dhcp_offer_list(dhcp_offer_list); 328 free_dhcp_offer_list(dhcp_offer_list);
@@ -357,17 +370,20 @@ int get_hardware_address(int sock, char *interface_name, unsigned char *client_h
357 } 370 }
358 371
359 if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { 372 if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
360 printf(_("Error: Couldn't get hardware address from %s. sysctl 1 error - %s.\n"), interface_name, strerror(errno)); 373 printf(_("Error: Couldn't get hardware address from %s. sysctl 1 error - %s.\n"),
374 interface_name, strerror(errno));
361 exit(STATE_UNKNOWN); 375 exit(STATE_UNKNOWN);
362 } 376 }
363 377
364 if ((buf = malloc(len)) == NULL) { 378 if ((buf = malloc(len)) == NULL) {
365 printf(_("Error: Couldn't get hardware address from interface %s. malloc error - %s.\n"), interface_name, strerror(errno)); 379 printf(_("Error: Couldn't get hardware address from interface %s. malloc error - %s.\n"),
380 interface_name, strerror(errno));
366 exit(4); 381 exit(4);
367 } 382 }
368 383
369 if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { 384 if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
370 printf(_("Error: Couldn't get hardware address from %s. sysctl 2 error - %s.\n"), interface_name, strerror(errno)); 385 printf(_("Error: Couldn't get hardware address from %s. sysctl 2 error - %s.\n"),
386 interface_name, strerror(errno));
371 exit(STATE_UNKNOWN); 387 exit(STATE_UNKNOWN);
372 } 388 }
373 389
@@ -398,12 +414,16 @@ int get_hardware_address(int sock, char *interface_name, unsigned char *client_h
398 unit = atoi(p); 414 unit = atoi(p);
399 strncat(dev, interface_name, 6); 415 strncat(dev, interface_name, 6);
400 } else { 416 } else {
401 printf(_("Error: can't find unit number in interface_name (%s) - expecting TypeNumber eg lnc0.\n"), interface_name); 417 printf(_("Error: can't find unit number in interface_name (%s) - expecting TypeNumber eg "
418 "lnc0.\n"),
419 interface_name);
402 exit(STATE_UNKNOWN); 420 exit(STATE_UNKNOWN);
403 } 421 }
404 stat = mac_addr_dlpi(dev, unit, client_hardware_address); 422 stat = mac_addr_dlpi(dev, unit, client_hardware_address);
405 if (stat != 0) { 423 if (stat != 0) {
406 printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit); 424 printf(
425 _("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"),
426 dev, unit);
407 exit(STATE_UNKNOWN); 427 exit(STATE_UNKNOWN);
408 } 428 }
409 429
@@ -415,7 +435,9 @@ int get_hardware_address(int sock, char *interface_name, unsigned char *client_h
415 435
416 stat = mac_addr_dlpi(dev, unit, client_hardware_address); 436 stat = mac_addr_dlpi(dev, unit, client_hardware_address);
417 if (stat != 0) { 437 if (stat != 0) {
418 printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit); 438 printf(
439 _("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"),
440 dev, unit);
419 exit(STATE_UNKNOWN); 441 exit(STATE_UNKNOWN);
420 } 442 }
421 /* Kompf 2000-2003 */ 443 /* Kompf 2000-2003 */
@@ -463,8 +485,10 @@ get_ip_address_wrapper get_ip_address(int sock, char *interface_name) {
463} 485}
464 486
465/* sends a DHCPDISCOVER broadcast message in an attempt to find DHCP servers */ 487/* sends a DHCPDISCOVER broadcast message in an attempt to find DHCP servers */
466static send_dhcp_discover_wrapper send_dhcp_discover(int sock, bool unicast, struct in_addr dhcp_ip, struct in_addr requested_address, 488static send_dhcp_discover_wrapper send_dhcp_discover(int sock, bool unicast, struct in_addr dhcp_ip,
467 bool request_specific_address, struct in_addr my_ip, 489 struct in_addr requested_address,
490 bool request_specific_address,
491 struct in_addr my_ip,
468 unsigned char *client_hardware_address) { 492 unsigned char *client_hardware_address) {
469 dhcp_packet discover_packet = {0}; 493 dhcp_packet discover_packet = {0};
470 /* boot request flag (backward compatible with BOOTP servers) */ 494 /* boot request flag (backward compatible with BOOTP servers) */
@@ -506,8 +530,9 @@ static send_dhcp_discover_wrapper send_dhcp_discover(int sock, bool unicast, str
506 530
507 unsigned short opts = 4; 531 unsigned short opts = 4;
508 /* DHCP message type is embedded in options field */ 532 /* DHCP message type is embedded in options field */
509 discover_packet.options[opts++] = DHCP_OPTION_MESSAGE_TYPE; /* DHCP message type option identifier */ 533 discover_packet.options[opts++] =
510 discover_packet.options[opts++] = '\x01'; /* DHCP message option length in bytes */ 534 DHCP_OPTION_MESSAGE_TYPE; /* DHCP message type option identifier */
535 discover_packet.options[opts++] = '\x01'; /* DHCP message option length in bytes */
511 discover_packet.options[opts++] = DHCPDISCOVER; 536 discover_packet.options[opts++] = DHCPDISCOVER;
512 537
513 /* the IP address we're requesting */ 538 /* the IP address we're requesting */
@@ -535,8 +560,10 @@ static send_dhcp_discover_wrapper send_dhcp_discover(int sock, bool unicast, str
535 }; 560 };
536 561
537 if (verbose) { 562 if (verbose) {
538 printf(_("DHCPDISCOVER to %s port %d\n"), inet_ntoa(sockaddr_broadcast.sin_addr), ntohs(sockaddr_broadcast.sin_port)); 563 printf(_("DHCPDISCOVER to %s port %d\n"), inet_ntoa(sockaddr_broadcast.sin_addr),
539 printf("DHCPDISCOVER XID: %u (0x%X)\n", ntohl(discover_packet.xid), ntohl(discover_packet.xid)); 564 ntohs(sockaddr_broadcast.sin_port));
565 printf("DHCPDISCOVER XID: %u (0x%X)\n", ntohl(discover_packet.xid),
566 ntohl(discover_packet.xid));
540 printf("DHCDISCOVER ciaddr: %s\n", inet_ntoa(discover_packet.ciaddr)); 567 printf("DHCDISCOVER ciaddr: %s\n", inet_ntoa(discover_packet.ciaddr));
541 printf("DHCDISCOVER yiaddr: %s\n", inet_ntoa(discover_packet.yiaddr)); 568 printf("DHCDISCOVER yiaddr: %s\n", inet_ntoa(discover_packet.yiaddr));
542 printf("DHCDISCOVER siaddr: %s\n", inet_ntoa(discover_packet.siaddr)); 569 printf("DHCDISCOVER siaddr: %s\n", inet_ntoa(discover_packet.siaddr));
@@ -554,7 +581,8 @@ static send_dhcp_discover_wrapper send_dhcp_discover(int sock, bool unicast, str
554} 581}
555 582
556/* waits for a DHCPOFFER message from one or more DHCP servers */ 583/* waits for a DHCPOFFER message from one or more DHCP servers */
557get_dhcp_offer_wrapper get_dhcp_offer(int sock, int dhcpoffer_timeout, uint32_t packet_xid, dhcp_offer *dhcp_offer_list, 584get_dhcp_offer_wrapper get_dhcp_offer(int sock, int dhcpoffer_timeout, uint32_t packet_xid,
585 dhcp_offer *dhcp_offer_list,
558 const unsigned char *client_hardware_address) { 586 const unsigned char *client_hardware_address) {
559 time_t start_time; 587 time_t start_time;
560 time(&start_time); 588 time(&start_time);
@@ -578,7 +606,8 @@ get_dhcp_offer_wrapper get_dhcp_offer(int sock, int dhcpoffer_timeout, uint32_t
578 dhcp_packet offer_packet = {0}; 606 dhcp_packet offer_packet = {0};
579 607
580 result = OK; 608 result = OK;
581 result = receive_dhcp_packet(&offer_packet, sizeof(offer_packet), sock, dhcpoffer_timeout, &source); 609 result = receive_dhcp_packet(&offer_packet, sizeof(offer_packet), sock, dhcpoffer_timeout,
610 &source);
582 611
583 if (result != OK) { 612 if (result != OK) {
584 if (verbose) { 613 if (verbose) {
@@ -607,8 +636,9 @@ get_dhcp_offer_wrapper get_dhcp_offer(int sock, int dhcpoffer_timeout, uint32_t
607 /* check packet xid to see if its the same as the one we used in the discover packet */ 636 /* check packet xid to see if its the same as the one we used in the discover packet */
608 if (ntohl(offer_packet.xid) != packet_xid) { 637 if (ntohl(offer_packet.xid) != packet_xid) {
609 if (verbose) { 638 if (verbose) {
610 printf(_("DHCPOFFER XID (%u) did not match DHCPDISCOVER XID (%u) - ignoring packet\n"), ntohl(offer_packet.xid), 639 printf(
611 packet_xid); 640 _("DHCPOFFER XID (%u) did not match DHCPDISCOVER XID (%u) - ignoring packet\n"),
641 ntohl(offer_packet.xid), packet_xid);
612 } 642 }
613 643
614 continue; 644 continue;
@@ -648,7 +678,8 @@ get_dhcp_offer_wrapper get_dhcp_offer(int sock, int dhcpoffer_timeout, uint32_t
648 printf("DHCPOFFER giaddr: %s\n", inet_ntoa(offer_packet.giaddr)); 678 printf("DHCPOFFER giaddr: %s\n", inet_ntoa(offer_packet.giaddr));
649 } 679 }
650 680
651 add_dhcp_offer_wrapper add_res = add_dhcp_offer(source.sin_addr, &offer_packet, dhcp_offer_list); 681 add_dhcp_offer_wrapper add_res =
682 add_dhcp_offer(source.sin_addr, &offer_packet, dhcp_offer_list);
652 if (add_res.error != OK) { 683 if (add_res.error != OK) {
653 // TODO 684 // TODO
654 } else { 685 } else {
@@ -673,7 +704,8 @@ get_dhcp_offer_wrapper get_dhcp_offer(int sock, int dhcpoffer_timeout, uint32_t
673 704
674/* sends a DHCP packet */ 705/* sends a DHCP packet */
675int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in *dest) { 706int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in *dest) {
676 int result = sendto(sock, (char *)buffer, buffer_size, 0, (struct sockaddr *)dest, sizeof(*dest)); 707 int result =
708 sendto(sock, (char *)buffer, buffer_size, 0, (struct sockaddr *)dest, sizeof(*dest));
677 709
678 if (verbose) { 710 if (verbose) {
679 printf(_("send_dhcp_packet result: %d\n"), result); 711 printf(_("send_dhcp_packet result: %d\n"), result);
@@ -687,7 +719,8 @@ int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in
687} 719}
688 720
689/* receives a DHCP packet */ 721/* receives a DHCP packet */
690int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, struct sockaddr_in *address) { 722int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout,
723 struct sockaddr_in *address) {
691 /* wait for data to arrive (up time timeout) */ 724 /* wait for data to arrive (up time timeout) */
692 struct timeval timeout_val = { 725 struct timeval timeout_val = {
693 .tv_sec = timeout, 726 .tv_sec = timeout,
@@ -711,7 +744,8 @@ int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, st
711 744
712 struct sockaddr_in source_address = {0}; 745 struct sockaddr_in source_address = {0};
713 socklen_t address_size = sizeof(source_address); 746 socklen_t address_size = sizeof(source_address);
714 int recv_result = recvfrom(sock, (char *)buffer, buffer_size, 0, (struct sockaddr *)&source_address, &address_size); 747 int recv_result = recvfrom(sock, (char *)buffer, buffer_size, 0,
748 (struct sockaddr *)&source_address, &address_size);
715 if (verbose) { 749 if (verbose) {
716 printf("recv_result: %d\n", recv_result); 750 printf("recv_result: %d\n", recv_result);
717 } 751 }
@@ -775,7 +809,8 @@ int create_dhcp_socket(bool unicast, char *network_interface_name) {
775 strncpy(interface.ifr_ifrn.ifrn_name, network_interface_name, IFNAMSIZ - 1); 809 strncpy(interface.ifr_ifrn.ifrn_name, network_interface_name, IFNAMSIZ - 1);
776 interface.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = '\0'; 810 interface.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = '\0';
777 if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, (char *)&interface, sizeof(interface)) < 0) { 811 if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, (char *)&interface, sizeof(interface)) < 0) {
778 printf(_("Error: Could not bind socket to interface %s. Check your privileges...\n"), network_interface_name); 812 printf(_("Error: Could not bind socket to interface %s. Check your privileges...\n"),
813 network_interface_name);
779 exit(STATE_UNKNOWN); 814 exit(STATE_UNKNOWN);
780 } 815 }
781 816
@@ -786,7 +821,8 @@ int create_dhcp_socket(bool unicast, char *network_interface_name) {
786 821
787 /* bind the socket */ 822 /* bind the socket */
788 if (bind(sock, (struct sockaddr *)&myname, sizeof(myname)) < 0) { 823 if (bind(sock, (struct sockaddr *)&myname, sizeof(myname)) < 0) {
789 printf(_("Error: Could not bind to DHCP socket (port %d)! Check your privileges...\n"), DHCP_CLIENT_PORT); 824 printf(_("Error: Could not bind to DHCP socket (port %d)! Check your privileges...\n"),
825 DHCP_CLIENT_PORT);
790 exit(STATE_UNKNOWN); 826 exit(STATE_UNKNOWN);
791 } 827 }
792 828
@@ -800,7 +836,8 @@ int close_dhcp_socket(int sock) {
800} 836}
801 837
802/* adds a requested server address to list in memory */ 838/* adds a requested server address to list in memory */
803int add_requested_server(struct in_addr server_address, int *requested_servers, requested_server **requested_server_list) { 839int add_requested_server(struct in_addr server_address, int *requested_servers,
840 requested_server **requested_server_list) {
804 requested_server *new_server = (requested_server *)malloc(sizeof(requested_server)); 841 requested_server *new_server = (requested_server *)malloc(sizeof(requested_server));
805 if (new_server == NULL) { 842 if (new_server == NULL) {
806 return ERROR; 843 return ERROR;
@@ -822,7 +859,8 @@ int add_requested_server(struct in_addr server_address, int *requested_servers,
822} 859}
823 860
824/* adds a DHCP OFFER to list in memory */ 861/* adds a DHCP OFFER to list in memory */
825add_dhcp_offer_wrapper add_dhcp_offer(struct in_addr source, dhcp_packet *offer_packet, dhcp_offer *dhcp_offer_list) { 862add_dhcp_offer_wrapper add_dhcp_offer(struct in_addr source, dhcp_packet *offer_packet,
863 dhcp_offer *dhcp_offer_list) {
826 if (offer_packet == NULL) { 864 if (offer_packet == NULL) {
827 add_dhcp_offer_wrapper tmp = { 865 add_dhcp_offer_wrapper tmp = {
828 .error = ERROR, 866 .error = ERROR,
@@ -859,15 +897,18 @@ add_dhcp_offer_wrapper add_dhcp_offer(struct in_addr source, dhcp_packet *offer_
859 dhcp_lease_time = ntohl(dhcp_lease_time); 897 dhcp_lease_time = ntohl(dhcp_lease_time);
860 break; 898 break;
861 case DHCP_OPTION_RENEWAL_TIME: 899 case DHCP_OPTION_RENEWAL_TIME:
862 memcpy(&dhcp_renewal_time, &offer_packet->options[dchp_opt_idx], sizeof(dhcp_renewal_time)); 900 memcpy(&dhcp_renewal_time, &offer_packet->options[dchp_opt_idx],
901 sizeof(dhcp_renewal_time));
863 dhcp_renewal_time = ntohl(dhcp_renewal_time); 902 dhcp_renewal_time = ntohl(dhcp_renewal_time);
864 break; 903 break;
865 case DHCP_OPTION_REBINDING_TIME: 904 case DHCP_OPTION_REBINDING_TIME:
866 memcpy(&dhcp_rebinding_time, &offer_packet->options[dchp_opt_idx], sizeof(dhcp_rebinding_time)); 905 memcpy(&dhcp_rebinding_time, &offer_packet->options[dchp_opt_idx],
906 sizeof(dhcp_rebinding_time));
867 dhcp_rebinding_time = ntohl(dhcp_rebinding_time); 907 dhcp_rebinding_time = ntohl(dhcp_rebinding_time);
868 break; 908 break;
869 case DHCP_OPTION_SERVER_IDENTIFIER: 909 case DHCP_OPTION_SERVER_IDENTIFIER:
870 memcpy(&serv_ident.s_addr, &offer_packet->options[dchp_opt_idx], sizeof(serv_ident.s_addr)); 910 memcpy(&serv_ident.s_addr, &offer_packet->options[dchp_opt_idx],
911 sizeof(serv_ident.s_addr));
871 break; 912 break;
872 } 913 }
873 914
@@ -955,7 +996,8 @@ int free_dhcp_offer_list(dhcp_offer *dhcp_offer_list) {
955/* frees memory allocated to requested server list */ 996/* frees memory allocated to requested server list */
956int free_requested_server_list(requested_server *requested_server_list) { 997int free_requested_server_list(requested_server *requested_server_list) {
957 requested_server *next_server; 998 requested_server *next_server;
958 for (requested_server *this_server = requested_server_list; this_server != NULL; this_server = next_server) { 999 for (requested_server *this_server = requested_server_list; this_server != NULL;
1000 this_server = next_server) {
959 next_server = this_server->next; 1001 next_server = this_server->next;
960 free(this_server); 1002 free(this_server);
961 } 1003 }
@@ -964,8 +1006,10 @@ int free_requested_server_list(requested_server *requested_server_list) {
964} 1006}
965 1007
966/* gets state and plugin output to return */ 1008/* gets state and plugin output to return */
967mp_subcheck get_results(bool exclusive, const int requested_servers, const struct in_addr requested_address, bool request_specific_address, 1009mp_subcheck get_results(bool exclusive, const int requested_servers,
968 requested_server *requested_server_list, int valid_responses, dhcp_offer *dhcp_offer_list) { 1010 const struct in_addr requested_address, bool request_specific_address,
1011 requested_server *requested_server_list, int valid_responses,
1012 dhcp_offer *dhcp_offer_list) {
969 mp_subcheck sc_dhcp_results = mp_subcheck_init(); 1013 mp_subcheck sc_dhcp_results = mp_subcheck_init();
970 sc_dhcp_results = mp_set_subcheck_default_state(sc_dhcp_results, STATE_OK); 1014 sc_dhcp_results = mp_set_subcheck_default_state(sc_dhcp_results, STATE_OK);
971 1015
@@ -995,22 +1039,28 @@ mp_subcheck get_results(bool exclusive, const int requested_servers, const struc
995 /* checks responses from requested servers */ 1039 /* checks responses from requested servers */
996 int requested_responses = 0; 1040 int requested_responses = 0;
997 if (requested_servers > 0) { 1041 if (requested_servers > 0) {
998 for (requested_server *temp_server = requested_server_list; temp_server != NULL; temp_server = temp_server->next) { 1042 for (requested_server *temp_server = requested_server_list; temp_server != NULL;
999 for (dhcp_offer *temp_offer = dhcp_offer_list; temp_offer != NULL; temp_offer = temp_offer->next) { 1043 temp_server = temp_server->next) {
1044 for (dhcp_offer *temp_offer = dhcp_offer_list; temp_offer != NULL;
1045 temp_offer = temp_offer->next) {
1000 /* get max lease time we were offered */ 1046 /* get max lease time we were offered */
1001 if (temp_offer->lease_time > max_lease_time || temp_offer->lease_time == DHCP_INFINITE_TIME) { 1047 if (temp_offer->lease_time > max_lease_time ||
1048 temp_offer->lease_time == DHCP_INFINITE_TIME) {
1002 max_lease_time = temp_offer->lease_time; 1049 max_lease_time = temp_offer->lease_time;
1003 } 1050 }
1004 1051
1005 /* see if we got the address we requested */ 1052 /* see if we got the address we requested */
1006 if (!memcmp(&requested_address, &temp_offer->offered_address, sizeof(requested_address))) { 1053 if (!memcmp(&requested_address, &temp_offer->offered_address,
1054 sizeof(requested_address))) {
1007 received_requested_address = true; 1055 received_requested_address = true;
1008 } 1056 }
1009 1057
1010 /* see if the servers we wanted a response from, talked to us or not */ 1058 /* see if the servers we wanted a response from, talked to us or not */
1011 if (!memcmp(&temp_offer->server_address, &temp_server->server_address, sizeof(temp_server->server_address))) { 1059 if (!memcmp(&temp_offer->server_address, &temp_server->server_address,
1060 sizeof(temp_server->server_address))) {
1012 if (verbose) { 1061 if (verbose) {
1013 printf(_("DHCP Server Match: Offerer=%s"), inet_ntoa(temp_offer->server_address)); 1062 printf(_("DHCP Server Match: Offerer=%s"),
1063 inet_ntoa(temp_offer->server_address));
1014 printf(_(" Requested=%s"), inet_ntoa(temp_server->server_address)); 1064 printf(_(" Requested=%s"), inet_ntoa(temp_server->server_address));
1015 if (temp_server->answered) { 1065 if (temp_server->answered) {
1016 printf(_(" (duplicate)")); 1066 printf(_(" (duplicate)"));
@@ -1028,7 +1078,8 @@ mp_subcheck get_results(bool exclusive, const int requested_servers, const struc
1028 } 1078 }
1029 1079
1030 /* exclusive mode: check for undesired offers */ 1080 /* exclusive mode: check for undesired offers */
1031 for (dhcp_offer *temp_offer = dhcp_offer_list; temp_offer != NULL; temp_offer = temp_offer->next) { 1081 for (dhcp_offer *temp_offer = dhcp_offer_list; temp_offer != NULL;
1082 temp_offer = temp_offer->next) {
1032 if (!temp_offer->desired) { 1083 if (!temp_offer->desired) {
1033 undesired_offer = temp_offer; /* Checks only for the first undesired offer */ 1084 undesired_offer = temp_offer; /* Checks only for the first undesired offer */
1034 break; /* no further checks needed */ 1085 break; /* no further checks needed */
@@ -1036,7 +1087,8 @@ mp_subcheck get_results(bool exclusive, const int requested_servers, const struc
1036 } 1087 }
1037 1088
1038 mp_subcheck sc_rqust_srvs = mp_subcheck_init(); 1089 mp_subcheck sc_rqust_srvs = mp_subcheck_init();
1039 xasprintf(&sc_rqust_srvs.output, "%d of %d requested servers responded", requested_responses, requested_servers); 1090 xasprintf(&sc_rqust_srvs.output, "%d of %d requested servers responded",
1091 requested_responses, requested_servers);
1040 1092
1041 if (requested_responses == requested_servers) { 1093 if (requested_responses == requested_servers) {
1042 sc_rqust_srvs = mp_set_subcheck_state(sc_rqust_srvs, STATE_OK); 1094 sc_rqust_srvs = mp_set_subcheck_state(sc_rqust_srvs, STATE_OK);
@@ -1053,14 +1105,17 @@ mp_subcheck get_results(bool exclusive, const int requested_servers, const struc
1053 1105
1054 } else { 1106 } else {
1055 /* else check and see if we got our requested address from any server */ 1107 /* else check and see if we got our requested address from any server */
1056 for (dhcp_offer *temp_offer = dhcp_offer_list; temp_offer != NULL; temp_offer = temp_offer->next) { 1108 for (dhcp_offer *temp_offer = dhcp_offer_list; temp_offer != NULL;
1109 temp_offer = temp_offer->next) {
1057 /* get max lease time we were offered */ 1110 /* get max lease time we were offered */
1058 if (temp_offer->lease_time > max_lease_time || temp_offer->lease_time == DHCP_INFINITE_TIME) { 1111 if (temp_offer->lease_time > max_lease_time ||
1112 temp_offer->lease_time == DHCP_INFINITE_TIME) {
1059 max_lease_time = temp_offer->lease_time; 1113 max_lease_time = temp_offer->lease_time;
1060 } 1114 }
1061 1115
1062 /* see if we got the address we requested */ 1116 /* see if we got the address we requested */
1063 if (!memcmp(&requested_address, &temp_offer->offered_address, sizeof(requested_address))) { 1117 if (!memcmp(&requested_address, &temp_offer->offered_address,
1118 sizeof(requested_address))) {
1064 received_requested_address = true; 1119 received_requested_address = true;
1065 } 1120 }
1066 } 1121 }
@@ -1069,7 +1124,8 @@ mp_subcheck get_results(bool exclusive, const int requested_servers, const struc
1069 if (max_lease_time == DHCP_INFINITE_TIME) { 1124 if (max_lease_time == DHCP_INFINITE_TIME) {
1070 xasprintf(&sc_dhcp_results.output, "%s, max lease time = Infinity", sc_dhcp_results.output); 1125 xasprintf(&sc_dhcp_results.output, "%s, max lease time = Infinity", sc_dhcp_results.output);
1071 } else { 1126 } else {
1072 xasprintf(&sc_dhcp_results.output, "%s, max lease time = %" PRIu32 " seconds", sc_dhcp_results.output, max_lease_time); 1127 xasprintf(&sc_dhcp_results.output, "%s, max lease time = %" PRIu32 " seconds",
1128 sc_dhcp_results.output, max_lease_time);
1073 } 1129 }
1074 1130
1075 if (exclusive) { 1131 if (exclusive) {
@@ -1083,8 +1139,8 @@ mp_subcheck get_results(bool exclusive, const int requested_servers, const struc
1083 // Get the addresses for printout 1139 // Get the addresses for printout
1084 // 1.address of the sending server 1140 // 1.address of the sending server
1085 char server_address[INET_ADDRSTRLEN]; 1141 char server_address[INET_ADDRSTRLEN];
1086 const char *server_address_transformed = 1142 const char *server_address_transformed = inet_ntop(
1087 inet_ntop(AF_INET, &undesired_offer->server_address, server_address, sizeof(server_address)); 1143 AF_INET, &undesired_offer->server_address, server_address, sizeof(server_address));
1088 1144
1089 if (server_address != server_address_transformed) { 1145 if (server_address != server_address_transformed) {
1090 die(STATE_UNKNOWN, "inet_ntop failed"); 1146 die(STATE_UNKNOWN, "inet_ntop failed");
@@ -1093,13 +1149,15 @@ mp_subcheck get_results(bool exclusive, const int requested_servers, const struc
1093 // 2.address offered 1149 // 2.address offered
1094 char offered_address[INET_ADDRSTRLEN]; 1150 char offered_address[INET_ADDRSTRLEN];
1095 const char *offered_address_transformed = 1151 const char *offered_address_transformed =
1096 inet_ntop(AF_INET, &undesired_offer->offered_address, offered_address, sizeof(offered_address)); 1152 inet_ntop(AF_INET, &undesired_offer->offered_address, offered_address,
1153 sizeof(offered_address));
1097 1154
1098 if (offered_address != offered_address_transformed) { 1155 if (offered_address != offered_address_transformed) {
1099 die(STATE_UNKNOWN, "inet_ntop failed"); 1156 die(STATE_UNKNOWN, "inet_ntop failed");
1100 } 1157 }
1101 1158
1102 xasprintf(&sc_rogue_server.output, "Rogue DHCP Server detected! Server %s offered %s", server_address, offered_address); 1159 xasprintf(&sc_rogue_server.output, "Rogue DHCP Server detected! Server %s offered %s",
1160 server_address, offered_address);
1103 } else { 1161 } else {
1104 sc_rogue_server = mp_set_subcheck_state(sc_rogue_server, STATE_OK); 1162 sc_rogue_server = mp_set_subcheck_state(sc_rogue_server, STATE_OK);
1105 xasprintf(&sc_rogue_server.output, "No Rogue DHCP Server detected"); 1163 xasprintf(&sc_rogue_server.output, "No Rogue DHCP Server detected");
@@ -1112,10 +1170,12 @@ mp_subcheck get_results(bool exclusive, const int requested_servers, const struc
1112 1170
1113 if (received_requested_address) { 1171 if (received_requested_address) {
1114 sc_rqustd_addr = mp_set_subcheck_state(sc_rqustd_addr, STATE_OK); 1172 sc_rqustd_addr = mp_set_subcheck_state(sc_rqustd_addr, STATE_OK);
1115 xasprintf(&sc_rqustd_addr.output, "Requested address (%s) was offered", inet_ntoa(requested_address)); 1173 xasprintf(&sc_rqustd_addr.output, "Requested address (%s) was offered",
1174 inet_ntoa(requested_address));
1116 } else { 1175 } else {
1117 sc_rqustd_addr = mp_set_subcheck_state(sc_rqustd_addr, STATE_WARNING); 1176 sc_rqustd_addr = mp_set_subcheck_state(sc_rqustd_addr, STATE_WARNING);
1118 xasprintf(&sc_rqustd_addr.output, "Requested address (%s) was NOT offered", inet_ntoa(requested_address)); 1177 xasprintf(&sc_rqustd_addr.output, "Requested address (%s) was NOT offered",
1178 inet_ntoa(requested_address));
1119 } 1179 }
1120 1180
1121 mp_add_subcheck_to_subcheck(&sc_dhcp_results, sc_rqustd_addr); 1181 mp_add_subcheck_to_subcheck(&sc_dhcp_results, sc_rqustd_addr);
@@ -1138,18 +1198,19 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
1138 }; 1198 };
1139 1199
1140 int option_index = 0; 1200 int option_index = 0;
1141 static struct option long_options[] = {{"serverip", required_argument, 0, 's'}, 1201 static struct option long_options[] = {
1142 {"requestedip", required_argument, 0, 'r'}, 1202 {"serverip", required_argument, 0, 's'},
1143 {"timeout", required_argument, 0, 't'}, 1203 {"requestedip", required_argument, 0, 'r'},
1144 {"interface", required_argument, 0, 'i'}, 1204 {"timeout", required_argument, 0, 't'},
1145 {"mac", required_argument, 0, 'm'}, 1205 {"interface", required_argument, 0, 'i'},
1146 {"unicast", no_argument, 0, 'u'}, 1206 {"mac", required_argument, 0, 'm'},
1147 {"exclusive", no_argument, 0, 'x'}, 1207 {"unicast", no_argument, 0, 'u'},
1148 {"verbose", no_argument, 0, 'v'}, 1208 {"exclusive", no_argument, 0, 'x'},
1149 {"version", no_argument, 0, 'V'}, 1209 {"verbose", no_argument, 0, 'v'},
1150 {"help", no_argument, 0, 'h'}, 1210 {"version", no_argument, 0, 'V'},
1151 {"output-format", required_argument, 0, output_format_index}, 1211 {"help", no_argument, 0, 'h'},
1152 {0, 0, 0, 0}}; 1212 {"output-format", required_argument, 0, output_format_index},
1213 {0, 0, 0, 0}};
1153 1214
1154 check_dhcp_config config = check_dhcp_config_init(); 1215 check_dhcp_config config = check_dhcp_config_init();
1155 int option_char = 0; 1216 int option_char = 0;
@@ -1163,7 +1224,8 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
1163 switch (option_char) { 1224 switch (option_char) {
1164 case 's': /* DHCP server address */ 1225 case 's': /* DHCP server address */
1165 resolve_host(optarg, &config.dhcp_ip); 1226 resolve_host(optarg, &config.dhcp_ip);
1166 add_requested_server(config.dhcp_ip, &config.num_of_requested_servers, &config.requested_server_list); 1227 add_requested_server(config.dhcp_ip, &config.num_of_requested_servers,
1228 &config.requested_server_list);
1167 break; 1229 break;
1168 1230
1169 case 'r': /* address we are requested from DHCP servers */ 1231 case 'r': /* address we are requested from DHCP servers */
@@ -1187,7 +1249,8 @@ process_arguments_wrapper process_arguments(int argc, char **argv) {
1187 break; 1249 break;
1188 1250
1189 case 'i': /* interface name */ 1251 case 'i': /* interface name */
1190 strncpy(config.network_interface_name, optarg, sizeof(config.network_interface_name) - 1); 1252 strncpy(config.network_interface_name, optarg,
1253 sizeof(config.network_interface_name) - 1);
1191 config.network_interface_name[sizeof(config.network_interface_name) - 1] = '\x0'; 1254 config.network_interface_name[sizeof(config.network_interface_name) - 1] = '\x0';
1192 break; 1255 break;
1193 1256
@@ -1289,7 +1352,8 @@ static int put_ctrl(int fd, int len, int pri) {
1289 1352
1290 ctl.len = len; 1353 ctl.len = len;
1291 if (putmsg(fd, &ctl, 0, pri) < 0) { 1354 if (putmsg(fd, &ctl, 0, pri) < 0) {
1292 printf(_("Error: DLPI stream API failed to get MAC in put_ctrl/putmsg(): %s.\n"), strerror(errno)); 1355 printf(_("Error: DLPI stream API failed to get MAC in put_ctrl/putmsg(): %s.\n"),
1356 strerror(errno));
1293 exit(STATE_UNKNOWN); 1357 exit(STATE_UNKNOWN);
1294 } 1358 }
1295 1359
@@ -1302,7 +1366,8 @@ static int put_both(int fd, int clen, int dlen, int pri) {
1302 ctl.len = clen; 1366 ctl.len = clen;
1303 dat.len = dlen; 1367 dat.len = dlen;
1304 if (putmsg(fd, &ctl, &dat, pri) < 0) { 1368 if (putmsg(fd, &ctl, &dat, pri) < 0) {
1305 printf(_("Error: DLPI stream API failed to get MAC in put_both/putmsg().\n"), strerror(errno)); 1369 printf(_("Error: DLPI stream API failed to get MAC in put_both/putmsg().\n"),
1370 strerror(errno));
1306 exit(STATE_UNKNOWN); 1371 exit(STATE_UNKNOWN);
1307 } 1372 }
1308 1373
@@ -1314,7 +1379,8 @@ static int dl_open(const char *dev, int unit, int *fd) {
1314 dl_attach_req_t *attach_req = (dl_attach_req_t *)ctl_area; 1379 dl_attach_req_t *attach_req = (dl_attach_req_t *)ctl_area;
1315 1380
1316 if ((*fd = open(dev, O_RDWR)) == -1) { 1381 if ((*fd = open(dev, O_RDWR)) == -1) {
1317 printf(_("Error: DLPI stream API failed to get MAC in dl_attach_req/open(%s..): %s.\n"), dev, strerror(errno)); 1382 printf(_("Error: DLPI stream API failed to get MAC in dl_attach_req/open(%s..): %s.\n"),
1383 dev, strerror(errno));
1318 exit(STATE_UNKNOWN); 1384 exit(STATE_UNKNOWN);
1319 } 1385 }
1320 attach_req->dl_primitive = DL_ATTACH_REQ; 1386 attach_req->dl_primitive = DL_ATTACH_REQ;
@@ -1338,7 +1404,8 @@ static int dl_bind(int fd, int sap, u_char *addr) {
1338 put_ctrl(fd, sizeof(dl_bind_req_t), 0); 1404 put_ctrl(fd, sizeof(dl_bind_req_t), 0);
1339 get_msg(fd); 1405 get_msg(fd);
1340 if (GOT_ERR == check_ctrl(DL_BIND_ACK)) { 1406 if (GOT_ERR == check_ctrl(DL_BIND_ACK)) {
1341 printf(_("Error: DLPI stream API failed to get MAC in dl_bind/check_ctrl(): %s.\n"), strerror(errno)); 1407 printf(_("Error: DLPI stream API failed to get MAC in dl_bind/check_ctrl(): %s.\n"),
1408 strerror(errno));
1342 exit(STATE_UNKNOWN); 1409 exit(STATE_UNKNOWN);
1343 } 1410 }
1344 bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr, bind_ack->dl_addr_length); 1411 bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr, bind_ack->dl_addr_length);
@@ -1455,7 +1522,8 @@ void print_help(void) {
1455 printf(" %s\n", "-u, --unicast"); 1522 printf(" %s\n", "-u, --unicast");
1456 printf(" %s\n", _("Unicast testing: mimic a DHCP relay, requires -s")); 1523 printf(" %s\n", _("Unicast testing: mimic a DHCP relay, requires -s"));
1457 printf(" %s\n", "-x, --exclusive"); 1524 printf(" %s\n", "-x, --exclusive");
1458 printf(" %s\n", _("Only requested DHCP server may response (rogue DHCP server detection), requires -s")); 1525 printf(" %s\n",
1526 _("Only requested DHCP server may response (rogue DHCP server detection), requires -s"));
1459 1527
1460 printf(UT_SUPPORT); 1528 printf(UT_SUPPORT);
1461} 1529}
diff --git a/plugins-root/check_icmp.d/check_icmp_helpers.c b/plugins-root/check_icmp.d/check_icmp_helpers.c
index d56fbd8b..1b96a392 100644
--- a/plugins-root/check_icmp.d/check_icmp_helpers.c
+++ b/plugins-root/check_icmp.d/check_icmp_helpers.c
@@ -76,7 +76,7 @@ check_icmp_state check_icmp_state_init() {
76 76
77ping_target_create_wrapper ping_target_create(struct sockaddr_storage address) { 77ping_target_create_wrapper ping_target_create(struct sockaddr_storage address) {
78 ping_target_create_wrapper result = { 78 ping_target_create_wrapper result = {
79 .errorcode = OK, 79 .errorcode = 0,
80 }; 80 };
81 81
82 struct sockaddr_storage *tmp_addr = &address; 82 struct sockaddr_storage *tmp_addr = &address;
@@ -88,7 +88,7 @@ ping_target_create_wrapper ping_target_create(struct sockaddr_storage address) {
88 ((struct sockaddr_in *)tmp_addr)->sin_addr.s_addr == INADDR_ANY))) || 88 ((struct sockaddr_in *)tmp_addr)->sin_addr.s_addr == INADDR_ANY))) ||
89 (tmp_addr->ss_family == AF_INET6 && 89 (tmp_addr->ss_family == AF_INET6 &&
90 (((struct sockaddr_in6 *)tmp_addr)->sin6_addr.s6_addr == in6addr_any.s6_addr))) { 90 (((struct sockaddr_in6 *)tmp_addr)->sin6_addr.s6_addr == in6addr_any.s6_addr))) {
91 result.errorcode = ERROR; 91 result.errorcode = 1;
92 return result; 92 return result;
93 } 93 }
94 94
diff --git a/plugins-root/check_icmp.d/config.h b/plugins-root/check_icmp.d/config.h
index c348bef5..be388d0a 100644
--- a/plugins-root/check_icmp.d/config.h
+++ b/plugins-root/check_icmp.d/config.h
@@ -97,7 +97,7 @@ typedef struct icmp_ping_data {
97 97
98/* 80 msec packet interval by default */ 98/* 80 msec packet interval by default */
99// DEPRECATED, remove when removing the option 99// DEPRECATED, remove when removing the option
100#define DEFAULT_PKT_INTERVAL 80000 100#define DEFAULT_PKT_INTERVAL 80000
101 101
102#define DEFAULT_TARGET_INTERVAL 0 102#define DEFAULT_TARGET_INTERVAL 0
103 103
diff --git a/plugins-root/pst3.c b/plugins-root/pst3.c
index 1f69f3a6..1bfe3d35 100644
--- a/plugins-root/pst3.c
+++ b/plugins-root/pst3.c
@@ -1,45 +1,45 @@
1/***************************************************************************** 1/*****************************************************************************
2* 2 *
3* pst3 3 * pst3
4* 4 *
5* License: GPL 5 * License: GPL
6* Copyright (c) 2008 Monitoring Plugins Development Team 6 * Copyright (c) 2008 Monitoring Plugins Development Team
7* 7 *
8* Description: 8 * Description:
9* 9 *
10* This file contains the pst3 executable. This is a replacement ps command 10 * This file contains the pst3 executable. This is a replacement ps command
11* for Solaris to get output which provides a long argument listing, which 11 * for Solaris to get output which provides a long argument listing, which
12* is not possible with the standard ps command (due to truncation). /usr/ucb/ps 12 * is not possible with the standard ps command (due to truncation). /usr/ucb/ps
13* also has issues where some fields run into each other. 13 * also has issues where some fields run into each other.
14* 14 *
15* This executable works by reading process address structures, so needs 15 * This executable works by reading process address structures, so needs
16* to be executed as root 16 * to be executed as root
17* 17 *
18* Originally written by R.W.Ingraham 18 * Originally written by R.W.Ingraham
19* Rewritten by Duncan Ferguson (Altinity Ltd, June 2008) 19 * Rewritten by Duncan Ferguson (Altinity Ltd, June 2008)
20* The rewrite was necessary as /dev/kmem is not available within 20 * The rewrite was necessary as /dev/kmem is not available within
21* non-global zones on Solaris 10 21 * non-global zones on Solaris 10
22* 22 *
23* Details for rewrite came from 23 * Details for rewrite came from
24* source of /usr/ucb/ps on Solaris: 24 * source of /usr/ucb/ps on Solaris:
25* http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/ucbcmd/ps/ps.c#argvoff 25 * http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/ucbcmd/ps/ps.c#argvoff
26* usenet group posting 26 * usenet group posting
27* http://groups.google.com/group/comp.unix.solaris/tree/browse_frm/month/2001-09/bfa40c08bac819a2?rnum=141&_done=%2Fgroup%2Fcomp.unix.solaris%2Fbrowse_frm%2Fmonth%2F2001-09%3F 27 * http://groups.google.com/group/comp.unix.solaris/tree/browse_frm/month/2001-09/bfa40c08bac819a2?rnum=141&_done=%2Fgroup%2Fcomp.unix.solaris%2Fbrowse_frm%2Fmonth%2F2001-09%3F
28* 28 *
29* This program is free software: you can redistribute it and/or modify 29 * This program is free software: you can redistribute it and/or modify
30* it under the terms of the GNU General Public License as published by 30 * it under the terms of the GNU General Public License as published by
31* the Free Software Foundation, either version 3 of the License, or 31 * the Free Software Foundation, either version 3 of the License, or
32* (at your option) any later version. 32 * (at your option) any later version.
33* 33 *
34* This program is distributed in the hope that it will be useful, 34 * This program is distributed in the hope that it will be useful,
35* but WITHOUT ANY WARRANTY; without even the implied warranty of 35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37* GNU General Public License for more details. 37 * GNU General Public License for more details.
38* 38 *
39* You should have received a copy of the GNU General Public License 39 * You should have received a copy of the GNU General Public License
40* along with this program. If not, see <http://www.gnu.org/licenses/>. 40 * along with this program. If not, see <http://www.gnu.org/licenses/>.
41* 41 *
42*****************************************************************************/ 42 *****************************************************************************/
43 43
44#include <stdio.h> 44#include <stdio.h>
45#include <stdlib.h> 45#include <stdlib.h>
@@ -55,14 +55,14 @@
55 * Constants 55 * Constants
56 */ 56 */
57 57
58#define PROC_DIR "/proc" 58#define PROC_DIR "/proc"
59#define ARGS 30 59#define ARGS 30
60 60
61/* 61/*
62 * Globals 62 * Globals
63 */ 63 */
64 64
65static char * szProg; 65static char *szProg;
66 66
67/* 67/*
68 * Prototypes 68 * Prototypes
@@ -71,192 +71,179 @@ void usage();
71 71
72/*----------------------------------------------------------------------------*/ 72/*----------------------------------------------------------------------------*/
73 73
74int main (int argc, char **argv) 74int main(int argc, char **argv) {
75{ 75 DIR *procdir;
76 DIR *procdir; 76 struct dirent *proc;
77 struct dirent *proc; 77 char ps_name[ARGS];
78 char ps_name[ARGS]; 78 char as_name[ARGS];
79 char as_name[ARGS]; 79 psinfo_t psinfo;
80 psinfo_t psinfo; 80
81 81 /* Set our program name global */
82 /* Set our program name global */ 82 if ((szProg = strrchr(argv[0], '/')) != NULL) {
83 if ((szProg = strrchr(argv[0], '/')) != NULL) 83 szProg++;
84 szProg++; 84 } else {
85 else 85 szProg = argv[0];
86 szProg = argv[0]; 86 }
87 87
88 /* if given any parameters, print out help */ 88 /* if given any parameters, print out help */
89 if(argc > 1) { 89 if (argc > 1) {
90 (void)usage(); 90 (void)usage();
91 exit(1); 91 exit(1);
92 } 92 }
93 93
94 /* Make sure that our euid is root */ 94 /* Make sure that our euid is root */
95 if (geteuid() != 0) 95 if (geteuid() != 0) {
96 { 96 fprintf(stderr, "%s: This program can only be run by the root user!\n", szProg);
97 fprintf(stderr, "%s: This program can only be run by the root user!\n", szProg); 97 exit(1);
98 exit(1); 98 }
99 } 99
100 100 if ((procdir = opendir(PROC_DIR)) == NULL) {
101 if ((procdir = opendir(PROC_DIR)) == NULL) { 101 fprintf(stderr, "%s: cannot open PROC directory %s\n", szProg, PROC_DIR);
102 fprintf(stderr, "%s: cannot open PROC directory %s\n", szProg, PROC_DIR); 102 exit(1);
103 exit(1); 103 }
104 } 104
105 105 /* Display column headings */
106 /* Display column headings */ 106 printf("%c %5s %5s %5s %6s %6s %4s %s %s\n", 'S', "UID", "PID", "PPID", "VSZ", "RSS", "%CPU",
107 printf("%c %5s %5s %5s %6s %6s %4s %s %s\n", 107 "COMMAND", "ARGS");
108 'S', 108
109 "UID", 109 /* Zip through all of the process entries */
110 "PID", 110 while ((proc = readdir(procdir))) {
111 "PPID", 111 int ps_fd;
112 "VSZ", 112 int as_fd;
113 "RSS", 113 off_t argoff;
114 "%CPU", 114 int i;
115 "COMMAND", 115 char *args;
116 "ARGS" 116 char *procname;
117 ); 117 char *ptr;
118 118 int argslen;
119 /* Zip through all of the process entries */ 119 uintptr_t args_addr;
120 while((proc = readdir(procdir))) { 120 ;
121 int ps_fd; 121 uintptr_t *args_vecs;
122 int as_fd; 122 ;
123 off_t argoff; 123 int args_count;
124 int i; 124
125 char *args; 125 if (proc->d_name[0] == '.') {
126 char *procname; 126 continue;
127 char *ptr; 127 }
128 int argslen; 128
129 uintptr_t args_addr;; 129 sprintf(ps_name, "%s/%s/%s", PROC_DIR, proc->d_name, "psinfo");
130 uintptr_t *args_vecs;; 130 sprintf(as_name, "%s/%s/%s", PROC_DIR, proc->d_name, "as");
131 int args_count; 131 try_again:
132 132 if ((ps_fd = open(ps_name, O_RDONLY)) == -1) {
133 if(proc->d_name[0] == '.') 133 continue;
134 continue; 134 }
135 135
136 sprintf(ps_name,"%s/%s/%s",PROC_DIR,proc->d_name,"psinfo"); 136 if ((as_fd = open(as_name, O_RDONLY)) == -1) {
137 sprintf(as_name,"%s/%s/%s",PROC_DIR,proc->d_name,"as"); 137 close(ps_fd);
138try_again: 138 continue;
139 if((ps_fd = open(ps_name, O_RDONLY)) == -1) 139 }
140 continue; 140
141 141 if (read(ps_fd, &psinfo, sizeof(psinfo)) != sizeof(psinfo)) {
142 if((as_fd = open(as_name, O_RDONLY)) == -1) { 142 int err = errno;
143 close(ps_fd); 143 close(ps_fd);
144 continue; 144 close(as_fd);
145 } 145 if (err == EAGAIN) {
146 146 goto try_again;
147 if(read(ps_fd, &psinfo, sizeof(psinfo)) != sizeof(psinfo)) { 147 }
148 int err = errno; 148 if (err != ENOENT) {
149 close(ps_fd); 149 fprintf(stderr, "%s: read() on %s: %s\n", szProg, ps_name, strerror(err));
150 close(as_fd); 150 }
151 if(err == EAGAIN) goto try_again; 151 continue;
152 if(err != ENOENT) 152 }
153 fprintf(stderr, "%s: read() on %s: %s\n", szProg, 153 close(ps_fd);
154 ps_name, strerror(err)); 154
155 continue; 155 /* system process, ignore since the previous version did */
156 } 156 if (psinfo.pr_nlwp == 0 || strcmp(psinfo.pr_lwp.pr_clname, "SYS") == 0) {
157 close(ps_fd); 157 continue;
158 158 }
159 /* system process, ignore since the previous version did */ 159
160 if( 160 /* get the procname to match previous versions */
161 psinfo.pr_nlwp == 0 || 161 procname = strdup(psinfo.pr_psargs);
162 strcmp(psinfo.pr_lwp.pr_clname, "SYS") == 0 162 if ((ptr = strchr(procname, ' ')) != NULL) {
163 ) { 163 *ptr = '\0';
164 continue; 164 }
165 } 165 if ((ptr = strrchr(procname, '/')) != NULL) {
166 166 ptr++;
167 /* get the procname to match previous versions */ 167 } else {
168 procname = strdup(psinfo.pr_psargs); 168 ptr = procname;
169 if((ptr = strchr(procname, ' ')) != NULL) 169 }
170 *ptr = '\0'; 170
171 if((ptr = strrchr(procname, '/')) != NULL) 171 /*
172 ptr++; 172 * print out what we currently know
173 else 173 */
174 ptr = procname; 174 printf("%c %5d %5d %5d %6lu %6lu %4.1f %s ", psinfo.pr_lwp.pr_sname, psinfo.pr_euid,
175 175 psinfo.pr_pid, psinfo.pr_ppid, psinfo.pr_size, psinfo.pr_rssize,
176 /* 176 ((float)(psinfo.pr_pctcpu) / 0x8000 * 100.0), ptr);
177 * print out what we currently know 177 free(procname);
178 */ 178
179 printf("%c %5d %5d %5d %6lu %6lu %4.1f %s ", 179 /*
180 psinfo.pr_lwp.pr_sname, 180 * and now for the command line stuff
181 psinfo.pr_euid, 181 */
182 psinfo.pr_pid, 182
183 psinfo.pr_ppid, 183 args_addr = psinfo.pr_argv;
184 psinfo.pr_size, 184 args_count = psinfo.pr_argc;
185 psinfo.pr_rssize, 185 args_vecs = malloc(args_count * sizeof(uintptr_t));
186 ((float)(psinfo.pr_pctcpu) / 0x8000 * 100.0), 186
187 ptr 187 if (psinfo.pr_dmodel == PR_MODEL_NATIVE) {
188 ); 188 /* this process matches target process */
189 free(procname); 189 pread(as_fd, args_vecs, args_count * sizeof(uintptr_t), args_addr);
190 190 } else {
191 /* 191 /* this process is 64bit, target process is 32 bit*/
192 * and now for the command line stuff 192 caddr32_t *args_vecs32 = (caddr32_t *)args_vecs;
193 */ 193 pread(as_fd, args_vecs32, args_count * sizeof(caddr32_t), args_addr);
194 194 for (i = args_count - 1; i >= 0; --i) {
195 args_addr = psinfo.pr_argv; 195 args_vecs[i] = args_vecs32[i];
196 args_count = psinfo.pr_argc; 196 }
197 args_vecs = malloc(args_count * sizeof(uintptr_t)); 197 }
198 198
199 if(psinfo.pr_dmodel == PR_MODEL_NATIVE) { 199 /*
200 /* this process matches target process */ 200 * now read in the args - if what we read in fills buffer
201 pread(as_fd,args_vecs, args_count * sizeof(uintptr_t), 201 * resize buffer and reread that bit again
202 args_addr); 202 */
203 } else { 203 argslen = ARGS;
204 /* this process is 64bit, target process is 32 bit*/ 204 args = malloc(argslen + 1);
205 caddr32_t *args_vecs32 = (caddr32_t *)args_vecs; 205 for (i = 0; i < args_count; i++) {
206 pread(as_fd,args_vecs32,args_count * sizeof(caddr32_t), 206 memset(args, '\0', argslen + 1);
207 args_addr); 207 if (pread(as_fd, args, argslen, args_vecs[i]) <= 0) {
208 for (i=args_count-1;i>=0;--i) 208 break;
209 args_vecs[i]=args_vecs32[i]; 209 }
210 } 210 args[argslen] = '\0';
211 211 if (strlen(args) == argslen) {
212 /* 212 argslen += ARGS;
213 * now read in the args - if what we read in fills buffer 213 args = realloc(args, argslen + 1);
214 * resize buffer and reread that bit again 214 i--;
215 */ 215 continue;
216 argslen=ARGS; 216 }
217 args=malloc(argslen+1); 217 printf(" %s", args);
218 for(i=0;i<args_count;i++) { 218 }
219 memset(args,'\0',argslen+1); 219 free(args_vecs);
220 if(pread(as_fd, args, argslen, args_vecs[i]) <= 0) { 220 free(args);
221 break; 221 close(as_fd);
222 } 222 printf("\n");
223 args[argslen]='\0'; 223 }
224 if(strlen(args) == argslen){ 224
225 argslen += ARGS; 225 (void)closedir(procdir);
226 args = realloc(args, argslen + 1); 226
227 i--; 227 return (0);
228 continue;
229 }
230 printf(" %s", args);
231 }
232 free(args_vecs);
233 free(args);
234 close(as_fd);
235 printf("\n");
236 }
237
238 (void) closedir(procdir);
239
240 return (0);
241} 228}
242 229
243/*----------------------------------------------------------------------------*/ 230/*----------------------------------------------------------------------------*/
244 231
245void usage() { 232void usage() {
246 printf("%s: Help output\n\n", szProg); 233 printf("%s: Help output\n\n", szProg);
247 printf("If this program is given any arguments, this help is displayed.\n"); 234 printf("If this program is given any arguments, this help is displayed.\n");
248 printf("This command is used to print out the full command line for all\n"); 235 printf("This command is used to print out the full command line for all\n");
249 printf("running processes because /usr/bin/ps is limited to 80 chars and\n"); 236 printf("running processes because /usr/bin/ps is limited to 80 chars and\n");
250 printf("/usr/ucb/ps can merge columns together.\n\n"); 237 printf("/usr/ucb/ps can merge columns together.\n\n");
251 printf("Columns are:\n"); 238 printf("Columns are:\n");
252 printf("\tS - State of process - see 'ps' man page\n"); 239 printf("\tS - State of process - see 'ps' man page\n");
253 printf("\tUID - UID of the process owner\n"); 240 printf("\tUID - UID of the process owner\n");
254 printf("\tPID - PID of the process\n"); 241 printf("\tPID - PID of the process\n");
255 printf("\tPPID - PID of the parent process\n"); 242 printf("\tPPID - PID of the parent process\n");
256 printf("\tVSZ - Virtual memory usage (kilobytes)\n"); 243 printf("\tVSZ - Virtual memory usage (kilobytes)\n");
257 printf("\tRSS - Real memory usage (kilobytes)\n"); 244 printf("\tRSS - Real memory usage (kilobytes)\n");
258 printf("\t%%CPU - CPU usage\n"); 245 printf("\t%%CPU - CPU usage\n");
259 printf("\tCOMMAND - Command being run\n"); 246 printf("\tCOMMAND - Command being run\n");
260 printf("\tARGS - Full command line with arguments\n"); 247 printf("\tARGS - Full command line with arguments\n");
261 return; 248 return;
262} 249}
diff --git a/plugins/check_apt.c b/plugins/check_apt.c
index 5aaf1eb6..80ce6060 100644
--- a/plugins/check_apt.c
+++ b/plugins/check_apt.c
@@ -374,8 +374,8 @@ run_upgrade_result run_upgrade(const upgrade_type upgrade, const char *do_includ
374 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"), progname, rerrbuf); 374 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"), progname, rerrbuf);
375 } 375 }
376 376
377 struct output chld_out; 377 output chld_out;
378 struct output chld_err; 378 output chld_err;
379 char *cmdline = NULL; 379 char *cmdline = NULL;
380 cmdline = construct_cmdline(upgrade, upgrade_opts); 380 cmdline = construct_cmdline(upgrade, upgrade_opts);
381 if (input_filename != NULL) { 381 if (input_filename != NULL) {
@@ -492,8 +492,8 @@ run_update_result run_update(char *update_opts) {
492 result.sc = mp_set_subcheck_default_state(result.sc, STATE_OK); 492 result.sc = mp_set_subcheck_default_state(result.sc, STATE_OK);
493 xasprintf(&result.sc.output, "executing '%s' first", cmdline); 493 xasprintf(&result.sc.output, "executing '%s' first", cmdline);
494 494
495 struct output chld_out; 495 output chld_out;
496 struct output chld_err; 496 output chld_err;
497 int cmd_error = np_runcmd(cmdline, &chld_out, &chld_err, 0); 497 int cmd_error = np_runcmd(cmdline, &chld_out, &chld_err, 0);
498 /* apt-get update changes exit status if it can't fetch packages. 498 /* apt-get update changes exit status if it can't fetch packages.
499 * since we were explicitly asked to do so, this is treated as 499 * since we were explicitly asked to do so, this is treated as
diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c
index 2bc38d49..74b7a46f 100644
--- a/plugins/check_by_ssh.c
+++ b/plugins/check_by_ssh.c
@@ -45,7 +45,8 @@ typedef struct {
45 check_by_ssh_config config; 45 check_by_ssh_config config;
46} check_by_ssh_config_wrapper; 46} check_by_ssh_config_wrapper;
47static check_by_ssh_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/); 47static check_by_ssh_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
48static check_by_ssh_config_wrapper validate_arguments(check_by_ssh_config_wrapper /*config_wrapper*/); 48static check_by_ssh_config_wrapper
49 validate_arguments(check_by_ssh_config_wrapper /*config_wrapper*/);
49 50
50static command_construct comm_append(command_construct /*cmd*/, const char * /*str*/); 51static command_construct comm_append(command_construct /*cmd*/, const char * /*str*/);
51static void print_help(void); 52static void print_help(void);
@@ -90,7 +91,8 @@ int main(int argc, char **argv) {
90 91
91 /* SSH returns 255 if connection attempt fails; include the first line of error output */ 92 /* SSH returns 255 if connection attempt fails; include the first line of error output */
92 if (result == 255 && config.unknown_timeout) { 93 if (result == 255 && config.unknown_timeout) {
93 printf(_("SSH connection failed: %s\n"), chld_err.lines > 0 ? chld_err.line[0] : "(no error output)"); 94 printf(_("SSH connection failed: %s\n"),
95 chld_err.lines > 0 ? chld_err.line[0] : "(no error output)");
94 return STATE_UNKNOWN; 96 return STATE_UNKNOWN;
95 } 97 }
96 98
@@ -134,7 +136,8 @@ int main(int argc, char **argv) {
134 puts(chld_out.line[i]); 136 puts(chld_out.line[i]);
135 } 137 }
136 } else { 138 } else {
137 printf(_("%s - check_by_ssh: Remote command '%s' returned status %d\n"), state_text(result), config.remotecmd, result); 139 printf(_("%s - check_by_ssh: Remote command '%s' returned status %d\n"),
140 state_text(result), config.remotecmd, result);
138 } 141 }
139 return result; /* return error status from remote command */ 142 return result; /* return error status from remote command */
140 } 143 }
@@ -160,9 +163,11 @@ int main(int argc, char **argv) {
160 die(STATE_UNKNOWN, _("%s: Error parsing output\n"), progname); 163 die(STATE_UNKNOWN, _("%s: Error parsing output\n"), progname);
161 } 164 }
162 165
163 if (config.service[commands] && status_text && sscanf(chld_out.line[i], "STATUS CODE: %d", &cresult) == 1) { 166 if (config.service[commands] && status_text &&
164 fprintf(file_pointer, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n", (int)local_time, config.host_shortname, 167 sscanf(chld_out.line[i], "STATUS CODE: %d", &cresult) == 1) {
165 config.service[commands++], cresult, status_text); 168 fprintf(file_pointer, "[%d] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s\n",
169 (int)local_time, config.host_shortname, config.service[commands++], cresult,
170 status_text);
166 } 171 }
167 } 172 }
168 173
@@ -172,34 +177,35 @@ int main(int argc, char **argv) {
172 177
173/* process command-line arguments */ 178/* process command-line arguments */
174check_by_ssh_config_wrapper process_arguments(int argc, char **argv) { 179check_by_ssh_config_wrapper process_arguments(int argc, char **argv) {
175 static struct option longopts[] = {{"version", no_argument, 0, 'V'}, 180 static struct option longopts[] = {
176 {"help", no_argument, 0, 'h'}, 181 {"version", no_argument, 0, 'V'},
177 {"verbose", no_argument, 0, 'v'}, 182 {"help", no_argument, 0, 'h'},
178 {"fork", no_argument, 0, 'f'}, 183 {"verbose", no_argument, 0, 'v'},
179 {"timeout", required_argument, 0, 't'}, 184 {"fork", no_argument, 0, 'f'},
180 {"unknown-timeout", no_argument, 0, 'U'}, 185 {"timeout", required_argument, 0, 't'},
181 {"host", required_argument, 0, 'H'}, /* backward compatibility */ 186 {"unknown-timeout", no_argument, 0, 'U'},
182 {"hostname", required_argument, 0, 'H'}, 187 {"host", required_argument, 0, 'H'}, /* backward compatibility */
183 {"port", required_argument, 0, 'p'}, 188 {"hostname", required_argument, 0, 'H'},
184 {"output", required_argument, 0, 'O'}, 189 {"port", required_argument, 0, 'p'},
185 {"name", required_argument, 0, 'n'}, 190 {"output", required_argument, 0, 'O'},
186 {"services", required_argument, 0, 's'}, 191 {"name", required_argument, 0, 'n'},
187 {"identity", required_argument, 0, 'i'}, 192 {"services", required_argument, 0, 's'},
188 {"user", required_argument, 0, 'u'}, 193 {"identity", required_argument, 0, 'i'},
189 {"logname", required_argument, 0, 'l'}, 194 {"user", required_argument, 0, 'u'},
190 {"command", required_argument, 0, 'C'}, 195 {"logname", required_argument, 0, 'l'},
191 {"skip", optional_argument, 0, 'S'}, /* backwards compatibility */ 196 {"command", required_argument, 0, 'C'},
192 {"skip-stdout", optional_argument, 0, 'S'}, 197 {"skip", optional_argument, 0, 'S'}, /* backwards compatibility */
193 {"skip-stderr", optional_argument, 0, 'E'}, 198 {"skip-stdout", optional_argument, 0, 'S'},
194 {"warn-on-stderr", no_argument, 0, 'W'}, 199 {"skip-stderr", optional_argument, 0, 'E'},
195 {"proto1", no_argument, 0, '1'}, 200 {"warn-on-stderr", no_argument, 0, 'W'},
196 {"proto2", no_argument, 0, '2'}, 201 {"proto1", no_argument, 0, '1'},
197 {"use-ipv4", no_argument, 0, '4'}, 202 {"proto2", no_argument, 0, '2'},
198 {"use-ipv6", no_argument, 0, '6'}, 203 {"use-ipv4", no_argument, 0, '4'},
199 {"ssh-option", required_argument, 0, 'o'}, 204 {"use-ipv6", no_argument, 0, '6'},
200 {"quiet", no_argument, 0, 'q'}, 205 {"ssh-option", required_argument, 0, 'o'},
201 {"configfile", optional_argument, 0, 'F'}, 206 {"quiet", no_argument, 0, 'q'},
202 {0, 0, 0, 0}}; 207 {"configfile", optional_argument, 0, 'F'},
208 {0, 0, 0, 0}};
203 209
204 check_by_ssh_config_wrapper result = { 210 check_by_ssh_config_wrapper result = {
205 .errorcode = OK, 211 .errorcode = OK,
@@ -221,7 +227,8 @@ check_by_ssh_config_wrapper process_arguments(int argc, char **argv) {
221 227
222 int option = 0; 228 int option = 0;
223 while (true) { 229 while (true) {
224 int opt_index = getopt_long(argc, argv, "Vvh1246fqt:UH:O:p:i:u:l:C:S::E::n:s:o:F:", longopts, &option); 230 int opt_index =
231 getopt_long(argc, argv, "Vvh1246fqt:UH:O:p:i:u:l:C:S::E::n:s:o:F:", longopts, &option);
225 232
226 if (opt_index == -1 || opt_index == EOF) { 233 if (opt_index == -1 || opt_index == EOF) {
227 break; 234 break;
@@ -266,11 +273,13 @@ check_by_ssh_config_wrapper process_arguments(int argc, char **argv) {
266 char *p2; 273 char *p2;
267 274
268 p1 = optarg; 275 p1 = optarg;
269 result.config.service = realloc(result.config.service, (++result.config.number_of_services) * sizeof(char *)); 276 result.config.service = realloc(result.config.service,
277 (++result.config.number_of_services) * sizeof(char *));
270 while ((p2 = index(p1, ':'))) { 278 while ((p2 = index(p1, ':'))) {
271 *p2 = '\0'; 279 *p2 = '\0';
272 result.config.service[result.config.number_of_services - 1] = p1; 280 result.config.service[result.config.number_of_services - 1] = p1;
273 result.config.service = realloc(result.config.service, (++result.config.number_of_services) * sizeof(char *)); 281 result.config.service = realloc(
282 result.config.service, (++result.config.number_of_services) * sizeof(char *));
274 p1 = p2 + 1; 283 p1 = p2 + 1;
275 } 284 }
276 result.config.service[result.config.number_of_services - 1] = p1; 285 result.config.service[result.config.number_of_services - 1] = p1;
@@ -309,7 +318,8 @@ check_by_ssh_config_wrapper process_arguments(int argc, char **argv) {
309 case 'C': /* Command for remote machine */ 318 case 'C': /* Command for remote machine */
310 result.config.commands++; 319 result.config.commands++;
311 if (result.config.commands > 1) { 320 if (result.config.commands > 1) {
312 xasprintf(&result.config.remotecmd, "%s;echo STATUS CODE: $?;", result.config.remotecmd); 321 xasprintf(&result.config.remotecmd, "%s;echo STATUS CODE: $?;",
322 result.config.remotecmd);
313 } 323 }
314 xasprintf(&result.config.remotecmd, "%s%s", result.config.remotecmd, optarg); 324 xasprintf(&result.config.remotecmd, "%s%s", result.config.remotecmd, optarg);
315 break; 325 break;
@@ -396,7 +406,8 @@ command_construct comm_append(command_construct cmd, const char *str) {
396 die(STATE_UNKNOWN, _("%s: Argument limit of %d exceeded\n"), progname, NP_MAXARGS); 406 die(STATE_UNKNOWN, _("%s: Argument limit of %d exceeded\n"), progname, NP_MAXARGS);
397 } 407 }
398 408
399 if ((cmd.commargv = (char **)realloc(cmd.commargv, (cmd.commargc + 1) * sizeof(char *))) == NULL) { 409 if ((cmd.commargv = (char **)realloc(cmd.commargv, (cmd.commargc + 1) * sizeof(char *))) ==
410 NULL) {
400 die(STATE_UNKNOWN, _("Can not (re)allocate 'commargv' buffer\n")); 411 die(STATE_UNKNOWN, _("Can not (re)allocate 'commargv' buffer\n"));
401 } 412 }
402 413
@@ -412,12 +423,18 @@ check_by_ssh_config_wrapper validate_arguments(check_by_ssh_config_wrapper confi
412 return config_wrapper; 423 return config_wrapper;
413 } 424 }
414 425
415 if (config_wrapper.config.passive && config_wrapper.config.commands != config_wrapper.config.number_of_services) { 426 if (config_wrapper.config.passive &&
416 die(STATE_UNKNOWN, _("%s: In passive mode, you must provide a service name for each command.\n"), progname); 427 config_wrapper.config.commands != config_wrapper.config.number_of_services) {
428 die(STATE_UNKNOWN,
429 _("%s: In passive mode, you must provide a service name for each command.\n"),
430 progname);
417 } 431 }
418 432
419 if (config_wrapper.config.passive && config_wrapper.config.host_shortname == NULL) { 433 if (config_wrapper.config.passive && config_wrapper.config.host_shortname == NULL) {
420 die(STATE_UNKNOWN, _("%s: In passive mode, you must provide the host short name from the monitoring configs.\n"), progname); 434 die(STATE_UNKNOWN,
435 _("%s: In passive mode, you must provide the host short name from the monitoring "
436 "configs.\n"),
437 progname);
421 } 438 }
422 439
423 return config_wrapper; 440 return config_wrapper;
@@ -454,7 +471,8 @@ void print_help(void) {
454 printf(" %s\n", "-W, --warn-on-stderr]"); 471 printf(" %s\n", "-W, --warn-on-stderr]");
455 printf(" %s\n", _("Exit with an warning, if there is an output on STDERR")); 472 printf(" %s\n", _("Exit with an warning, if there is an output on STDERR"));
456 printf(" %s\n", "-f"); 473 printf(" %s\n", "-f");
457 printf(" %s\n", _("tells ssh to fork rather than create a tty [optional]. This will always return OK if ssh is executed")); 474 printf(" %s\n", _("tells ssh to fork rather than create a tty [optional]. This will always "
475 "return OK if ssh is executed"));
458 printf(" %s\n", "-C, --command='COMMAND STRING'"); 476 printf(" %s\n", "-C, --command='COMMAND STRING'");
459 printf(" %s\n", _("command to execute on the remote machine")); 477 printf(" %s\n", _("command to execute on the remote machine"));
460 printf(" %s\n", "-l, --logname=USERNAME"); 478 printf(" %s\n", "-l, --logname=USERNAME");
@@ -490,7 +508,9 @@ void print_help(void) {
490 printf(" %s\n", _("all of -O, -s, and -n options (servicelist order must match '-C'options)")); 508 printf(" %s\n", _("all of -O, -s, and -n options (servicelist order must match '-C'options)"));
491 printf("\n"); 509 printf("\n");
492 printf("%s\n", _("Examples:")); 510 printf("%s\n", _("Examples:"));
493 printf(" %s\n", "$ check_by_ssh -H localhost -n lh -s c1:c2:c3 -C uptime -C uptime -C uptime -O /tmp/foo"); 511 printf(
512 " %s\n",
513 "$ check_by_ssh -H localhost -n lh -s c1:c2:c3 -C uptime -C uptime -C uptime -O /tmp/foo");
494 printf(" %s\n", "$ cat /tmp/foo"); 514 printf(" %s\n", "$ cat /tmp/foo");
495 printf(" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c1;0; up 2 days"); 515 printf(" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c1;0; up 2 days");
496 printf(" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c2;0; up 2 days"); 516 printf(" %s\n", "[1080933700] PROCESS_SERVICE_CHECK_RESULT;flint;c2;0; up 2 days");
diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c
index 9b695499..373520ee 100644
--- a/plugins/check_cluster.c
+++ b/plugins/check_cluster.c
@@ -112,25 +112,30 @@ int main(int argc, char **argv) {
112 int return_code = STATE_OK; 112 int return_code = STATE_OK;
113 /* return the status of the cluster */ 113 /* return the status of the cluster */
114 if (config.check_type == CHECK_SERVICES) { 114 if (config.check_type == CHECK_SERVICES) {
115 return_code = get_status(total_services_warning + total_services_unknown + total_services_critical, config.thresholds); 115 return_code =
116 printf("CLUSTER %s: %s: %d ok, %d warning, %d unknown, %d critical\n", state_text(return_code), 116 get_status(total_services_warning + total_services_unknown + total_services_critical,
117 (config.label == NULL) ? "Service cluster" : config.label, total_services_ok, total_services_warning, total_services_unknown, 117 config.thresholds);
118 printf("CLUSTER %s: %s: %d ok, %d warning, %d unknown, %d critical\n",
119 state_text(return_code), (config.label == NULL) ? "Service cluster" : config.label,
120 total_services_ok, total_services_warning, total_services_unknown,
118 total_services_critical); 121 total_services_critical);
119 } else { 122 } else {
120 return_code = get_status(total_hosts_down + total_hosts_unreachable, config.thresholds); 123 return_code = get_status(total_hosts_down + total_hosts_unreachable, config.thresholds);
121 printf("CLUSTER %s: %s: %d up, %d down, %d unreachable\n", state_text(return_code), 124 printf("CLUSTER %s: %s: %d up, %d down, %d unreachable\n", state_text(return_code),
122 (config.label == NULL) ? "Host cluster" : config.label, total_hosts_up, total_hosts_down, total_hosts_unreachable); 125 (config.label == NULL) ? "Host cluster" : config.label, total_hosts_up,
126 total_hosts_down, total_hosts_unreachable);
123 } 127 }
124 128
125 exit(return_code); 129 exit(return_code);
126} 130}
127 131
128check_cluster_config_wrapper process_arguments(int argc, char **argv) { 132check_cluster_config_wrapper process_arguments(int argc, char **argv) {
129 static struct option longopts[] = {{"data", required_argument, 0, 'd'}, {"warning", required_argument, 0, 'w'}, 133 static struct option longopts[] = {
130 {"critical", required_argument, 0, 'c'}, {"label", required_argument, 0, 'l'}, 134 {"data", required_argument, 0, 'd'}, {"warning", required_argument, 0, 'w'},
131 {"host", no_argument, 0, 'h'}, {"service", no_argument, 0, 's'}, 135 {"critical", required_argument, 0, 'c'}, {"label", required_argument, 0, 'l'},
132 {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, 136 {"host", no_argument, 0, 'h'}, {"service", no_argument, 0, 's'},
133 {"help", no_argument, 0, 'H'}, {0, 0, 0, 0}}; 137 {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'},
138 {"help", no_argument, 0, 'H'}, {0, 0, 0, 0}};
134 139
135 check_cluster_config_wrapper result = { 140 check_cluster_config_wrapper result = {
136 .errorcode = OK, 141 .errorcode = OK,
@@ -251,7 +256,8 @@ void print_help(void) {
251 printf("\n"); 256 printf("\n");
252 printf("%s\n", _("Examples:")); 257 printf("%s\n", _("Examples:"));
253 printf(" %s\n", "check_cluster -s -d 2,0,2,0 -c @3:"); 258 printf(" %s\n", "check_cluster -s -d 2,0,2,0 -c @3:");
254 printf(" %s\n", _("Will alert critical if there are 3 or more service data points in a non-OK")); 259 printf(" %s\n",
260 _("Will alert critical if there are 3 or more service data points in a non-OK"));
255 printf(" %s\n", _("state.")); 261 printf(" %s\n", _("state."));
256 262
257 printf(UT_SUPPORT); 263 printf(UT_SUPPORT);
diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c
index 9efcd1cb..468ded31 100644
--- a/plugins/check_dbi.c
+++ b/plugins/check_dbi.c
@@ -71,8 +71,9 @@ static double timediff(struct timeval /*start*/, struct timeval /*end*/);
71 71
72static void np_dbi_print_error(dbi_conn /*conn*/, char * /*fmt*/, ...); 72static void np_dbi_print_error(dbi_conn /*conn*/, char * /*fmt*/, ...);
73 73
74static mp_state_enum do_query(dbi_conn /*conn*/, const char ** /*res_val_str*/, double * /*res_val*/, double * /*res_time*/, mp_dbi_metric /*metric*/, 74static mp_state_enum do_query(dbi_conn /*conn*/, const char ** /*res_val_str*/,
75 mp_dbi_type /*type*/, char * /*np_dbi_query*/); 75 double * /*res_val*/, double * /*res_time*/, mp_dbi_metric /*metric*/,
76 mp_dbi_type /*type*/, char * /*np_dbi_query*/);
76 77
77int main(int argc, char **argv) { 78int main(int argc, char **argv) {
78 int status = STATE_UNKNOWN; 79 int status = STATE_UNKNOWN;
@@ -118,7 +119,8 @@ int main(int argc, char **argv) {
118 dbi_inst *instance_p = {0}; 119 dbi_inst *instance_p = {0};
119 120
120 if (dbi_initialize_r(NULL, instance_p) < 0) { 121 if (dbi_initialize_r(NULL, instance_p) < 0) {
121 printf("UNKNOWN - failed to initialize DBI; possibly you don't have any drivers installed.\n"); 122 printf(
123 "UNKNOWN - failed to initialize DBI; possibly you don't have any drivers installed.\n");
122 return STATE_UNKNOWN; 124 return STATE_UNKNOWN;
123 } 125 }
124 126
@@ -133,10 +135,12 @@ int main(int argc, char **argv) {
133 135
134 driver = dbi_driver_open_r(config.dbi_driver, instance_p); 136 driver = dbi_driver_open_r(config.dbi_driver, instance_p);
135 if (!driver) { 137 if (!driver) {
136 printf("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n", config.dbi_driver); 138 printf("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n",
139 config.dbi_driver);
137 140
138 printf("Known drivers:\n"); 141 printf("Known drivers:\n");
139 for (driver = dbi_driver_list_r(NULL, instance_p); driver; driver = dbi_driver_list_r(driver, instance_p)) { 142 for (driver = dbi_driver_list_r(NULL, instance_p); driver;
143 driver = dbi_driver_list_r(driver, instance_p)) {
140 printf(" - %s\n", dbi_driver_get_name(driver)); 144 printf(" - %s\n", dbi_driver_get_name(driver));
141 } 145 }
142 return STATE_UNKNOWN; 146 return STATE_UNKNOWN;
@@ -156,7 +160,8 @@ int main(int argc, char **argv) {
156 const char *opt; 160 const char *opt;
157 161
158 if (verbose > 1) { 162 if (verbose > 1) {
159 printf("Setting DBI driver option '%s' to '%s'\n", config.dbi_options[i].key, config.dbi_options[i].value); 163 printf("Setting DBI driver option '%s' to '%s'\n", config.dbi_options[i].key,
164 config.dbi_options[i].value);
160 } 165 }
161 166
162 if (!dbi_conn_set_option(conn, config.dbi_options[i].key, config.dbi_options[i].value)) { 167 if (!dbi_conn_set_option(conn, config.dbi_options[i].key, config.dbi_options[i].value)) {
@@ -164,10 +169,12 @@ int main(int argc, char **argv) {
164 } 169 }
165 /* else: status != 0 */ 170 /* else: status != 0 */
166 171
167 np_dbi_print_error(conn, "UNKNOWN - failed to set option '%s' to '%s'", config.dbi_options[i].key, config.dbi_options[i].value); 172 np_dbi_print_error(conn, "UNKNOWN - failed to set option '%s' to '%s'",
173 config.dbi_options[i].key, config.dbi_options[i].value);
168 printf("Known driver options:\n"); 174 printf("Known driver options:\n");
169 175
170 for (opt = dbi_conn_get_option_list(conn, NULL); opt; opt = dbi_conn_get_option_list(conn, opt)) { 176 for (opt = dbi_conn_get_option_list(conn, NULL); opt;
177 opt = dbi_conn_get_option_list(conn, opt)) {
171 printf(" - %s\n", opt); 178 printf(" - %s\n", opt);
172 } 179 }
173 dbi_conn_close(conn); 180 dbi_conn_close(conn);
@@ -230,14 +237,16 @@ int main(int argc, char **argv) {
230 } 237 }
231 238
232 if (dbi_conn_select_db(conn, config.dbi_database)) { 239 if (dbi_conn_select_db(conn, config.dbi_database)) {
233 np_dbi_print_error(conn, "UNKNOWN - failed to select database '%s'", config.dbi_database); 240 np_dbi_print_error(conn, "UNKNOWN - failed to select database '%s'",
241 config.dbi_database);
234 return STATE_UNKNOWN; 242 return STATE_UNKNOWN;
235 } 243 }
236 } 244 }
237 245
238 if (config.dbi_query) { 246 if (config.dbi_query) {
239 /* execute query */ 247 /* execute query */
240 status = do_query(conn, &query_val_str, &query_val, &query_time, config.metric, config.type, config.dbi_query); 248 status = do_query(conn, &query_val_str, &query_val, &query_time, config.metric, config.type,
249 config.dbi_query);
241 if (status != STATE_OK) { 250 if (status != STATE_OK) {
242 /* do_query prints an error message in this case */ 251 /* do_query prints an error message in this case */
243 return status; 252 return status;
@@ -281,7 +290,8 @@ int main(int argc, char **argv) {
281 /* In case of METRIC_QUERY_RESULT, isnan(query_val) indicates an error 290 /* In case of METRIC_QUERY_RESULT, isnan(query_val) indicates an error
282 * which should have been reported and handled (abort) before 291 * which should have been reported and handled (abort) before
283 * ... unless we expected a string to be returned */ 292 * ... unless we expected a string to be returned */
284 assert((config.metric != METRIC_QUERY_RESULT) || (!isnan(query_val)) || (config.type == TYPE_STRING)); 293 assert((config.metric != METRIC_QUERY_RESULT) || (!isnan(query_val)) ||
294 (config.type == TYPE_STRING));
285 295
286 assert((config.type != TYPE_STRING) || (config.expect || config.expect_re_str)); 296 assert((config.type != TYPE_STRING) || (config.expect || config.expect_re_str));
287 297
@@ -289,12 +299,14 @@ int main(int argc, char **argv) {
289 if (config.dbi_query) { 299 if (config.dbi_query) {
290 if (config.type == TYPE_STRING) { 300 if (config.type == TYPE_STRING) {
291 assert(config.expect || config.expect_re_str); 301 assert(config.expect || config.expect_re_str);
292 printf(", '%s' returned '%s' in %fs", config.dbi_query, query_val_str ? query_val_str : "<nothing>", query_time); 302 printf(", '%s' returned '%s' in %fs", config.dbi_query,
303 query_val_str ? query_val_str : "<nothing>", query_time);
293 if (status != STATE_OK) { 304 if (status != STATE_OK) {
294 if (config.expect) { 305 if (config.expect) {
295 printf(" (expected '%s')", config.expect); 306 printf(" (expected '%s')", config.expect);
296 } else if (config.expect_re_str) { 307 } else if (config.expect_re_str) {
297 printf(" (expected regex /%s/%s)", config.expect_re_str, ((config.expect_re_cflags & REG_ICASE) ? "i" : "")); 308 printf(" (expected regex /%s/%s)", config.expect_re_str,
309 ((config.expect_re_cflags & REG_ICASE) ? "i" : ""));
298 } 310 }
299 } 311 }
300 } else if (isnan(query_val)) { 312 } else if (isnan(query_val)) {
@@ -304,18 +316,31 @@ int main(int argc, char **argv) {
304 } 316 }
305 } 317 }
306 318
307 printf(" | conntime=%fs;%s;%s;0; server_version=%u;%s;%s;0;", conn_time, 319 printf(
308 ((config.metric == METRIC_CONN_TIME) && config.warning_range) ? config.warning_range : "", 320 " | conntime=%fs;%s;%s;0; server_version=%u;%s;%s;0;", conn_time,
309 ((config.metric == METRIC_CONN_TIME) && config.critical_range) ? config.critical_range : "", server_version, 321 ((config.metric == METRIC_CONN_TIME) && config.warning_range) ? config.warning_range : "",
310 ((config.metric == METRIC_SERVER_VERSION) && config.warning_range) ? config.warning_range : "", 322 ((config.metric == METRIC_CONN_TIME) && config.critical_range) ? config.critical_range : "",
311 ((config.metric == METRIC_SERVER_VERSION) && config.critical_range) ? config.critical_range : ""); 323 server_version,
324 ((config.metric == METRIC_SERVER_VERSION) && config.warning_range) ? config.warning_range
325 : "",
326 ((config.metric == METRIC_SERVER_VERSION) && config.critical_range) ? config.critical_range
327 : "");
312 if (config.dbi_query) { 328 if (config.dbi_query) {
313 if (!isnan(query_val)) { /* this is also true when -e is used */ 329 if (!isnan(query_val)) { /* this is also true when -e is used */
314 printf(" query=%f;%s;%s;;", query_val, ((config.metric == METRIC_QUERY_RESULT) && config.warning_range) ? config.warning_range : "", 330 printf(" query=%f;%s;%s;;", query_val,
315 ((config.metric == METRIC_QUERY_RESULT) && config.critical_range) ? config.critical_range : ""); 331 ((config.metric == METRIC_QUERY_RESULT) && config.warning_range)
332 ? config.warning_range
333 : "",
334 ((config.metric == METRIC_QUERY_RESULT) && config.critical_range)
335 ? config.critical_range
336 : "");
316 } 337 }
317 printf(" querytime=%fs;%s;%s;0;", query_time, ((config.metric == METRIC_QUERY_TIME) && config.warning_range) ? config.warning_range : "", 338 printf(" querytime=%fs;%s;%s;0;", query_time,
318 ((config.metric == METRIC_QUERY_TIME) && config.critical_range) ? config.critical_range : ""); 339 ((config.metric == METRIC_QUERY_TIME) && config.warning_range) ? config.warning_range
340 : "",
341 ((config.metric == METRIC_QUERY_TIME) && config.critical_range)
342 ? config.critical_range
343 : "");
319 } 344 }
320 printf("\n"); 345 printf("\n");
321 return status; 346 return status;
@@ -442,7 +467,8 @@ check_dbi_config_wrapper process_arguments(int argc, char **argv) {
442 *value = '\0'; 467 *value = '\0';
443 ++value; 468 ++value;
444 469
445 new = realloc(result.config.dbi_options, (result.config.dbi_options_num + 1) * sizeof(*new)); 470 new = realloc(result.config.dbi_options,
471 (result.config.dbi_options_num + 1) * sizeof(*new));
446 if (!new) { 472 if (!new) {
447 printf("UNKNOWN - failed to reallocate memory\n"); 473 printf("UNKNOWN - failed to reallocate memory\n");
448 exit(STATE_UNKNOWN); 474 exit(STATE_UNKNOWN);
@@ -464,7 +490,8 @@ check_dbi_config_wrapper process_arguments(int argc, char **argv) {
464 } 490 }
465 } 491 }
466 492
467 set_thresholds(&result.config.dbi_thresholds, result.config.warning_range, result.config.critical_range); 493 set_thresholds(&result.config.dbi_thresholds, result.config.warning_range,
494 result.config.critical_range);
468 495
469 return validate_arguments(result); 496 return validate_arguments(result);
470} 497}
@@ -474,21 +501,28 @@ check_dbi_config_wrapper validate_arguments(check_dbi_config_wrapper config_wrap
474 usage("Must specify a DBI driver"); 501 usage("Must specify a DBI driver");
475 } 502 }
476 503
477 if (((config_wrapper.config.metric == METRIC_QUERY_RESULT) || (config_wrapper.config.metric == METRIC_QUERY_TIME)) && 504 if (((config_wrapper.config.metric == METRIC_QUERY_RESULT) ||
505 (config_wrapper.config.metric == METRIC_QUERY_TIME)) &&
478 (!config_wrapper.config.dbi_query)) { 506 (!config_wrapper.config.dbi_query)) {
479 usage("Must specify a query to execute (metric == QUERY_RESULT)"); 507 usage("Must specify a query to execute (metric == QUERY_RESULT)");
480 } 508 }
481 509
482 if ((config_wrapper.config.metric != METRIC_CONN_TIME) && (config_wrapper.config.metric != METRIC_SERVER_VERSION) && 510 if ((config_wrapper.config.metric != METRIC_CONN_TIME) &&
483 (config_wrapper.config.metric != METRIC_QUERY_RESULT) && (config_wrapper.config.metric != METRIC_QUERY_TIME)) { 511 (config_wrapper.config.metric != METRIC_SERVER_VERSION) &&
512 (config_wrapper.config.metric != METRIC_QUERY_RESULT) &&
513 (config_wrapper.config.metric != METRIC_QUERY_TIME)) {
484 usage("Invalid metric specified"); 514 usage("Invalid metric specified");
485 } 515 }
486 516
487 if (config_wrapper.config.expect && (config_wrapper.config.warning_range || config_wrapper.config.critical_range || config_wrapper.config.expect_re_str)) { 517 if (config_wrapper.config.expect &&
518 (config_wrapper.config.warning_range || config_wrapper.config.critical_range ||
519 config_wrapper.config.expect_re_str)) {
488 usage("Do not mix -e and -w/-c/-r/-R"); 520 usage("Do not mix -e and -w/-c/-r/-R");
489 } 521 }
490 522
491 if (config_wrapper.config.expect_re_str && (config_wrapper.config.warning_range || config_wrapper.config.critical_range || config_wrapper.config.expect)) { 523 if (config_wrapper.config.expect_re_str &&
524 (config_wrapper.config.warning_range || config_wrapper.config.critical_range ||
525 config_wrapper.config.expect)) {
492 usage("Do not mix -r/-R and -w/-c/-e"); 526 usage("Do not mix -r/-R and -w/-c/-e");
493 } 527 }
494 528
@@ -496,7 +530,8 @@ check_dbi_config_wrapper validate_arguments(check_dbi_config_wrapper config_wrap
496 usage("Option -e requires metric QUERY_RESULT"); 530 usage("Option -e requires metric QUERY_RESULT");
497 } 531 }
498 532
499 if (config_wrapper.config.expect_re_str && (config_wrapper.config.metric != METRIC_QUERY_RESULT)) { 533 if (config_wrapper.config.expect_re_str &&
534 (config_wrapper.config.metric != METRIC_QUERY_RESULT)) {
500 usage("Options -r/-R require metric QUERY_RESULT"); 535 usage("Options -r/-R require metric QUERY_RESULT");
501 } 536 }
502 537
@@ -607,7 +642,8 @@ void print_usage(void) {
607 printf(" [-e <string>] [-r|-R <regex>]\n"); 642 printf(" [-e <string>] [-r|-R <regex>]\n");
608} 643}
609 644
610const char *get_field_str(dbi_conn conn, dbi_result res, unsigned short field_type, mp_dbi_metric metric, mp_dbi_type type) { 645const char *get_field_str(dbi_conn conn, dbi_result res, unsigned short field_type,
646 mp_dbi_metric metric, mp_dbi_type type) {
611 const char *str; 647 const char *str;
612 648
613 if (field_type != DBI_TYPE_STRING) { 649 if (field_type != DBI_TYPE_STRING) {
@@ -630,7 +666,8 @@ const char *get_field_str(dbi_conn conn, dbi_result res, unsigned short field_ty
630 return str; 666 return str;
631} 667}
632 668
633double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type, mp_dbi_metric metric, mp_dbi_type type) { 669double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type, mp_dbi_metric metric,
670 mp_dbi_type type) {
634 double val = NAN; 671 double val = NAN;
635 672
636 if (*field_type == DBI_TYPE_INTEGER) { 673 if (*field_type == DBI_TYPE_INTEGER) {
@@ -679,7 +716,8 @@ double get_field(dbi_conn conn, dbi_result res, unsigned short *field_type, mp_d
679 return val; 716 return val;
680} 717}
681 718
682mp_state_enum get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str, double *res_val, mp_dbi_metric metric, mp_dbi_type type) { 719mp_state_enum get_query_result(dbi_conn conn, dbi_result res, const char **res_val_str,
720 double *res_val, mp_dbi_metric metric, mp_dbi_type type) {
683 unsigned short field_type; 721 unsigned short field_type;
684 double val = NAN; 722 double val = NAN;
685 723
@@ -747,8 +785,8 @@ mp_state_enum get_query_result(dbi_conn conn, dbi_result res, const char **res_v
747 return STATE_OK; 785 return STATE_OK;
748} 786}
749 787
750mp_state_enum do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *res_time, mp_dbi_metric metric, mp_dbi_type type, 788mp_state_enum do_query(dbi_conn conn, const char **res_val_str, double *res_val, double *res_time,
751 char *np_dbi_query) { 789 mp_dbi_metric metric, mp_dbi_type type, char *np_dbi_query) {
752 dbi_result res; 790 dbi_result res;
753 791
754 struct timeval timeval_start; 792 struct timeval timeval_start;
diff --git a/plugins/check_dig.c b/plugins/check_dig.c
index d0903be2..c27e5f13 100644
--- a/plugins/check_dig.c
+++ b/plugins/check_dig.c
@@ -81,8 +81,9 @@ int main(int argc, char **argv) {
81 81
82 char *command_line; 82 char *command_line;
83 /* get the command to run */ 83 /* get the command to run */
84 xasprintf(&command_line, "%s %s %s -p %d @%s %s %s +retry=%d +time=%d", PATH_TO_DIG, config.dig_args, config.query_transport, 84 xasprintf(&command_line, "%s %s %s -p %d @%s %s %s +retry=%d +time=%d", PATH_TO_DIG,
85 config.server_port, config.dns_server, config.query_address, config.record_type, config.number_tries, timeout_interval_dig); 85 config.dig_args, config.query_transport, config.server_port, config.dns_server,
86 config.query_address, config.record_type, config.number_tries, timeout_interval_dig);
86 87
87 alarm(timeout_interval); 88 alarm(timeout_interval);
88 struct timeval start_time; 89 struct timeval start_time;
@@ -118,8 +119,9 @@ int main(int argc, char **argv) {
118 printf("%s\n", chld_out.line[i]); 119 printf("%s\n", chld_out.line[i]);
119 } 120 }
120 121
121 if (strcasestr(chld_out.line[i], (config.expected_address == NULL ? config.query_address : config.expected_address)) != 122 if (strcasestr(chld_out.line[i], (config.expected_address == NULL
122 NULL) { 123 ? config.query_address
124 : config.expected_address)) != NULL) {
123 msg = chld_out.line[i]; 125 msg = chld_out.line[i];
124 result = STATE_OK; 126 result = STATE_OK;
125 127
@@ -174,8 +176,9 @@ int main(int argc, char **argv) {
174 176
175 printf("DNS %s - %.3f seconds response time (%s)|%s\n", state_text(result), elapsed_time, 177 printf("DNS %s - %.3f seconds response time (%s)|%s\n", state_text(result), elapsed_time,
176 msg ? msg : _("Probably a non-existent host/domain"), 178 msg ? msg : _("Probably a non-existent host/domain"),
177 fperfdata("time", elapsed_time, "s", (config.warning_interval > UNDEFINED), config.warning_interval, 179 fperfdata("time", elapsed_time, "s", (config.warning_interval > UNDEFINED),
178 (config.critical_interval > UNDEFINED), config.critical_interval, true, 0, false, 0)); 180 config.warning_interval, (config.critical_interval > UNDEFINED),
181 config.critical_interval, true, 0, false, 0));
179 exit(result); 182 exit(result);
180} 183}
181 184
@@ -335,7 +338,8 @@ void print_help(void) {
335 printf(" %s\n", "-T, --record_type=STRING"); 338 printf(" %s\n", "-T, --record_type=STRING");
336 printf(" %s\n", _("Record type to lookup (default: A)")); 339 printf(" %s\n", _("Record type to lookup (default: A)"));
337 printf(" %s\n", "-a, --expected_address=STRING"); 340 printf(" %s\n", "-a, --expected_address=STRING");
338 printf(" %s\n", _("An address expected to be in the answer section. If not set, uses whatever")); 341 printf(" %s\n",
342 _("An address expected to be in the answer section. If not set, uses whatever"));
339 printf(" %s\n", _("was in -l")); 343 printf(" %s\n", _("was in -l"));
340 printf(" %s\n", "-A, --dig-arguments=STRING"); 344 printf(" %s\n", "-A, --dig-arguments=STRING");
341 printf(" %s\n", _("Pass STRING as argument(s) to dig")); 345 printf(" %s\n", _("Pass STRING as argument(s) to dig"));
diff --git a/plugins/check_disk.c b/plugins/check_disk.c
index 515ddff0..d42b5486 100644
--- a/plugins/check_disk.c
+++ b/plugins/check_disk.c
@@ -78,18 +78,21 @@ typedef struct {
78} check_disk_config_wrapper; 78} check_disk_config_wrapper;
79static check_disk_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/); 79static check_disk_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
80 80
81static void set_all_thresholds(parameter_list_elem *path, char *warn_freespace_units, char *crit_freespace_units, 81static void set_all_thresholds(parameter_list_elem *path, char *warn_freespace_units,
82 char *warn_freespace_percent, char *crit_freespace_percent, char *warn_freeinodes_percent, 82 char *crit_freespace_units, char *warn_freespace_percent,
83 char *crit_freespace_percent, char *warn_freeinodes_percent,
83 char *crit_freeinodes_percent); 84 char *crit_freeinodes_percent);
84static double calculate_percent(uintmax_t /*value*/, uintmax_t /*total*/); 85static double calculate_percent(uintmax_t /*value*/, uintmax_t /*total*/);
85static bool stat_path(parameter_list_elem * /*parameters*/, bool /*ignore_missing*/); 86static bool stat_path(parameter_list_elem * /*parameters*/, bool /*ignore_missing*/);
86 87
87/* 88/*
88 * Puts the values from a struct fs_usage into a parameter_list with an additional flag to control how reserved 89 * Puts the values from a struct fs_usage into a parameter_list with an additional flag to control
89 * and inodes should be judged (ignored or not) 90 * how reserved and inodes should be judged (ignored or not)
90 */ 91 */
91static parameter_list_elem get_path_stats(parameter_list_elem parameters, struct fs_usage fsp, bool freespace_ignore_reserved); 92static parameter_list_elem get_path_stats(parameter_list_elem parameters, struct fs_usage fsp,
92static mp_subcheck evaluate_filesystem(measurement_unit measurement_unit, bool display_inodes_perfdata, byte_unit unit); 93 bool freespace_ignore_reserved);
94static mp_subcheck evaluate_filesystem(measurement_unit measurement_unit,
95 bool display_inodes_perfdata, byte_unit unit);
93 96
94void print_usage(void); 97void print_usage(void);
95static void print_help(void); 98static void print_help(void);
@@ -111,7 +114,6 @@ const byte_unit TeraBytes_factor = 1000000000000;
111const byte_unit PetaBytes_factor = 1000000000000000; 114const byte_unit PetaBytes_factor = 1000000000000000;
112const byte_unit ExaBytes_factor = 1000000000000000000; 115const byte_unit ExaBytes_factor = 1000000000000000000;
113 116
114
115int main(int argc, char **argv) { 117int main(int argc, char **argv) {
116 setlocale(LC_ALL, ""); 118 setlocale(LC_ALL, "");
117 bindtextdomain(PACKAGE, LOCALEDIR); 119 bindtextdomain(PACKAGE, LOCALEDIR);
@@ -140,7 +142,8 @@ int main(int argc, char **argv) {
140 } 142 }
141 143
142 if (!config.path_ignored) { 144 if (!config.path_ignored) {
143 mp_int_fs_list_set_best_match(config.path_select_list, config.mount_list, config.exact_match); 145 mp_int_fs_list_set_best_match(config.path_select_list, config.mount_list,
146 config.exact_match);
144 } 147 }
145 148
146 // Error if no match found for specified paths 149 // Error if no match found for specified paths
@@ -203,20 +206,23 @@ int main(int argc, char **argv) {
203 } 206 }
204 207
205 if (path->group == NULL) { 208 if (path->group == NULL) {
206 if (config.fs_exclude_list && np_find_regmatch(config.fs_exclude_list, mount_entry->me_type)) { 209 if (config.fs_exclude_list &&
210 np_find_regmatch(config.fs_exclude_list, mount_entry->me_type)) {
207 // Skip excluded fs's 211 // Skip excluded fs's
208 path = mp_int_fs_list_del(&config.path_select_list, path); 212 path = mp_int_fs_list_del(&config.path_select_list, path);
209 continue; 213 continue;
210 } 214 }
211 215
212 if (config.device_path_exclude_list && (np_find_name(config.device_path_exclude_list, mount_entry->me_devname) || 216 if (config.device_path_exclude_list &&
213 np_find_name(config.device_path_exclude_list, mount_entry->me_mountdir))) { 217 (np_find_name(config.device_path_exclude_list, mount_entry->me_devname) ||
218 np_find_name(config.device_path_exclude_list, mount_entry->me_mountdir))) {
214 // Skip excluded device or mount paths 219 // Skip excluded device or mount paths
215 path = mp_int_fs_list_del(&config.path_select_list, path); 220 path = mp_int_fs_list_del(&config.path_select_list, path);
216 continue; 221 continue;
217 } 222 }
218 223
219 if (config.fs_include_list && !np_find_regmatch(config.fs_include_list, mount_entry->me_type)) { 224 if (config.fs_include_list &&
225 !np_find_regmatch(config.fs_include_list, mount_entry->me_type)) {
220 // Skip not included fstypes 226 // Skip not included fstypes
221 path = mp_int_fs_list_del(&config.path_select_list, path); 227 path = mp_int_fs_list_del(&config.path_select_list, path);
222 continue; 228 continue;
@@ -259,8 +265,8 @@ int main(int argc, char **argv) {
259 if (verbose >= 3) { 265 if (verbose >= 3) {
260 printf("For %s, used_units=%lu free_units=%lu total_units=%lu " 266 printf("For %s, used_units=%lu free_units=%lu total_units=%lu "
261 "fsp.fsu_blocksize=%lu\n", 267 "fsp.fsu_blocksize=%lu\n",
262 mount_entry->me_mountdir, filesystem->used_bytes, filesystem->free_bytes, filesystem->total_bytes, 268 mount_entry->me_mountdir, filesystem->used_bytes, filesystem->free_bytes,
263 fsp.fsu_blocksize); 269 filesystem->total_bytes, fsp.fsu_blocksize);
264 } 270 }
265 } else { 271 } else {
266 // failed to retrieve file system data or not mounted? 272 // failed to retrieve file system data or not mounted?
@@ -285,12 +291,14 @@ int main(int argc, char **argv) {
285 measurement_unit_list *measurements = NULL; 291 measurement_unit_list *measurements = NULL;
286 measurement_unit_list *current = NULL; 292 measurement_unit_list *current = NULL;
287 // create measuring units, because of groups 293 // create measuring units, because of groups
288 for (parameter_list_elem *filesystem = config.path_select_list.first; filesystem; filesystem = mp_int_fs_list_get_next(filesystem)) { 294 for (parameter_list_elem *filesystem = config.path_select_list.first; filesystem;
295 filesystem = mp_int_fs_list_get_next(filesystem)) {
289 assert(filesystem->best_match != NULL); 296 assert(filesystem->best_match != NULL);
290 297
291 if (filesystem->group == NULL) { 298 if (filesystem->group == NULL) {
292 // create a measurement unit for the fs 299 // create a measurement unit for the fs
293 measurement_unit unit = create_measurement_unit_from_filesystem(*filesystem, config.display_mntp); 300 measurement_unit unit =
301 create_measurement_unit_from_filesystem(*filesystem, config.display_mntp);
294 if (measurements == NULL) { 302 if (measurements == NULL) {
295 measurements = current = add_measurement_list(NULL, unit); 303 measurements = current = add_measurement_list(NULL, unit);
296 } else { 304 } else {
@@ -300,14 +308,17 @@ int main(int argc, char **argv) {
300 // Grouped elements are consecutive 308 // Grouped elements are consecutive
301 if (measurements == NULL) { 309 if (measurements == NULL) {
302 // first entry 310 // first entry
303 measurement_unit unit = create_measurement_unit_from_filesystem(*filesystem, config.display_mntp); 311 measurement_unit unit =
312 create_measurement_unit_from_filesystem(*filesystem, config.display_mntp);
304 unit.name = strdup(filesystem->group); 313 unit.name = strdup(filesystem->group);
305 measurements = current = add_measurement_list(NULL, unit); 314 measurements = current = add_measurement_list(NULL, unit);
306 } else { 315 } else {
307 // if this is the first element of a group, the name of the previous entry is different 316 // if this is the first element of a group, the name of the previous entry is
317 // different
308 if (strcmp(filesystem->group, current->unit.name) != 0) { 318 if (strcmp(filesystem->group, current->unit.name) != 0) {
309 // so, this must be the first element of a group 319 // so, this must be the first element of a group
310 measurement_unit unit = create_measurement_unit_from_filesystem(*filesystem, config.display_mntp); 320 measurement_unit unit =
321 create_measurement_unit_from_filesystem(*filesystem, config.display_mntp);
311 unit.name = filesystem->group; 322 unit.name = filesystem->group;
312 current = add_measurement_list(measurements, unit); 323 current = add_measurement_list(measurements, unit);
313 324
@@ -322,7 +333,8 @@ int main(int argc, char **argv) {
322 /* Process for every path in list */ 333 /* Process for every path in list */
323 if (measurements != NULL) { 334 if (measurements != NULL) {
324 for (measurement_unit_list *unit = measurements; unit; unit = unit->next) { 335 for (measurement_unit_list *unit = measurements; unit; unit = unit->next) {
325 mp_subcheck unit_sc = evaluate_filesystem(unit->unit, config.display_inodes_perfdata, config.display_unit); 336 mp_subcheck unit_sc = evaluate_filesystem(unit->unit, config.display_inodes_perfdata,
337 config.display_unit);
326 mp_add_subcheck_to_check(&overall, unit_sc); 338 mp_add_subcheck_to_check(&overall, unit_sc);
327 } 339 }
328 } else { 340 } else {
@@ -433,7 +445,8 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
433 445
434 while (true) { 446 while (true) {
435 int option = 0; 447 int option = 0;
436 int option_index = getopt_long(argc, argv, "+?VqhvefCt:c:w:K:W:u:p:x:X:N:mklLPg:R:r:i:I:MEAn", longopts, &option); 448 int option_index = getopt_long(
449 argc, argv, "+?VqhvefCt:c:w:K:W:u:p:x:X:N:mklLPg:R:r:i:I:MEAn", longopts, &option);
437 450
438 if (option_index == -1 || option_index == EOF) { 451 if (option_index == -1 || option_index == EOF) {
439 break; 452 break;
@@ -578,9 +591,10 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
578 result.config.display_inodes_perfdata = true; 591 result.config.display_inodes_perfdata = true;
579 break; 592 break;
580 case 'p': /* select path */ { 593 case 'p': /* select path */ {
581 if (!(warn_freespace_units || crit_freespace_units || warn_freespace_percent || crit_freespace_percent || 594 if (!(warn_freespace_units || crit_freespace_units || warn_freespace_percent ||
582 warn_freeinodes_percent || crit_freeinodes_percent)) { 595 crit_freespace_percent || warn_freeinodes_percent || crit_freeinodes_percent)) {
583 die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set a threshold value before using -p\n")); 596 die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"),
597 _("Must set a threshold value before using -p\n"));
584 } 598 }
585 599
586 /* add parameter if not found. overwrite thresholds if path has already been added */ 600 /* add parameter if not found. overwrite thresholds if path has already been added */
@@ -595,7 +609,8 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
595 // } 609 // }
596 } 610 }
597 search_entry->group = group; 611 search_entry->group = group;
598 set_all_thresholds(search_entry, warn_freespace_units, crit_freespace_units, warn_freespace_percent, crit_freespace_percent, 612 set_all_thresholds(search_entry, warn_freespace_units, crit_freespace_units,
613 warn_freespace_percent, crit_freespace_percent,
599 614
600 warn_freeinodes_percent, crit_freeinodes_percent); 615 warn_freeinodes_percent, crit_freeinodes_percent);
601 616
@@ -603,7 +618,8 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
603 // if (!stat_path(se, result.config.ignore_missing)) { 618 // if (!stat_path(se, result.config.ignore_missing)) {
604 // break; 619 // break;
605 // } 620 // }
606 mp_int_fs_list_set_best_match(result.config.path_select_list, result.config.mount_list, result.config.exact_match); 621 mp_int_fs_list_set_best_match(result.config.path_select_list, result.config.mount_list,
622 result.config.exact_match);
607 623
608 path_selected = true; 624 path_selected = true;
609 } break; 625 } break;
@@ -615,7 +631,8 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
615 if (err != 0) { 631 if (err != 0) {
616 char errbuf[MAX_INPUT_BUFFER]; 632 char errbuf[MAX_INPUT_BUFFER];
617 regerror(err, &result.config.fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER); 633 regerror(err, &result.config.fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER);
618 die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); 634 die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"),
635 _("Could not compile regular expression"), errbuf);
619 } 636 }
620 break; 637 break;
621 case 'N': /* include file system type */ 638 case 'N': /* include file system type */
@@ -623,7 +640,8 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
623 if (err != 0) { 640 if (err != 0) {
624 char errbuf[MAX_INPUT_BUFFER]; 641 char errbuf[MAX_INPUT_BUFFER];
625 regerror(err, &result.config.fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER); 642 regerror(err, &result.config.fs_exclude_list->regex, errbuf, MAX_INPUT_BUFFER);
626 die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); 643 die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"),
644 _("Could not compile regular expression"), errbuf);
627 } 645 }
628 } break; 646 } break;
629 case 'v': /* verbose */ 647 case 'v': /* verbose */
@@ -638,7 +656,8 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
638 break; 656 break;
639 case 'E': 657 case 'E':
640 if (path_selected) { 658 if (path_selected) {
641 die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set -E before selecting paths\n")); 659 die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"),
660 _("Must set -E before selecting paths\n"));
642 } 661 }
643 result.config.exact_match = true; 662 result.config.exact_match = true;
644 break; 663 break;
@@ -647,7 +666,8 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
647 break; 666 break;
648 case 'g': 667 case 'g':
649 if (path_selected) { 668 if (path_selected) {
650 die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), _("Must set group value before selecting paths\n")); 669 die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"),
670 _("Must set group value before selecting paths\n"));
651 } 671 }
652 group = optarg; 672 group = optarg;
653 break; 673 break;
@@ -657,14 +677,16 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
657 case 'i': { 677 case 'i': {
658 if (!path_selected) { 678 if (!path_selected) {
659 die(STATE_UNKNOWN, "DISK %s: %s\n", _("UNKNOWN"), 679 die(STATE_UNKNOWN, "DISK %s: %s\n", _("UNKNOWN"),
660 _("Paths need to be selected before using -i/-I. Use -A to select all paths explicitly")); 680 _("Paths need to be selected before using -i/-I. Use -A to select all paths "
681 "explicitly"));
661 } 682 }
662 regex_t regex; 683 regex_t regex;
663 int err = regcomp(&regex, optarg, cflags); 684 int err = regcomp(&regex, optarg, cflags);
664 if (err != 0) { 685 if (err != 0) {
665 char errbuf[MAX_INPUT_BUFFER]; 686 char errbuf[MAX_INPUT_BUFFER];
666 regerror(err, &regex, errbuf, MAX_INPUT_BUFFER); 687 regerror(err, &regex, errbuf, MAX_INPUT_BUFFER);
667 die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); 688 die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"),
689 _("Could not compile regular expression"), errbuf);
668 } 690 }
669 691
670 for (parameter_list_elem *elem = result.config.path_select_list.first; elem;) { 692 for (parameter_list_elem *elem = result.config.path_select_list.first; elem;) {
@@ -695,10 +717,11 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
695 cflags |= REG_ICASE; 717 cflags |= REG_ICASE;
696 // Intentional fallthrough 718 // Intentional fallthrough
697 case 'r': { 719 case 'r': {
698 if (!(warn_freespace_units || crit_freespace_units || warn_freespace_percent || crit_freespace_percent || 720 if (!(warn_freespace_units || crit_freespace_units || warn_freespace_percent ||
699 warn_freeinodes_percent || crit_freeinodes_percent)) { 721 crit_freespace_percent || warn_freeinodes_percent || crit_freeinodes_percent)) {
700 die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"), 722 die(STATE_UNKNOWN, "DISK %s: %s", _("UNKNOWN"),
701 _("Must set a threshold value before using -r/-R/-A (--ereg-path/--eregi-path/--all)\n")); 723 _("Must set a threshold value before using -r/-R/-A "
724 "(--ereg-path/--eregi-path/--all)\n"));
702 } 725 }
703 726
704 regex_t regex; 727 regex_t regex;
@@ -706,7 +729,8 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
706 if (err != 0) { 729 if (err != 0) {
707 char errbuf[MAX_INPUT_BUFFER]; 730 char errbuf[MAX_INPUT_BUFFER];
708 regerror(err, &regex, errbuf, MAX_INPUT_BUFFER); 731 regerror(err, &regex, errbuf, MAX_INPUT_BUFFER);
709 die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); 732 die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"),
733 _("Could not compile regular expression"), errbuf);
710 } 734 }
711 735
712 bool found = false; 736 bool found = false;
@@ -714,16 +738,21 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
714 if (np_regex_match_mount_entry(me, &regex)) { 738 if (np_regex_match_mount_entry(me, &regex)) {
715 found = true; 739 found = true;
716 if (verbose >= 3) { 740 if (verbose >= 3) {
717 printf("%s %s matching expression %s\n", me->me_devname, me->me_mountdir, optarg); 741 printf("%s %s matching expression %s\n", me->me_devname, me->me_mountdir,
742 optarg);
718 } 743 }
719 744
720 /* add parameter if not found. overwrite thresholds if path has already been added */ 745 /* add parameter if not found. overwrite thresholds if path has already been
746 * added */
721 parameter_list_elem *se = NULL; 747 parameter_list_elem *se = NULL;
722 if (!(se = mp_int_fs_list_find(result.config.path_select_list, me->me_mountdir))) { 748 if (!(se = mp_int_fs_list_find(result.config.path_select_list,
723 se = mp_int_fs_list_append(&result.config.path_select_list, me->me_mountdir); 749 me->me_mountdir))) {
750 se =
751 mp_int_fs_list_append(&result.config.path_select_list, me->me_mountdir);
724 } 752 }
725 se->group = group; 753 se->group = group;
726 set_all_thresholds(se, warn_freespace_units, crit_freespace_units, warn_freespace_percent, crit_freespace_percent, 754 set_all_thresholds(se, warn_freespace_units, crit_freespace_units,
755 warn_freespace_percent, crit_freespace_percent,
727 warn_freeinodes_percent, crit_freeinodes_percent); 756 warn_freeinodes_percent, crit_freeinodes_percent);
728 } 757 }
729 } 758 }
@@ -735,11 +764,13 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
735 break; 764 break;
736 } 765 }
737 766
738 die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"), _("Regular expression did not match any path or disk"), optarg); 767 die(STATE_UNKNOWN, "DISK %s: %s - %s\n", _("UNKNOWN"),
768 _("Regular expression did not match any path or disk"), optarg);
739 } 769 }
740 770
741 path_selected = true; 771 path_selected = true;
742 mp_int_fs_list_set_best_match(result.config.path_select_list, result.config.mount_list, result.config.exact_match); 772 mp_int_fs_list_set_best_match(result.config.path_select_list, result.config.mount_list,
773 result.config.exact_match);
743 cflags = default_cflags; 774 cflags = default_cflags;
744 775
745 } break; 776 } break;
@@ -747,16 +778,20 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
747 result.config.display_mntp = true; 778 result.config.display_mntp = true;
748 break; 779 break;
749 case 'C': { 780 case 'C': {
750 /* add all mount entries to path_select list if no partitions have been explicitly defined using -p */ 781 /* add all mount entries to path_select list if no partitions have been explicitly
782 * defined using -p */
751 if (!path_selected) { 783 if (!path_selected) {
752 parameter_list_elem *path; 784 parameter_list_elem *path;
753 for (struct mount_entry *me = result.config.mount_list; me; me = me->me_next) { 785 for (struct mount_entry *me = result.config.mount_list; me; me = me->me_next) {
754 if (!(path = mp_int_fs_list_find(result.config.path_select_list, me->me_mountdir))) { 786 if (!(path = mp_int_fs_list_find(result.config.path_select_list,
755 path = mp_int_fs_list_append(&result.config.path_select_list, me->me_mountdir); 787 me->me_mountdir))) {
788 path =
789 mp_int_fs_list_append(&result.config.path_select_list, me->me_mountdir);
756 } 790 }
757 path->best_match = me; 791 path->best_match = me;
758 path->group = group; 792 path->group = group;
759 set_all_thresholds(path, warn_freespace_units, crit_freespace_units, warn_freespace_percent, crit_freespace_percent, 793 set_all_thresholds(path, warn_freespace_units, crit_freespace_units,
794 warn_freespace_percent, crit_freespace_percent,
760 warn_freeinodes_percent, crit_freeinodes_percent); 795 warn_freeinodes_percent, crit_freeinodes_percent);
761 } 796 }
762 } 797 }
@@ -843,10 +878,12 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
843 if (verbose > 0) { 878 if (verbose > 0) {
844 printf("Got an positional filesystem: %s\n", argv[index]); 879 printf("Got an positional filesystem: %s\n", argv[index]);
845 } 880 }
846 struct parameter_list *se = mp_int_fs_list_append(&result.config.path_select_list, strdup(argv[index++])); 881 struct parameter_list *se =
882 mp_int_fs_list_append(&result.config.path_select_list, strdup(argv[index++]));
847 path_selected = true; 883 path_selected = true;
848 set_all_thresholds(se, warn_freespace_units, crit_freespace_units, warn_freespace_percent, crit_freespace_percent, 884 set_all_thresholds(se, warn_freespace_units, crit_freespace_units, warn_freespace_percent,
849 warn_freeinodes_percent, crit_freeinodes_percent); 885 crit_freespace_percent, warn_freeinodes_percent,
886 crit_freeinodes_percent);
850 } 887 }
851 888
852 // If a list of paths has not been explicitly selected, find entire 889 // If a list of paths has not been explicitly selected, find entire
@@ -864,18 +901,21 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
864 } 901 }
865 path->best_match = me; 902 path->best_match = me;
866 path->group = group; 903 path->group = group;
867 set_all_thresholds(path, warn_freespace_units, crit_freespace_units, warn_freespace_percent, crit_freespace_percent, 904 set_all_thresholds(path, warn_freespace_units, crit_freespace_units,
905 warn_freespace_percent, crit_freespace_percent,
868 warn_freeinodes_percent, crit_freeinodes_percent); 906 warn_freeinodes_percent, crit_freeinodes_percent);
869 } 907 }
870 } 908 }
871 909
872 // Set thresholds to the appropriate unit 910 // Set thresholds to the appropriate unit
873 for (parameter_list_elem *tmp = result.config.path_select_list.first; tmp; tmp = mp_int_fs_list_get_next(tmp)) { 911 for (parameter_list_elem *tmp = result.config.path_select_list.first; tmp;
912 tmp = mp_int_fs_list_get_next(tmp)) {
874 913
875 mp_perfdata_value factor = mp_create_pd_value(unit); 914 mp_perfdata_value factor = mp_create_pd_value(unit);
876 915
877 if (tmp->freespace_units.critical_is_set) { 916 if (tmp->freespace_units.critical_is_set) {
878 tmp->freespace_units.critical = mp_range_multiply(tmp->freespace_units.critical, factor); 917 tmp->freespace_units.critical =
918 mp_range_multiply(tmp->freespace_units.critical, factor);
879 } 919 }
880 if (tmp->freespace_units.warning_is_set) { 920 if (tmp->freespace_units.warning_is_set) {
881 tmp->freespace_units.warning = mp_range_multiply(tmp->freespace_units.warning, factor); 921 tmp->freespace_units.warning = mp_range_multiply(tmp->freespace_units.warning, factor);
@@ -885,8 +925,10 @@ check_disk_config_wrapper process_arguments(int argc, char **argv) {
885 return result; 925 return result;
886} 926}
887 927
888void set_all_thresholds(parameter_list_elem *path, char *warn_freespace_units, char *crit_freespace_units, char *warn_freespace_percent, 928void set_all_thresholds(parameter_list_elem *path, char *warn_freespace_units,
889 char *crit_freespace_percent, char *warn_freeinodes_percent, char *crit_freeinodes_percent) { 929 char *crit_freespace_units, char *warn_freespace_percent,
930 char *crit_freespace_percent, char *warn_freeinodes_percent,
931 char *crit_freeinodes_percent) {
890 mp_range_parsed tmp; 932 mp_range_parsed tmp;
891 933
892 if (warn_freespace_units) { 934 if (warn_freespace_units) {
@@ -927,7 +969,8 @@ void print_help(void) {
927 printf(COPYRIGHT, copyright, email); 969 printf(COPYRIGHT, copyright, email);
928 970
929 printf("%s\n", _("This plugin checks the amount of used disk space on a mounted file system")); 971 printf("%s\n", _("This plugin checks the amount of used disk space on a mounted file system"));
930 printf("%s\n", _("and generates an alert if free space is less than one of the threshold values")); 972 printf("%s\n",
973 _("and generates an alert if free space is less than one of the threshold values"));
931 974
932 printf("\n\n"); 975 printf("\n\n");
933 976
@@ -949,7 +992,8 @@ void print_help(void) {
949 printf(" %s\n", "-K, --icritical=PERCENT%"); 992 printf(" %s\n", "-K, --icritical=PERCENT%");
950 printf(" %s\n", _("Exit with CRITICAL status if less than PERCENT of inode space is free")); 993 printf(" %s\n", _("Exit with CRITICAL status if less than PERCENT of inode space is free"));
951 printf(" %s\n", "-p, --path=PATH, --partition=PARTITION"); 994 printf(" %s\n", "-p, --path=PATH, --partition=PARTITION");
952 printf(" %s\n", _("Mount point or block device as emitted by the mount(8) command (may be repeated)")); 995 printf(" %s\n",
996 _("Mount point or block device as emitted by the mount(8) command (may be repeated)"));
953 printf(" %s\n", "-x, --exclude_device=PATH <STRING>"); 997 printf(" %s\n", "-x, --exclude_device=PATH <STRING>");
954 printf(" %s\n", _("Ignore device (only works if -p unspecified)")); 998 printf(" %s\n", _("Ignore device (only works if -p unspecified)"));
955 printf(" %s\n", "-C, --clear"); 999 printf(" %s\n", "-C, --clear");
@@ -963,71 +1007,88 @@ void print_help(void) {
963 printf(" %s\n", "-P, --iperfdata"); 1007 printf(" %s\n", "-P, --iperfdata");
964 printf(" %s\n", _("Display inode usage in perfdata")); 1008 printf(" %s\n", _("Display inode usage in perfdata"));
965 printf(" %s\n", "-g, --group=NAME"); 1009 printf(" %s\n", "-g, --group=NAME");
966 printf(" %s\n", _("Group paths. Thresholds apply to (free-)space of all partitions together")); 1010 printf(" %s\n",
1011 _("Group paths. Thresholds apply to (free-)space of all partitions together"));
967 printf(" %s\n", "-l, --local"); 1012 printf(" %s\n", "-l, --local");
968 printf(" %s\n", _("Only check local filesystems")); 1013 printf(" %s\n", _("Only check local filesystems"));
969 printf(" %s\n", "-L, --stat-remote-fs"); 1014 printf(" %s\n", "-L, --stat-remote-fs");
970 printf(" %s\n", _("Only check local filesystems against thresholds. Yet call stat on remote filesystems")); 1015 printf(
1016 " %s\n",
1017 _("Only check local filesystems against thresholds. Yet call stat on remote filesystems"));
971 printf(" %s\n", _("to test if they are accessible (e.g. to detect Stale NFS Handles)")); 1018 printf(" %s\n", _("to test if they are accessible (e.g. to detect Stale NFS Handles)"));
972 printf(" %s\n", "-M, --mountpoint"); 1019 printf(" %s\n", "-M, --mountpoint");
973 printf(" %s\n", _("Display the (block) device instead of the mount point")); 1020 printf(" %s\n", _("Display the (block) device instead of the mount point"));
974 printf(" %s\n", "-A, --all"); 1021 printf(" %s\n", "-A, --all");
975 printf(" %s\n", _("Explicitly select all paths. This is equivalent to -R '.*'")); 1022 printf(" %s\n", _("Explicitly select all paths. This is equivalent to -R '.*'"));
976 printf(" %s\n", "-R, --eregi-path=PATH, --eregi-partition=PARTITION"); 1023 printf(" %s\n", "-R, --eregi-path=PATH, --eregi-partition=PARTITION");
977 printf(" %s\n", _("Case insensitive regular expression for path/partition (may be repeated)")); 1024 printf(" %s\n",
1025 _("Case insensitive regular expression for path/partition (may be repeated)"));
978 printf(" %s\n", "-r, --ereg-path=PATH, --ereg-partition=PARTITION"); 1026 printf(" %s\n", "-r, --ereg-path=PATH, --ereg-partition=PARTITION");
979 printf(" %s\n", _("Regular expression for path or partition (may be repeated)")); 1027 printf(" %s\n", _("Regular expression for path or partition (may be repeated)"));
980 printf(" %s\n", "-I, --ignore-eregi-path=PATH, --ignore-eregi-partition=PARTITION"); 1028 printf(" %s\n", "-I, --ignore-eregi-path=PATH, --ignore-eregi-partition=PARTITION");
981 printf(" %s\n", _("Regular expression to ignore selected path/partition (case insensitive) (may be repeated)")); 1029 printf(" %s\n", _("Regular expression to ignore selected path/partition (case insensitive) "
1030 "(may be repeated)"));
982 printf(" %s\n", "-i, --ignore-ereg-path=PATH, --ignore-ereg-partition=PARTITION"); 1031 printf(" %s\n", "-i, --ignore-ereg-path=PATH, --ignore-ereg-partition=PARTITION");
983 printf(" %s\n", _("Regular expression to ignore selected path or partition (may be repeated)")); 1032 printf(" %s\n",
1033 _("Regular expression to ignore selected path or partition (may be repeated)"));
984 printf(" %s\n", "-n, --ignore-missing"); 1034 printf(" %s\n", "-n, --ignore-missing");
985 printf(" %s\n", _("Return OK if no filesystem matches, filesystem does not exist or is inaccessible.")); 1035 printf(" %s\n",
1036 _("Return OK if no filesystem matches, filesystem does not exist or is inaccessible."));
986 printf(" %s\n", _("(Provide this option before -p / -r / --ereg-path if used)")); 1037 printf(" %s\n", _("(Provide this option before -p / -r / --ereg-path if used)"));
987 printf(UT_PLUG_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); 1038 printf(UT_PLUG_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
988 printf(" %s\n", "-u, --units=STRING"); 1039 printf(" %s\n", "-u, --units=STRING");
989 printf(" %s\n", _("Select the unit used for the absolute value thresholds")); 1040 printf(" %s\n", _("Select the unit used for the absolute value thresholds"));
990 printf( 1041 printf(" %s\n", _("Choose one of \"bytes\", \"KiB\", \"kB\", \"MiB\", \"MB\", \"GiB\", "
991 " %s\n", 1042 "\"GB\", \"TiB\", \"TB\", \"PiB\", \"PB\" (default: MiB)"));
992 _("Choose one of \"bytes\", \"KiB\", \"kB\", \"MiB\", \"MB\", \"GiB\", \"GB\", \"TiB\", \"TB\", \"PiB\", \"PB\" (default: MiB)"));
993 printf(" %s\n", "-k, --kilobytes"); 1043 printf(" %s\n", "-k, --kilobytes");
994 printf(" %s\n", _("Same as '--units kB'")); 1044 printf(" %s\n", _("Same as '--units kB'"));
995 printf(" %s\n", "--display-unit"); 1045 printf(" %s\n", "--display-unit");
996 printf(" %s\n", _("Select the unit used for in the output")); 1046 printf(" %s\n", _("Select the unit used for in the output"));
997 printf( 1047 printf(" %s\n", _("Choose one of \"bytes\", \"KiB\", \"kB\", \"MiB\", \"MB\", \"GiB\", "
998 " %s\n", 1048 "\"GB\", \"TiB\", \"TB\", \"PiB\", \"PB\" (default: MiB)"));
999 _("Choose one of \"bytes\", \"KiB\", \"kB\", \"MiB\", \"MB\", \"GiB\", \"GB\", \"TiB\", \"TB\", \"PiB\", \"PB\" (default: MiB)"));
1000 printf(" %s\n", "-m, --megabytes"); 1049 printf(" %s\n", "-m, --megabytes");
1001 printf(" %s\n", _("Same as '--units MB'")); 1050 printf(" %s\n", _("Same as '--units MB'"));
1002 printf(UT_VERBOSE); 1051 printf(UT_VERBOSE);
1003 printf(" %s\n", "-X, --exclude-type=TYPE_REGEX"); 1052 printf(" %s\n", "-X, --exclude-type=TYPE_REGEX");
1004 printf(" %s\n", _("Ignore all filesystems of types matching given regex(7) (may be repeated)")); 1053 printf(" %s\n",
1054 _("Ignore all filesystems of types matching given regex(7) (may be repeated)"));
1005 printf(" %s\n", "-N, --include-type=TYPE_REGEX"); 1055 printf(" %s\n", "-N, --include-type=TYPE_REGEX");
1006 printf(" %s\n", _("Check only filesystems where the type matches this given regex(7) (may be repeated)")); 1056 printf(
1057 " %s\n",
1058 _("Check only filesystems where the type matches this given regex(7) (may be repeated)"));
1007 printf(UT_OUTPUT_FORMAT); 1059 printf(UT_OUTPUT_FORMAT);
1008 1060
1009 printf("\n"); 1061 printf("\n");
1010 printf("%s\n", _("General usage hints:")); 1062 printf("%s\n", _("General usage hints:"));
1011 printf(" %s\n", _("- Arguments are positional! \"-w 5 -c 1 -p /foo -w6 -c2 -p /bar\" is not the same as")); 1063 printf(
1064 " %s\n",
1065 _("- Arguments are positional! \"-w 5 -c 1 -p /foo -w6 -c2 -p /bar\" is not the same as"));
1012 printf(" %s\n", _("\"-w 5 -c 1 -p /bar w6 -c2 -p /foo\".")); 1066 printf(" %s\n", _("\"-w 5 -c 1 -p /bar w6 -c2 -p /foo\"."));
1013 printf(" %s\n", _("- The syntax is broadly: \"{thresholds a} {paths a} -C {thresholds b} {thresholds b} ...\"")); 1067 printf(" %s\n", _("- The syntax is broadly: \"{thresholds a} {paths a} -C {thresholds b} "
1068 "{thresholds b} ...\""));
1014 1069
1015 printf("\n"); 1070 printf("\n");
1016 printf("%s\n", _("Examples:")); 1071 printf("%s\n", _("Examples:"));
1017 printf(" %s\n", "check_disk -w 10% -c 5% -p /tmp -p /var -C -w 100000 -c 50000 -p /"); 1072 printf(" %s\n", "check_disk -w 10% -c 5% -p /tmp -p /var -C -w 100000 -c 50000 -p /");
1018 printf(" %s\n\n", _("Checks /tmp and /var at 10% and 5%, and / at 100MB and 50MB")); 1073 printf(" %s\n\n", _("Checks /tmp and /var at 10% and 5%, and / at 100MB and 50MB"));
1019 printf(" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -g sidDATA -r '^/oracle/SID/data.*$'"); 1074 printf(" %s\n",
1020 printf(" %s\n", _("Checks all filesystems not matching -r at 100M and 50M. The fs matching the -r regex")); 1075 "check_disk -w 100 -c 50 -C -w 1000 -c 500 -g sidDATA -r '^/oracle/SID/data.*$'");
1021 printf(" %s\n\n", _("are grouped which means the freespace thresholds are applied to all disks together")); 1076 printf(
1077 " %s\n",
1078 _("Checks all filesystems not matching -r at 100M and 50M. The fs matching the -r regex"));
1079 printf(" %s\n\n",
1080 _("are grouped which means the freespace thresholds are applied to all disks together"));
1022 printf(" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -p /foo -C -w 5% -c 3% -p /bar"); 1081 printf(" %s\n", "check_disk -w 100 -c 50 -C -w 1000 -c 500 -p /foo -C -w 5% -c 3% -p /bar");
1023 printf(" %s\n", _("Checks /foo for 1000M/500M and /bar for 5/3%. All remaining volumes use 100M/50M")); 1082 printf(" %s\n",
1083 _("Checks /foo for 1000M/500M and /bar for 5/3%. All remaining volumes use 100M/50M"));
1024 1084
1025 printf(UT_SUPPORT); 1085 printf(UT_SUPPORT);
1026} 1086}
1027 1087
1028void print_usage(void) { 1088void print_usage(void) {
1029 printf("%s\n", _("Usage:")); 1089 printf("%s\n", _("Usage:"));
1030 printf(" %s {-w absolute_limit |-w percentage_limit%% | -W inode_percentage_limit } {-c absolute_limit|-c percentage_limit%% | -K " 1090 printf(" %s {-w absolute_limit |-w percentage_limit%% | -W inode_percentage_limit } {-c "
1091 "absolute_limit|-c percentage_limit%% | -K "
1031 "inode_percentage_limit } {-p path | -x device}\n", 1092 "inode_percentage_limit } {-p path | -x device}\n",
1032 progname); 1093 progname);
1033 printf("[-C] [-E] [-e] [-f] [-g group ] [-k] [-l] [-M] [-m] [-R path ] [-r path ]\n"); 1094 printf("[-C] [-E] [-e] [-f] [-g group ] [-k] [-l] [-M] [-m] [-R path ] [-r path ]\n");
@@ -1049,13 +1110,15 @@ bool stat_path(parameter_list_elem *parameters, bool ignore_missing) {
1049 return false; 1110 return false;
1050 } 1111 }
1051 printf("DISK %s - ", _("CRITICAL")); 1112 printf("DISK %s - ", _("CRITICAL"));
1052 die(STATE_CRITICAL, _("%s %s: %s\n"), parameters->name, _("is not accessible"), strerror(errno)); 1113 die(STATE_CRITICAL, _("%s %s: %s\n"), parameters->name, _("is not accessible"),
1114 strerror(errno));
1053 } 1115 }
1054 1116
1055 return true; 1117 return true;
1056} 1118}
1057 1119
1058static parameter_list_elem get_path_stats(parameter_list_elem parameters, const struct fs_usage fsp, bool freespace_ignore_reserved) { 1120static parameter_list_elem get_path_stats(parameter_list_elem parameters, const struct fs_usage fsp,
1121 bool freespace_ignore_reserved) {
1059 uintmax_t available = fsp.fsu_bavail; 1122 uintmax_t available = fsp.fsu_bavail;
1060 uintmax_t available_to_root = fsp.fsu_bfree; 1123 uintmax_t available_to_root = fsp.fsu_bfree;
1061 uintmax_t used = fsp.fsu_blocks - fsp.fsu_bfree; 1124 uintmax_t used = fsp.fsu_blocks - fsp.fsu_bfree;
@@ -1082,7 +1145,8 @@ static parameter_list_elem get_path_stats(parameter_list_elem parameters, const
1082 /* option activated : we subtract the root-reserved inodes from the total */ 1145 /* option activated : we subtract the root-reserved inodes from the total */
1083 /* not all OS report fsp->fsu_favail, only the ones with statvfs syscall */ 1146 /* not all OS report fsp->fsu_favail, only the ones with statvfs syscall */
1084 /* for others, fsp->fsu_ffree == fsp->fsu_favail */ 1147 /* for others, fsp->fsu_ffree == fsp->fsu_favail */
1085 parameters.inodes_total = fsp.fsu_files - parameters.inodes_free_to_root + parameters.inodes_free; 1148 parameters.inodes_total =
1149 fsp.fsu_files - parameters.inodes_free_to_root + parameters.inodes_free;
1086 } else { 1150 } else {
1087 /* default behaviour : take all the inodes into account */ 1151 /* default behaviour : take all the inodes into account */
1088 parameters.inodes_total = fsp.fsu_files; 1152 parameters.inodes_total = fsp.fsu_files;
@@ -1091,7 +1155,8 @@ static parameter_list_elem get_path_stats(parameter_list_elem parameters, const
1091 return parameters; 1155 return parameters;
1092} 1156}
1093 1157
1094mp_subcheck evaluate_filesystem(measurement_unit measurement_unit, bool display_inodes_perfdata, byte_unit unit) { 1158mp_subcheck evaluate_filesystem(measurement_unit measurement_unit, bool display_inodes_perfdata,
1159 byte_unit unit) {
1095 mp_subcheck result = mp_subcheck_init(); 1160 mp_subcheck result = mp_subcheck_init();
1096 result = mp_set_subcheck_default_state(result, STATE_UNKNOWN); 1161 result = mp_set_subcheck_default_state(result, STATE_UNKNOWN);
1097 xasprintf(&result.output, "%s", measurement_unit.name); 1162 xasprintf(&result.output, "%s", measurement_unit.name);
@@ -1108,10 +1173,12 @@ mp_subcheck evaluate_filesystem(measurement_unit measurement_unit, bool display_
1108 freespace_bytes_sc = mp_set_subcheck_default_state(freespace_bytes_sc, STATE_OK); 1173 freespace_bytes_sc = mp_set_subcheck_default_state(freespace_bytes_sc, STATE_OK);
1109 1174
1110 if (unit != Humanized) { 1175 if (unit != Humanized) {
1111 xasprintf(&freespace_bytes_sc.output, "Free space absolute: %ju%s (of %ju%s)", (uintmax_t)(measurement_unit.free_bytes / unit), 1176 xasprintf(&freespace_bytes_sc.output, "Free space absolute: %ju%s (of %ju%s)",
1112 get_unit_string(unit), (uintmax_t)(measurement_unit.total_bytes / unit), get_unit_string(unit)); 1177 (uintmax_t)(measurement_unit.free_bytes / unit), get_unit_string(unit),
1178 (uintmax_t)(measurement_unit.total_bytes / unit), get_unit_string(unit));
1113 } else { 1179 } else {
1114 xasprintf(&freespace_bytes_sc.output, "Free space absolute: %s (of %s)", humanize_byte_value(measurement_unit.free_bytes, false), 1180 xasprintf(&freespace_bytes_sc.output, "Free space absolute: %s (of %s)",
1181 humanize_byte_value(measurement_unit.free_bytes, false),
1115 humanize_byte_value((unsigned long long)measurement_unit.total_bytes, false)); 1182 humanize_byte_value((unsigned long long)measurement_unit.total_bytes, false));
1116 } 1183 }
1117 1184
@@ -1127,29 +1194,37 @@ mp_subcheck evaluate_filesystem(measurement_unit measurement_unit, bool display_
1127 // special case for absolute space thresholds here: 1194 // special case for absolute space thresholds here:
1128 // if absolute values are not set, compute the thresholds from percentage thresholds 1195 // if absolute values are not set, compute the thresholds from percentage thresholds
1129 mp_thresholds temp_thlds = measurement_unit.freespace_bytes_thresholds; 1196 mp_thresholds temp_thlds = measurement_unit.freespace_bytes_thresholds;
1130 if (!temp_thlds.critical_is_set && measurement_unit.freespace_percent_thresholds.critical_is_set) { 1197 if (!temp_thlds.critical_is_set &&
1198 measurement_unit.freespace_percent_thresholds.critical_is_set) {
1131 mp_range tmp_range = measurement_unit.freespace_percent_thresholds.critical; 1199 mp_range tmp_range = measurement_unit.freespace_percent_thresholds.critical;
1132 1200
1133 if (!tmp_range.end_infinity) { 1201 if (!tmp_range.end_infinity) {
1134 tmp_range.end = mp_create_pd_value(mp_get_pd_value(tmp_range.end) / 100 * measurement_unit.total_bytes); 1202 tmp_range.end = mp_create_pd_value(mp_get_pd_value(tmp_range.end) / 100 *
1203 measurement_unit.total_bytes);
1135 } 1204 }
1136 1205
1137 if (!tmp_range.start_infinity) { 1206 if (!tmp_range.start_infinity) {
1138 tmp_range.start = mp_create_pd_value(mp_get_pd_value(tmp_range.start) / 100 * measurement_unit.total_bytes); 1207 tmp_range.start = mp_create_pd_value(mp_get_pd_value(tmp_range.start) / 100 *
1208 measurement_unit.total_bytes);
1139 } 1209 }
1140 measurement_unit.freespace_bytes_thresholds = mp_thresholds_set_crit(measurement_unit.freespace_bytes_thresholds, tmp_range); 1210 measurement_unit.freespace_bytes_thresholds =
1211 mp_thresholds_set_crit(measurement_unit.freespace_bytes_thresholds, tmp_range);
1141 used_space = mp_pd_set_thresholds(used_space, measurement_unit.freespace_bytes_thresholds); 1212 used_space = mp_pd_set_thresholds(used_space, measurement_unit.freespace_bytes_thresholds);
1142 } 1213 }
1143 1214
1144 if (!temp_thlds.warning_is_set && measurement_unit.freespace_percent_thresholds.warning_is_set) { 1215 if (!temp_thlds.warning_is_set &&
1216 measurement_unit.freespace_percent_thresholds.warning_is_set) {
1145 mp_range tmp_range = measurement_unit.freespace_percent_thresholds.warning; 1217 mp_range tmp_range = measurement_unit.freespace_percent_thresholds.warning;
1146 if (!tmp_range.end_infinity) { 1218 if (!tmp_range.end_infinity) {
1147 tmp_range.end = mp_create_pd_value(mp_get_pd_value(tmp_range.end) / 100 * measurement_unit.total_bytes); 1219 tmp_range.end = mp_create_pd_value(mp_get_pd_value(tmp_range.end) / 100 *
1220 measurement_unit.total_bytes);
1148 } 1221 }
1149 if (!tmp_range.start_infinity) { 1222 if (!tmp_range.start_infinity) {
1150 tmp_range.start = mp_create_pd_value(mp_get_pd_value(tmp_range.start) / 100 * measurement_unit.total_bytes); 1223 tmp_range.start = mp_create_pd_value(mp_get_pd_value(tmp_range.start) / 100 *
1224 measurement_unit.total_bytes);
1151 } 1225 }
1152 measurement_unit.freespace_bytes_thresholds = mp_thresholds_set_warn(measurement_unit.freespace_bytes_thresholds, tmp_range); 1226 measurement_unit.freespace_bytes_thresholds =
1227 mp_thresholds_set_warn(measurement_unit.freespace_bytes_thresholds, tmp_range);
1153 used_space = mp_pd_set_thresholds(used_space, measurement_unit.freespace_bytes_thresholds); 1228 used_space = mp_pd_set_thresholds(used_space, measurement_unit.freespace_bytes_thresholds);
1154 } 1229 }
1155 1230
@@ -1161,15 +1236,18 @@ mp_subcheck evaluate_filesystem(measurement_unit measurement_unit, bool display_
1161 mp_subcheck freespace_percent_sc = mp_subcheck_init(); 1236 mp_subcheck freespace_percent_sc = mp_subcheck_init();
1162 freespace_percent_sc = mp_set_subcheck_default_state(freespace_percent_sc, STATE_OK); 1237 freespace_percent_sc = mp_set_subcheck_default_state(freespace_percent_sc, STATE_OK);
1163 1238
1164 double free_percentage = calculate_percent(measurement_unit.free_bytes, measurement_unit.total_bytes); 1239 double free_percentage =
1240 calculate_percent(measurement_unit.free_bytes, measurement_unit.total_bytes);
1165 xasprintf(&freespace_percent_sc.output, "Free space percentage: %g%%", free_percentage); 1241 xasprintf(&freespace_percent_sc.output, "Free space percentage: %g%%", free_percentage);
1166 1242
1167 // Using perfdata here just to get to the test result 1243 // Using perfdata here just to get to the test result
1168 mp_perfdata free_space_percent_pd = perfdata_init(); 1244 mp_perfdata free_space_percent_pd = perfdata_init();
1169 free_space_percent_pd.value = mp_create_pd_value(free_percentage); 1245 free_space_percent_pd.value = mp_create_pd_value(free_percentage);
1170 free_space_percent_pd = mp_pd_set_thresholds(free_space_percent_pd, measurement_unit.freespace_percent_thresholds); 1246 free_space_percent_pd =
1247 mp_pd_set_thresholds(free_space_percent_pd, measurement_unit.freespace_percent_thresholds);
1171 1248
1172 freespace_percent_sc = mp_set_subcheck_state(freespace_percent_sc, mp_get_pd_status(free_space_percent_pd)); 1249 freespace_percent_sc =
1250 mp_set_subcheck_state(freespace_percent_sc, mp_get_pd_status(free_space_percent_pd));
1173 mp_add_subcheck_to_subcheck(&result, freespace_percent_sc); 1251 mp_add_subcheck_to_subcheck(&result, freespace_percent_sc);
1174 1252
1175 // ================ 1253 // ================
@@ -1181,35 +1259,41 @@ mp_subcheck evaluate_filesystem(measurement_unit measurement_unit, bool display_
1181 mp_subcheck freeindodes_percent_sc = mp_subcheck_init(); 1259 mp_subcheck freeindodes_percent_sc = mp_subcheck_init();
1182 freeindodes_percent_sc = mp_set_subcheck_default_state(freeindodes_percent_sc, STATE_OK); 1260 freeindodes_percent_sc = mp_set_subcheck_default_state(freeindodes_percent_sc, STATE_OK);
1183 1261
1184 double free_inode_percentage = calculate_percent(measurement_unit.inodes_free, measurement_unit.inodes_total); 1262 double free_inode_percentage =
1263 calculate_percent(measurement_unit.inodes_free, measurement_unit.inodes_total);
1185 1264
1186 if (verbose > 0) { 1265 if (verbose > 0) {
1187 printf("free inode percentage computed: %g\n", free_inode_percentage); 1266 printf("free inode percentage computed: %g\n", free_inode_percentage);
1188 } 1267 }
1189 1268
1190 xasprintf(&freeindodes_percent_sc.output, "Inodes free: %g%% (%ju of %ju)", free_inode_percentage, measurement_unit.inodes_free, 1269 xasprintf(&freeindodes_percent_sc.output, "Inodes free: %g%% (%ju of %ju)",
1270 free_inode_percentage, measurement_unit.inodes_free,
1191 measurement_unit.inodes_total); 1271 measurement_unit.inodes_total);
1192 1272
1193 mp_perfdata inodes_pd = perfdata_init(); 1273 mp_perfdata inodes_pd = perfdata_init();
1194 xasprintf(&inodes_pd.label, "%s (inodes)", measurement_unit.name); 1274 xasprintf(&inodes_pd.label, "%s (inodes)", measurement_unit.name);
1195 inodes_pd = mp_set_pd_value(inodes_pd, measurement_unit.inodes_used); 1275 inodes_pd = mp_set_pd_value(inodes_pd, measurement_unit.inodes_used);
1196 inodes_pd = mp_set_pd_max_value(inodes_pd, mp_create_pd_value(measurement_unit.inodes_total)); 1276 inodes_pd =
1277 mp_set_pd_max_value(inodes_pd, mp_create_pd_value(measurement_unit.inodes_total));
1197 inodes_pd = mp_set_pd_min_value(inodes_pd, mp_create_pd_value(0)); 1278 inodes_pd = mp_set_pd_min_value(inodes_pd, mp_create_pd_value(0));
1198 1279
1199 mp_thresholds absolut_inode_thresholds = measurement_unit.freeinodes_percent_thresholds; 1280 mp_thresholds absolut_inode_thresholds = measurement_unit.freeinodes_percent_thresholds;
1200 1281
1201 if (absolut_inode_thresholds.critical_is_set) { 1282 if (absolut_inode_thresholds.critical_is_set) {
1202 absolut_inode_thresholds.critical = 1283 absolut_inode_thresholds.critical =
1203 mp_range_multiply(absolut_inode_thresholds.critical, mp_create_pd_value(measurement_unit.inodes_total / 100)); 1284 mp_range_multiply(absolut_inode_thresholds.critical,
1285 mp_create_pd_value(measurement_unit.inodes_total / 100));
1204 } 1286 }
1205 if (absolut_inode_thresholds.warning_is_set) { 1287 if (absolut_inode_thresholds.warning_is_set) {
1206 absolut_inode_thresholds.warning = 1288 absolut_inode_thresholds.warning =
1207 mp_range_multiply(absolut_inode_thresholds.warning, mp_create_pd_value(measurement_unit.inodes_total / 100)); 1289 mp_range_multiply(absolut_inode_thresholds.warning,
1290 mp_create_pd_value(measurement_unit.inodes_total / 100));
1208 } 1291 }
1209 1292
1210 inodes_pd = mp_pd_set_thresholds(inodes_pd, absolut_inode_thresholds); 1293 inodes_pd = mp_pd_set_thresholds(inodes_pd, absolut_inode_thresholds);
1211 1294
1212 freeindodes_percent_sc = mp_set_subcheck_state(freeindodes_percent_sc, mp_get_pd_status(inodes_pd)); 1295 freeindodes_percent_sc =
1296 mp_set_subcheck_state(freeindodes_percent_sc, mp_get_pd_status(inodes_pd));
1213 if (display_inodes_perfdata) { 1297 if (display_inodes_perfdata) {
1214 mp_add_perfdata_to_subcheck(&freeindodes_percent_sc, inodes_pd); 1298 mp_add_perfdata_to_subcheck(&freeindodes_percent_sc, inodes_pd);
1215 } 1299 }
diff --git a/plugins/check_disk.d/utils_disk.c b/plugins/check_disk.d/utils_disk.c
index eec1282b..0b89018d 100644
--- a/plugins/check_disk.d/utils_disk.c
+++ b/plugins/check_disk.d/utils_disk.c
@@ -126,7 +126,8 @@ bool np_find_regmatch(struct regex_list *list, const char *name) {
126 /* Emulate a full match as if surrounded with ^( )$ 126 /* Emulate a full match as if surrounded with ^( )$
127 by checking whether the match spans the whole name */ 127 by checking whether the match spans the whole name */
128 regmatch_t dummy_match; 128 regmatch_t dummy_match;
129 if (!regexec(&list->regex, name, 1, &dummy_match, 0) && dummy_match.rm_so == 0 && dummy_match.rm_eo == len) { 129 if (!regexec(&list->regex, name, 1, &dummy_match, 0) && dummy_match.rm_so == 0 &&
130 dummy_match.rm_eo == len) {
130 return true; 131 return true;
131 } 132 }
132 } 133 }
@@ -144,7 +145,8 @@ bool np_seen_name(struct name_list *list, const char *name) {
144} 145}
145 146
146bool np_regex_match_mount_entry(struct mount_entry *me, regex_t *re) { 147bool np_regex_match_mount_entry(struct mount_entry *me, regex_t *re) {
147 return ((regexec(re, me->me_devname, (size_t)0, NULL, 0) == 0) || (regexec(re, me->me_mountdir, (size_t)0, NULL, 0) == 0)); 148 return ((regexec(re, me->me_devname, (size_t)0, NULL, 0) == 0) ||
149 (regexec(re, me->me_mountdir, (size_t)0, NULL, 0) == 0));
148} 150}
149 151
150check_disk_config check_disk_config_init() { 152check_disk_config check_disk_config_init() {
@@ -264,7 +266,8 @@ measurement_unit_list *add_measurement_list(measurement_unit_list *list, measure
264 return new; 266 return new;
265} 267}
266 268
267measurement_unit add_filesystem_to_measurement_unit(measurement_unit unit, parameter_list_elem filesystem) { 269measurement_unit add_filesystem_to_measurement_unit(measurement_unit unit,
270 parameter_list_elem filesystem) {
268 271
269 unit.free_bytes += filesystem.free_bytes; 272 unit.free_bytes += filesystem.free_bytes;
270 unit.used_bytes += filesystem.used_bytes; 273 unit.used_bytes += filesystem.used_bytes;
@@ -277,7 +280,8 @@ measurement_unit add_filesystem_to_measurement_unit(measurement_unit unit, param
277 return unit; 280 return unit;
278} 281}
279 282
280measurement_unit create_measurement_unit_from_filesystem(parameter_list_elem filesystem, bool display_mntp) { 283measurement_unit create_measurement_unit_from_filesystem(parameter_list_elem filesystem,
284 bool display_mntp) {
281 measurement_unit result = measurement_unit_init(); 285 measurement_unit result = measurement_unit_init();
282 if (!display_mntp) { 286 if (!display_mntp) {
283 result.name = strdup(filesystem.best_match->me_mountdir); 287 result.name = strdup(filesystem.best_match->me_mountdir);
@@ -469,17 +473,20 @@ parameter_list_elem *mp_int_fs_list_get_next(parameter_list_elem *current) {
469 return current->next; 473 return current->next;
470} 474}
471 475
472void mp_int_fs_list_set_best_match(filesystem_list list, struct mount_entry *mount_list, bool exact) { 476void mp_int_fs_list_set_best_match(filesystem_list list, struct mount_entry *mount_list,
477 bool exact) {
473 for (parameter_list_elem *elem = list.first; elem; elem = mp_int_fs_list_get_next(elem)) { 478 for (parameter_list_elem *elem = list.first; elem; elem = mp_int_fs_list_get_next(elem)) {
474 if (!elem->best_match) { 479 if (!elem->best_match) {
475 size_t name_len = strlen(elem->name); 480 size_t name_len = strlen(elem->name);
476 struct mount_entry *best_match = NULL; 481 struct mount_entry *best_match = NULL;
477 482
478 /* set best match if path name exactly matches a mounted device name */ 483 /* set best match if path name exactly matches a mounted device name */
479 for (struct mount_entry *mount_entry = mount_list; mount_entry; mount_entry = mount_entry->me_next) { 484 for (struct mount_entry *mount_entry = mount_list; mount_entry;
485 mount_entry = mount_entry->me_next) {
480 if (strcmp(mount_entry->me_devname, elem->name) == 0) { 486 if (strcmp(mount_entry->me_devname, elem->name) == 0) {
481 struct fs_usage fsp; 487 struct fs_usage fsp;
482 if (get_fs_usage(mount_entry->me_mountdir, mount_entry->me_devname, &fsp) >= 0) { 488 if (get_fs_usage(mount_entry->me_mountdir, mount_entry->me_devname, &fsp) >=
489 0) {
483 best_match = mount_entry; 490 best_match = mount_entry;
484 } 491 }
485 } 492 }
@@ -488,15 +495,18 @@ void mp_int_fs_list_set_best_match(filesystem_list list, struct mount_entry *mou
488 /* set best match by directory name if no match was found by devname */ 495 /* set best match by directory name if no match was found by devname */
489 if (!best_match) { 496 if (!best_match) {
490 size_t best_match_len = 0; 497 size_t best_match_len = 0;
491 for (struct mount_entry *mount_entry = mount_list; mount_entry; mount_entry = mount_entry->me_next) { 498 for (struct mount_entry *mount_entry = mount_list; mount_entry;
499 mount_entry = mount_entry->me_next) {
492 size_t len = strlen(mount_entry->me_mountdir); 500 size_t len = strlen(mount_entry->me_mountdir);
493 501
494 if ((!exact && (best_match_len <= len && len <= name_len && 502 if ((!exact &&
495 (len == 1 || strncmp(mount_entry->me_mountdir, elem->name, len) == 0))) || 503 (best_match_len <= len && len <= name_len &&
504 (len == 1 || strncmp(mount_entry->me_mountdir, elem->name, len) == 0))) ||
496 (exact && strcmp(mount_entry->me_mountdir, elem->name) == 0)) { 505 (exact && strcmp(mount_entry->me_mountdir, elem->name) == 0)) {
497 struct fs_usage fsp; 506 struct fs_usage fsp;
498 507
499 if (get_fs_usage(mount_entry->me_mountdir, mount_entry->me_devname, &fsp) >= 0) { 508 if (get_fs_usage(mount_entry->me_mountdir, mount_entry->me_devname, &fsp) >=
509 0) {
500 best_match = mount_entry; 510 best_match = mount_entry;
501 best_match_len = len; 511 best_match_len = len;
502 } 512 }
@@ -507,7 +517,8 @@ void mp_int_fs_list_set_best_match(filesystem_list list, struct mount_entry *mou
507 if (best_match) { 517 if (best_match) {
508 elem->best_match = best_match; 518 elem->best_match = best_match;
509 } else { 519 } else {
510 elem->best_match = NULL; /* Not sure why this is needed as it should be null on initialisation */ 520 elem->best_match =
521 NULL; /* Not sure why this is needed as it should be null on initialisation */
511 } 522 }
512 523
513 // No filesystem without a mount_entry! 524 // No filesystem without a mount_entry!
diff --git a/plugins/check_disk.d/utils_disk.h b/plugins/check_disk.d/utils_disk.h
index 6831d1fd..c96d4296 100644
--- a/plugins/check_disk.d/utils_disk.h
+++ b/plugins/check_disk.d/utils_disk.h
@@ -141,12 +141,15 @@ parameter_list_elem *mp_int_fs_list_append(filesystem_list *list, const char *na
141parameter_list_elem *mp_int_fs_list_find(filesystem_list list, const char *name); 141parameter_list_elem *mp_int_fs_list_find(filesystem_list list, const char *name);
142parameter_list_elem *mp_int_fs_list_del(filesystem_list *list, parameter_list_elem *item); 142parameter_list_elem *mp_int_fs_list_del(filesystem_list *list, parameter_list_elem *item);
143parameter_list_elem *mp_int_fs_list_get_next(parameter_list_elem *current); 143parameter_list_elem *mp_int_fs_list_get_next(parameter_list_elem *current);
144void mp_int_fs_list_set_best_match(filesystem_list list, struct mount_entry *mount_list, bool exact); 144void mp_int_fs_list_set_best_match(filesystem_list list, struct mount_entry *mount_list,
145 bool exact);
145 146
146measurement_unit measurement_unit_init(); 147measurement_unit measurement_unit_init();
147measurement_unit_list *add_measurement_list(measurement_unit_list *list, measurement_unit elem); 148measurement_unit_list *add_measurement_list(measurement_unit_list *list, measurement_unit elem);
148measurement_unit add_filesystem_to_measurement_unit(measurement_unit unit, parameter_list_elem filesystem); 149measurement_unit add_filesystem_to_measurement_unit(measurement_unit unit,
149measurement_unit create_measurement_unit_from_filesystem(parameter_list_elem filesystem, bool display_mntp); 150 parameter_list_elem filesystem);
151measurement_unit create_measurement_unit_from_filesystem(parameter_list_elem filesystem,
152 bool display_mntp);
150 153
151int search_parameter_list(parameter_list_elem *list, const char *name); 154int search_parameter_list(parameter_list_elem *list, const char *name);
152bool np_regex_match_mount_entry(struct mount_entry *, regex_t *); 155bool np_regex_match_mount_entry(struct mount_entry *, regex_t *);
diff --git a/plugins/check_dns.c b/plugins/check_dns.c
index 95f33083..56f91dae 100644
--- a/plugins/check_dns.c
+++ b/plugins/check_dns.c
@@ -48,7 +48,8 @@ typedef struct {
48} check_dns_config_wrapper; 48} check_dns_config_wrapper;
49static check_dns_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/); 49static check_dns_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
50static check_dns_config_wrapper validate_arguments(check_dns_config_wrapper /*config_wrapper*/); 50static check_dns_config_wrapper validate_arguments(check_dns_config_wrapper /*config_wrapper*/);
51static mp_state_enum error_scan(char * /*input_buffer*/, bool * /*is_nxdomain*/, const char /*dns_server*/[ADDRESS_LENGTH]); 51static mp_state_enum error_scan(char * /*input_buffer*/, bool * /*is_nxdomain*/,
52 const char /*dns_server*/[ADDRESS_LENGTH]);
52static bool ip_match_cidr(const char * /*addr*/, const char * /*cidr_ro*/); 53static bool ip_match_cidr(const char * /*addr*/, const char * /*cidr_ro*/);
53static unsigned long ip2long(const char * /*src*/); 54static unsigned long ip2long(const char * /*src*/);
54static void print_help(void); 55static void print_help(void);
@@ -127,7 +128,8 @@ int main(int argc, char **argv) {
127 puts(chld_out.line[i]); 128 puts(chld_out.line[i]);
128 } 129 }
129 130
130 if (strcasestr(chld_out.line[i], ".in-addr.arpa") || strcasestr(chld_out.line[i], ".ip6.arpa")) { 131 if (strcasestr(chld_out.line[i], ".in-addr.arpa") ||
132 strcasestr(chld_out.line[i], ".ip6.arpa")) {
131 if ((strstr(chld_out.line[i], "canonical name = ") != NULL)) { 133 if ((strstr(chld_out.line[i], "canonical name = ") != NULL)) {
132 continue; 134 continue;
133 } 135 }
@@ -145,7 +147,8 @@ int main(int argc, char **argv) {
145 if (strstr(chld_out.line[i], "Server:") && strlen(config.dns_server) > 0) { 147 if (strstr(chld_out.line[i], "Server:") && strlen(config.dns_server) > 0) {
146 char *temp_buffer = strchr(chld_out.line[i], ':'); 148 char *temp_buffer = strchr(chld_out.line[i], ':');
147 if (temp_buffer == NULL) { 149 if (temp_buffer == NULL) {
148 die(STATE_UNKNOWN, _("'%s' returned a weirdly formatted Server line\n"), NSLOOKUP_COMMAND); 150 die(STATE_UNKNOWN, _("'%s' returned a weirdly formatted Server line\n"),
151 NSLOOKUP_COMMAND);
149 } 152 }
150 153
151 temp_buffer++; 154 temp_buffer++;
@@ -157,21 +160,25 @@ int main(int argc, char **argv) {
157 160
158 strip(temp_buffer); 161 strip(temp_buffer);
159 if (strlen(temp_buffer) == 0) { 162 if (strlen(temp_buffer) == 0) {
160 die(STATE_CRITICAL, _("DNS CRITICAL - '%s' returned empty server string\n"), NSLOOKUP_COMMAND); 163 die(STATE_CRITICAL, _("DNS CRITICAL - '%s' returned empty server string\n"),
164 NSLOOKUP_COMMAND);
161 } 165 }
162 166
163 if (strcmp(temp_buffer, config.dns_server) != 0) { 167 if (strcmp(temp_buffer, config.dns_server) != 0) {
164 die(STATE_CRITICAL, _("DNS CRITICAL - No response from DNS %s\n"), config.dns_server); 168 die(STATE_CRITICAL, _("DNS CRITICAL - No response from DNS %s\n"),
169 config.dns_server);
165 } 170 }
166 } 171 }
167 172
168 /* the server is responding, we just got the host name... */ 173 /* the server is responding, we just got the host name... */
169 if (strstr(chld_out.line[i], "Name:")) { 174 if (strstr(chld_out.line[i], "Name:")) {
170 parse_address = true; 175 parse_address = true;
171 } else if (parse_address && (strstr(chld_out.line[i], "Address:") || strstr(chld_out.line[i], "Addresses:"))) { 176 } else if (parse_address && (strstr(chld_out.line[i], "Address:") ||
177 strstr(chld_out.line[i], "Addresses:"))) {
172 char *temp_buffer = strchr(chld_out.line[i], ':'); 178 char *temp_buffer = strchr(chld_out.line[i], ':');
173 if (temp_buffer == NULL) { 179 if (temp_buffer == NULL) {
174 die(STATE_UNKNOWN, _("'%s' returned a weirdly formatted Address line\n"), NSLOOKUP_COMMAND); 180 die(STATE_UNKNOWN, _("'%s' returned a weirdly formatted Address line\n"),
181 NSLOOKUP_COMMAND);
175 } 182 }
176 183
177 temp_buffer++; 184 temp_buffer++;
@@ -183,7 +190,8 @@ int main(int argc, char **argv) {
183 190
184 strip(temp_buffer); 191 strip(temp_buffer);
185 if (strlen(temp_buffer) == 0) { 192 if (strlen(temp_buffer) == 0) {
186 die(STATE_CRITICAL, _("DNS CRITICAL - '%s' returned empty host name string\n"), NSLOOKUP_COMMAND); 193 die(STATE_CRITICAL, _("DNS CRITICAL - '%s' returned empty host name string\n"),
194 NSLOOKUP_COMMAND);
187 } 195 }
188 196
189 addresses[n_addresses++] = strdup(temp_buffer); 197 addresses[n_addresses++] = strdup(temp_buffer);
@@ -209,7 +217,8 @@ int main(int argc, char **argv) {
209 } 217 }
210 218
211 if (error_scan(chld_err.line[i], &is_nxdomain, config.dns_server) != STATE_OK) { 219 if (error_scan(chld_err.line[i], &is_nxdomain, config.dns_server) != STATE_OK) {
212 result = max_state(result, error_scan(chld_err.line[i], &is_nxdomain, config.dns_server)); 220 result =
221 max_state(result, error_scan(chld_err.line[i], &is_nxdomain, config.dns_server));
213 msg = strchr(input_buffer, ':'); 222 msg = strchr(input_buffer, ':');
214 if (msg) { 223 if (msg) {
215 msg++; 224 msg++;
@@ -242,7 +251,8 @@ int main(int argc, char **argv) {
242 } 251 }
243 *adrp = 0; 252 *adrp = 0;
244 } else { 253 } else {
245 die(STATE_CRITICAL, _("DNS CRITICAL - '%s' msg parsing exited with no address\n"), NSLOOKUP_COMMAND); 254 die(STATE_CRITICAL, _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
255 NSLOOKUP_COMMAND);
246 } 256 }
247 257
248 /* compare to expected address */ 258 /* compare to expected address */
@@ -255,7 +265,8 @@ int main(int argc, char **argv) {
255 for (size_t i = 0; i < config.expected_address_cnt; i++) { 265 for (size_t i = 0; i < config.expected_address_cnt; i++) {
256 /* check if we get a match on 'raw' ip or cidr */ 266 /* check if we get a match on 'raw' ip or cidr */
257 for (size_t j = 0; j < n_addresses; j++) { 267 for (size_t j = 0; j < n_addresses; j++) {
258 if (strcmp(addresses[j], config.expected_address[i]) == 0 || ip_match_cidr(addresses[j], config.expected_address[i])) { 268 if (strcmp(addresses[j], config.expected_address[i]) == 0 ||
269 ip_match_cidr(addresses[j], config.expected_address[i])) {
259 result = STATE_OK; 270 result = STATE_OK;
260 addr_match &= ~(1 << j); 271 addr_match &= ~(1 << j);
261 expect_match &= ~(1 << i); 272 expect_match &= ~(1 << i);
@@ -279,7 +290,8 @@ int main(int argc, char **argv) {
279 if (config.expect_nxdomain) { 290 if (config.expect_nxdomain) {
280 if (!is_nxdomain) { 291 if (!is_nxdomain) {
281 result = STATE_CRITICAL; 292 result = STATE_CRITICAL;
282 xasprintf(&msg, _("Domain '%s' was found by the server: '%s'\n"), config.query_address, address); 293 xasprintf(&msg, _("Domain '%s' was found by the server: '%s'\n"), config.query_address,
294 address);
283 } else { 295 } else {
284 if (address != NULL) { 296 if (address != NULL) {
285 free(address); 297 free(address);
@@ -291,7 +303,8 @@ int main(int argc, char **argv) {
291 /* check if authoritative */ 303 /* check if authoritative */
292 if (result == STATE_OK && config.expect_authority && non_authoritative) { 304 if (result == STATE_OK && config.expect_authority && non_authoritative) {
293 result = STATE_CRITICAL; 305 result = STATE_CRITICAL;
294 xasprintf(&msg, _("server %s is not authoritative for %s"), config.dns_server, config.query_address); 306 xasprintf(&msg, _("server %s is not authoritative for %s"), config.dns_server,
307 config.query_address);
295 } 308 }
296 309
297 long microsec = deltime(tv); 310 long microsec = deltime(tv);
@@ -306,24 +319,36 @@ int main(int argc, char **argv) {
306 } else if (result == STATE_CRITICAL) { 319 } else if (result == STATE_CRITICAL) {
307 printf("DNS %s: ", _("CRITICAL")); 320 printf("DNS %s: ", _("CRITICAL"));
308 } 321 }
309 printf(ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time); 322 printf(ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time),
323 elapsed_time);
310 printf(_(". %s returns %s"), config.query_address, address); 324 printf(_(". %s returns %s"), config.query_address, address);
311 if ((config.time_thresholds->warning != NULL) && (config.time_thresholds->critical != NULL)) { 325 if ((config.time_thresholds->warning != NULL) &&
312 printf("|%s\n", fperfdata("time", elapsed_time, "s", true, config.time_thresholds->warning->end, true, 326 (config.time_thresholds->critical != NULL)) {
327 printf("|%s\n",
328 fperfdata("time", elapsed_time, "s", true, config.time_thresholds->warning->end,
329 true, config.time_thresholds->critical->end, true, 0, false, 0));
330 } else if ((config.time_thresholds->warning == NULL) &&
331 (config.time_thresholds->critical != NULL)) {
332 printf("|%s\n", fperfdata("time", elapsed_time, "s", false, 0, true,
313 config.time_thresholds->critical->end, true, 0, false, 0)); 333 config.time_thresholds->critical->end, true, 0, false, 0));
314 } else if ((config.time_thresholds->warning == NULL) && (config.time_thresholds->critical != NULL)) { 334 } else if ((config.time_thresholds->warning != NULL) &&
315 printf("|%s\n", fperfdata("time", elapsed_time, "s", false, 0, true, config.time_thresholds->critical->end, true, 0, false, 0)); 335 (config.time_thresholds->critical == NULL)) {
316 } else if ((config.time_thresholds->warning != NULL) && (config.time_thresholds->critical == NULL)) { 336 printf("|%s\n",
317 printf("|%s\n", fperfdata("time", elapsed_time, "s", true, config.time_thresholds->warning->end, false, 0, true, 0, false, 0)); 337 fperfdata("time", elapsed_time, "s", true, config.time_thresholds->warning->end,
338 false, 0, true, 0, false, 0));
318 } else { 339 } else {
319 printf("|%s\n", fperfdata("time", elapsed_time, "s", false, 0, false, 0, true, 0, false, 0)); 340 printf("|%s\n",
341 fperfdata("time", elapsed_time, "s", false, 0, false, 0, true, 0, false, 0));
320 } 342 }
321 } else if (result == STATE_WARNING) { 343 } else if (result == STATE_WARNING) {
322 printf(_("DNS WARNING - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg); 344 printf(_("DNS WARNING - %s\n"),
345 !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg);
323 } else if (result == STATE_CRITICAL) { 346 } else if (result == STATE_CRITICAL) {
324 printf(_("DNS CRITICAL - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg); 347 printf(_("DNS CRITICAL - %s\n"),
348 !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg);
325 } else { 349 } else {
326 printf(_("DNS UNKNOWN - %s\n"), !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg); 350 printf(_("DNS UNKNOWN - %s\n"),
351 !strcmp(msg, "") ? _(" Probably a non-existent host/domain") : msg);
327 } 352 }
328 353
329 exit(result); 354 exit(result);
@@ -342,29 +367,34 @@ bool ip_match_cidr(const char *addr, const char *cidr_ro) {
342 mask = atoi(mask_c); 367 mask = atoi(mask_c);
343 368
344 /* https://www.cryptobells.com/verifying-ips-in-a-subnet-in-php/ */ 369 /* https://www.cryptobells.com/verifying-ips-in-a-subnet-in-php/ */
345 return (ip2long(addr) & ~((1 << (32 - mask)) - 1)) == (ip2long(subnet) >> (32 - mask)) << (32 - mask); 370 return (ip2long(addr) & ~((1 << (32 - mask)) - 1)) == (ip2long(subnet) >> (32 - mask))
371 << (32 - mask);
346} 372}
347 373
348unsigned long ip2long(const char *src) { 374unsigned long ip2long(const char *src) {
349 unsigned long ip[4]; 375 unsigned long ip[4];
350 /* http://computer-programming-forum.com/47-c-language/1376ffb92a12c471.htm */ 376 /* http://computer-programming-forum.com/47-c-language/1376ffb92a12c471.htm */
351 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 && 377 return (sscanf(src, "%3lu.%3lu.%3lu.%3lu", &ip[0], &ip[1], &ip[2], &ip[3]) == 4 &&
352 ip[3] < 256) 378 ip[0] < 256 && ip[1] < 256 && ip[2] < 256 && ip[3] < 256)
353 ? ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3] 379 ? ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3]
354 : 0; 380 : 0;
355} 381}
356 382
357mp_state_enum error_scan(char *input_buffer, bool *is_nxdomain, const char dns_server[ADDRESS_LENGTH]) { 383mp_state_enum error_scan(char *input_buffer, bool *is_nxdomain,
384 const char dns_server[ADDRESS_LENGTH]) {
358 385
359 const int nxdomain = strstr(input_buffer, "Non-existent") || strstr(input_buffer, "** server can't find") || 386 const int nxdomain = strstr(input_buffer, "Non-existent") ||
387 strstr(input_buffer, "** server can't find") ||
360 strstr(input_buffer, "** Can't find") || strstr(input_buffer, "NXDOMAIN"); 388 strstr(input_buffer, "** Can't find") || strstr(input_buffer, "NXDOMAIN");
361 if (nxdomain) { 389 if (nxdomain) {
362 *is_nxdomain = true; 390 *is_nxdomain = true;
363 } 391 }
364 392
365 /* the DNS lookup timed out */ 393 /* the DNS lookup timed out */
366 if (strstr(input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) || 394 if (strstr(input_buffer,
367 strstr(input_buffer, _("Consider using the `dig' or `host' programs instead. Run nslookup with")) || 395 _("Note: nslookup is deprecated and may be removed from future releases.")) ||
396 strstr(input_buffer,
397 _("Consider using the `dig' or `host' programs instead. Run nslookup with")) ||
368 strstr(input_buffer, _("the `-sil[ent]' option to prevent this message from appearing."))) { 398 strstr(input_buffer, _("the `-sil[ent]' option to prevent this message from appearing."))) {
369 return STATE_OK; 399 return STATE_OK;
370 } 400 }
@@ -382,8 +412,9 @@ mp_state_enum error_scan(char *input_buffer, bool *is_nxdomain, const char dns_s
382 } 412 }
383 413
384 /* Connection was refused */ 414 /* Connection was refused */
385 else if (strstr(input_buffer, "Connection refused") || strstr(input_buffer, "Couldn't find server") || 415 else if (strstr(input_buffer, "Connection refused") ||
386 strstr(input_buffer, "Refused") || (strstr(input_buffer, "** server can't find") && strstr(input_buffer, ": REFUSED"))) { 416 strstr(input_buffer, "Couldn't find server") || strstr(input_buffer, "Refused") ||
417 (strstr(input_buffer, "** server can't find") && strstr(input_buffer, ": REFUSED"))) {
387 die(STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server); 418 die(STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server);
388 } 419 }
389 420
@@ -504,20 +535,24 @@ check_dns_config_wrapper process_arguments(int argc, char **argv) {
504 if (strchr(optarg, ',') != NULL) { 535 if (strchr(optarg, ',') != NULL) {
505 char *comma = strchr(optarg, ','); 536 char *comma = strchr(optarg, ',');
506 while (comma != NULL) { 537 while (comma != NULL) {
507 result.config.expected_address = 538 result.config.expected_address = (char **)realloc(
508 (char **)realloc(result.config.expected_address, (result.config.expected_address_cnt + 1) * sizeof(char **)); 539 result.config.expected_address,
509 result.config.expected_address[result.config.expected_address_cnt] = strndup(optarg, comma - optarg); 540 (result.config.expected_address_cnt + 1) * sizeof(char **));
541 result.config.expected_address[result.config.expected_address_cnt] =
542 strndup(optarg, comma - optarg);
510 result.config.expected_address_cnt++; 543 result.config.expected_address_cnt++;
511 optarg = comma + 1; 544 optarg = comma + 1;
512 comma = strchr(optarg, ','); 545 comma = strchr(optarg, ',');
513 } 546 }
514 result.config.expected_address = 547 result.config.expected_address =
515 (char **)realloc(result.config.expected_address, (result.config.expected_address_cnt + 1) * sizeof(char **)); 548 (char **)realloc(result.config.expected_address,
549 (result.config.expected_address_cnt + 1) * sizeof(char **));
516 result.config.expected_address[result.config.expected_address_cnt] = strdup(optarg); 550 result.config.expected_address[result.config.expected_address_cnt] = strdup(optarg);
517 result.config.expected_address_cnt++; 551 result.config.expected_address_cnt++;
518 } else { 552 } else {
519 result.config.expected_address = 553 result.config.expected_address =
520 (char **)realloc(result.config.expected_address, (result.config.expected_address_cnt + 1) * sizeof(char **)); 554 (char **)realloc(result.config.expected_address,
555 (result.config.expected_address_cnt + 1) * sizeof(char **));
521 result.config.expected_address[result.config.expected_address_cnt] = strdup(optarg); 556 result.config.expected_address[result.config.expected_address_cnt] = strdup(optarg);
522 result.config.expected_address_cnt++; 557 result.config.expected_address_cnt++;
523 } 558 }
@@ -586,9 +621,11 @@ void print_help(void) {
586 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"); 621 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
587 printf(COPYRIGHT, copyright, email); 622 printf(COPYRIGHT, copyright, email);
588 623
589 printf("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query.")); 624 printf("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given "
625 "host/domain query."));
590 printf("%s\n", _("An optional DNS server to use may be specified.")); 626 printf("%s\n", _("An optional DNS server to use may be specified."));
591 printf("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used.")); 627 printf("%s\n", _("If no DNS server is specified, the default server(s) specified in "
628 "/etc/resolv.conf will be used."));
592 629
593 printf("\n\n"); 630 printf("\n\n");
594 631
@@ -602,11 +639,14 @@ void print_help(void) {
602 printf(" -s, --server=HOST\n"); 639 printf(" -s, --server=HOST\n");
603 printf(" %s\n", _("Optional DNS server you want to use for the lookup")); 640 printf(" %s\n", _("Optional DNS server you want to use for the lookup"));
604 printf(" -a, --expected-address=IP-ADDRESS|CIDR|HOST\n"); 641 printf(" -a, --expected-address=IP-ADDRESS|CIDR|HOST\n");
605 printf(" %s\n", _("Optional IP-ADDRESS/CIDR you expect the DNS server to return. HOST must end")); 642 printf(" %s\n",
606 printf(" %s\n", _("with a dot (.). This option can be repeated multiple times (Returns OK if any")); 643 _("Optional IP-ADDRESS/CIDR you expect the DNS server to return. HOST must end"));
644 printf(" %s\n",
645 _("with a dot (.). This option can be repeated multiple times (Returns OK if any"));
607 printf(" %s\n", _("value matches).")); 646 printf(" %s\n", _("value matches)."));
608 printf(" -n, --expect-nxdomain\n"); 647 printf(" -n, --expect-nxdomain\n");
609 printf(" %s\n", _("Expect the DNS server to return NXDOMAIN (i.e. the domain was not found)")); 648 printf(" %s\n",
649 _("Expect the DNS server to return NXDOMAIN (i.e. the domain was not found)"));
610 printf(" %s\n", _("Cannot be used together with -a")); 650 printf(" %s\n", _("Cannot be used together with -a"));
611 printf(" -A, --expect-authority\n"); 651 printf(" -A, --expect-authority\n");
612 printf(" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup")); 652 printf(" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup"));
@@ -615,7 +655,8 @@ void print_help(void) {
615 printf(" -c, --critical=seconds\n"); 655 printf(" -c, --critical=seconds\n");
616 printf(" %s\n", _("Return critical if elapsed time exceeds value. Default off")); 656 printf(" %s\n", _("Return critical if elapsed time exceeds value. Default off"));
617 printf(" -L, --all\n"); 657 printf(" -L, --all\n");
618 printf(" %s\n", _("Return critical if the list of expected addresses does not match all addresses")); 658 printf(" %s\n",
659 _("Return critical if the list of expected addresses does not match all addresses"));
619 printf(" %s\n", _("returned. Default off")); 660 printf(" %s\n", _("returned. Default off"));
620 661
621 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); 662 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
@@ -625,5 +666,7 @@ void print_help(void) {
625 666
626void print_usage(void) { 667void print_usage(void) {
627 printf("%s\n", _("Usage:")); 668 printf("%s\n", _("Usage:"));
628 printf("%s -H host [-s server] [-a expected-address] [-n] [-A] [-t timeout] [-w warn] [-c crit] [-L]\n", progname); 669 printf("%s -H host [-s server] [-a expected-address] [-n] [-A] [-t timeout] [-w warn] [-c "
670 "crit] [-L]\n",
671 progname);
629} 672}
diff --git a/plugins/check_dummy.c b/plugins/check_dummy.c
index 19f6c046..602d5868 100644
--- a/plugins/check_dummy.c
+++ b/plugins/check_dummy.c
@@ -45,18 +45,19 @@ int main(int argc, char **argv) {
45 bindtextdomain(PACKAGE, LOCALEDIR); 45 bindtextdomain(PACKAGE, LOCALEDIR);
46 textdomain(PACKAGE); 46 textdomain(PACKAGE);
47 47
48 if (argc < 2) 48 if (argc < 2) {
49 usage4(_("Could not parse arguments")); 49 usage4(_("Could not parse arguments"));
50 else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0) { 50 } else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0) {
51 print_revision(progname, NP_VERSION); 51 print_revision(progname, NP_VERSION);
52 exit(STATE_UNKNOWN); 52 exit(STATE_UNKNOWN);
53 } else if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) { 53 } else if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) {
54 print_help(); 54 print_help();
55 exit(STATE_UNKNOWN); 55 exit(STATE_UNKNOWN);
56 } else if (!is_integer(argv[1])) 56 } else if (!is_integer(argv[1])) {
57 usage4(_("Arguments to check_dummy must be an integer")); 57 usage4(_("Arguments to check_dummy must be an integer"));
58 else 58 } else {
59 result = atoi(argv[1]); 59 result = atoi(argv[1]);
60 }
60 61
61 switch (result) { 62 switch (result) {
62 case STATE_OK: 63 case STATE_OK:
@@ -78,8 +79,9 @@ int main(int argc, char **argv) {
78 return STATE_UNKNOWN; 79 return STATE_UNKNOWN;
79 } 80 }
80 81
81 if (argc >= 3) 82 if (argc >= 3) {
82 printf(": %s", argv[2]); 83 printf(": %s", argv[2]);
84 }
83 85
84 printf("\n"); 86 printf("\n");
85 87
@@ -92,7 +94,8 @@ void print_help(void) {
92 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"); 94 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
93 printf(COPYRIGHT, copyright, email); 95 printf(COPYRIGHT, copyright, email);
94 96
95 printf("%s\n", _("This plugin will simply return the state corresponding to the numeric value")); 97 printf("%s\n",
98 _("This plugin will simply return the state corresponding to the numeric value"));
96 99
97 printf("%s\n", _("of the <state> argument with optional text")); 100 printf("%s\n", _("of the <state> argument with optional text"));
98 101
diff --git a/plugins/check_fping.c b/plugins/check_fping.c
index 8018e06d..6160c2cb 100644
--- a/plugins/check_fping.c
+++ b/plugins/check_fping.c
@@ -46,8 +46,9 @@ enum {
46 RTA = 1 46 RTA = 1
47}; 47};
48 48
49static mp_state_enum textscan(char *buf, const char * /*server_name*/, bool /*crta_p*/, double /*crta*/, bool /*wrta_p*/, double /*wrta*/, 49static mp_state_enum textscan(char *buf, const char * /*server_name*/, bool /*crta_p*/,
50 bool /*cpl_p*/, int /*cpl*/, bool /*wpl_p*/, int /*wpl*/, bool /*alive_p*/); 50 double /*crta*/, bool /*wrta_p*/, double /*wrta*/, bool /*cpl_p*/,
51 int /*cpl*/, bool /*wpl_p*/, int /*wpl*/, bool /*alive_p*/);
51 52
52typedef struct { 53typedef struct {
53 int errorcode; 54 int errorcode;
@@ -133,9 +134,11 @@ int main(int argc, char **argv) {
133 134
134 if (config.icmp_timestamp) { 135 if (config.icmp_timestamp) {
135 // no packet size settable for ICMP timestamp 136 // no packet size settable for ICMP timestamp
136 xasprintf(&command_line, "%s %s -c %d %s", fping_prog, option_string, config.packet_count, server); 137 xasprintf(&command_line, "%s %s -c %d %s", fping_prog, option_string, config.packet_count,
138 server);
137 } else { 139 } else {
138 xasprintf(&command_line, "%s %s-b %d -c %d %s", fping_prog, option_string, config.packet_size, config.packet_count, server); 140 xasprintf(&command_line, "%s %s-b %d -c %d %s", fping_prog, option_string,
141 config.packet_size, config.packet_count, server);
139 } 142 }
140 143
141 if (verbose) { 144 if (verbose) {
@@ -160,8 +163,9 @@ int main(int argc, char **argv) {
160 if (verbose) { 163 if (verbose) {
161 printf("%s", input_buffer); 164 printf("%s", input_buffer);
162 } 165 }
163 status = max_state(status, textscan(input_buffer, config.server_name, config.crta_p, config.crta, config.wrta_p, config.wrta, 166 status = max_state(status, textscan(input_buffer, config.server_name, config.crta_p,
164 config.cpl_p, config.cpl, config.wpl_p, config.wpl, config.alive_p)); 167 config.crta, config.wrta_p, config.wrta, config.cpl_p,
168 config.cpl, config.wpl_p, config.wpl, config.alive_p));
165 } 169 }
166 170
167 /* If we get anything on STDERR, at least set warning */ 171 /* If we get anything on STDERR, at least set warning */
@@ -170,8 +174,9 @@ int main(int argc, char **argv) {
170 if (verbose) { 174 if (verbose) {
171 printf("%s", input_buffer); 175 printf("%s", input_buffer);
172 } 176 }
173 status = max_state(status, textscan(input_buffer, config.server_name, config.crta_p, config.crta, config.wrta_p, config.wrta, 177 status = max_state(status, textscan(input_buffer, config.server_name, config.crta_p,
174 config.cpl_p, config.cpl, config.wpl_p, config.wpl, config.alive_p)); 178 config.crta, config.wrta_p, config.wrta, config.cpl_p,
179 config.cpl, config.wpl_p, config.wpl, config.alive_p));
175 } 180 }
176 (void)fclose(child_stderr); 181 (void)fclose(child_stderr);
177 182
@@ -200,8 +205,8 @@ int main(int argc, char **argv) {
200 return status; 205 return status;
201} 206}
202 207
203mp_state_enum textscan(char *buf, const char *server_name, bool crta_p, double crta, bool wrta_p, double wrta, bool cpl_p, int cpl, 208mp_state_enum textscan(char *buf, const char *server_name, bool crta_p, double crta, bool wrta_p,
204 bool wpl_p, int wpl, bool alive_p) { 209 double wrta, bool cpl_p, int cpl, bool wpl_p, int wpl, bool alive_p) {
205 /* stops testing after the first successful reply. */ 210 /* stops testing after the first successful reply. */
206 double rta; 211 double rta;
207 double loss; 212 double loss;
@@ -214,7 +219,8 @@ mp_state_enum textscan(char *buf, const char *server_name, bool crta_p, double c
214 die(STATE_OK, _("FPING %s - %s (rta=%f ms)|%s\n"), state_text(STATE_OK), server_name, rta, 219 die(STATE_OK, _("FPING %s - %s (rta=%f ms)|%s\n"), state_text(STATE_OK), server_name, rta,
215 /* No loss since we only waited for the first reply 220 /* No loss since we only waited for the first reply
216 perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100), */ 221 perfdata ("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, true, 0, true, 100), */
217 fperfdata("rta", rta / 1.0e3, "s", wrta_p, wrta / 1.0e3, crta_p, crta / 1.0e3, true, 0, false, 0)); 222 fperfdata("rta", rta / 1.0e3, "s", wrta_p, wrta / 1.0e3, crta_p, crta / 1.0e3, true, 0,
223 false, 0));
218 } 224 }
219 225
220 mp_state_enum status = STATE_UNKNOWN; 226 mp_state_enum status = STATE_UNKNOWN;
@@ -255,9 +261,11 @@ mp_state_enum textscan(char *buf, const char *server_name, bool crta_p, double c
255 } else { 261 } else {
256 status = STATE_OK; 262 status = STATE_OK;
257 } 263 }
258 die(status, _("FPING %s - %s (loss=%.0f%%, rta=%f ms)|%s %s\n"), state_text(status), server_name, loss, rta, 264 die(status, _("FPING %s - %s (loss=%.0f%%, rta=%f ms)|%s %s\n"), state_text(status),
265 server_name, loss, rta,
259 perfdata("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, false, 0, false, 0), 266 perfdata("loss", (long int)loss, "%", wpl_p, wpl, cpl_p, cpl, false, 0, false, 0),
260 fperfdata("rta", rta / 1.0e3, "s", wrta_p, wrta / 1.0e3, crta_p, crta / 1.0e3, true, 0, false, 0)); 267 fperfdata("rta", rta / 1.0e3, "s", wrta_p, wrta / 1.0e3, crta_p, crta / 1.0e3, true, 0,
268 false, 0));
261 269
262 } else if (strstr(buf, "xmt/rcv/%loss")) { 270 } else if (strstr(buf, "xmt/rcv/%loss")) {
263 /* no min/max/avg if host was unreachable in fping v2.2.b1 */ 271 /* no min/max/avg if host was unreachable in fping v2.2.b1 */
@@ -350,7 +358,8 @@ check_fping_config_wrapper process_arguments(int argc, char **argv) {
350 } 358 }
351 359
352 while (true) { 360 while (true) {
353 int option_index = getopt_long(argc, argv, "+hVvaH:S:c:w:b:n:T:i:I:M:R:46", longopts, &option); 361 int option_index =
362 getopt_long(argc, argv, "+hVvaH:S:c:w:b:n:T:i:I:M:R:46", longopts, &option);
354 363
355 if (option_index == -1 || option_index == EOF || option_index == 1) { 364 if (option_index == -1 || option_index == EOF || option_index == 1) {
356 break; 365 break;
@@ -487,10 +496,12 @@ int get_threshold(char *arg, char *rv[2]) {
487 if (arg2) { 496 if (arg2) {
488 arg1[strcspn(arg1, ",:")] = 0; 497 arg1[strcspn(arg1, ",:")] = 0;
489 if (strstr(arg1, "%") && strstr(arg2, "%")) { 498 if (strstr(arg1, "%") && strstr(arg2, "%")) {
490 die(STATE_UNKNOWN, _("%s: Only one threshold may be packet loss (%s)\n"), progname, arg); 499 die(STATE_UNKNOWN, _("%s: Only one threshold may be packet loss (%s)\n"), progname,
500 arg);
491 } 501 }
492 if (!strstr(arg1, "%") && !strstr(arg2, "%")) { 502 if (!strstr(arg1, "%") && !strstr(arg2, "%")) {
493 die(STATE_UNKNOWN, _("%s: Only one threshold must be packet loss (%s)\n"), progname, arg); 503 die(STATE_UNKNOWN, _("%s: Only one threshold must be packet loss (%s)\n"), progname,
504 arg);
494 } 505 }
495 } 506 }
496 507
@@ -516,7 +527,8 @@ void print_help(void) {
516 printf("Copyright (c) 1999 Didi Rieder <adrieder@sbox.tu-graz.ac.at>\n"); 527 printf("Copyright (c) 1999 Didi Rieder <adrieder@sbox.tu-graz.ac.at>\n");
517 printf(COPYRIGHT, copyright, email); 528 printf(COPYRIGHT, copyright, email);
518 529
519 printf("%s\n", _("This plugin will use the fping command to ping the specified host for a fast check")); 530 printf("%s\n",
531 _("This plugin will use the fping command to ping the specified host for a fast check"));
520 532
521 printf("%s\n", _("Note that it is necessary to set the suid flag on fping.")); 533 printf("%s\n", _("Note that it is necessary to set the suid flag on fping."));
522 534
@@ -530,7 +542,8 @@ void print_help(void) {
530 printf(UT_IPv46); 542 printf(UT_IPv46);
531 543
532 printf(" %s\n", "-H, --hostname=HOST"); 544 printf(" %s\n", "-H, --hostname=HOST");
533 printf(" %s\n", _("name or IP Address of host to ping (IP Address bypasses name lookup, reducing system load)")); 545 printf(" %s\n", _("name or IP Address of host to ping (IP Address bypasses name lookup, "
546 "reducing system load)"));
534 printf(" %s\n", "-w, --warning=THRESHOLD"); 547 printf(" %s\n", "-w, --warning=THRESHOLD");
535 printf(" %s\n", _("warning threshold pair")); 548 printf(" %s\n", _("warning threshold pair"));
536 printf(" %s\n", "-c, --critical=THRESHOLD"); 549 printf(" %s\n", "-c, --critical=THRESHOLD");
@@ -544,7 +557,8 @@ void print_help(void) {
544 printf(" %s\n", "-T, --target-timeout=INTEGER"); 557 printf(" %s\n", "-T, --target-timeout=INTEGER");
545 printf(" %s (default: fping's default for -t)\n", _("Target timeout (ms)")); 558 printf(" %s (default: fping's default for -t)\n", _("Target timeout (ms)"));
546 printf(" %s\n", "-i, --interval=INTEGER"); 559 printf(" %s\n", "-i, --interval=INTEGER");
547 printf(" %s (default: fping's default for -p)\n", _("Interval (ms) between sending packets")); 560 printf(" %s (default: fping's default for -p)\n",
561 _("Interval (ms) between sending packets"));
548 printf(" %s\n", "-S, --sourceip=HOST"); 562 printf(" %s\n", "-S, --sourceip=HOST");
549 printf(" %s\n", _("name or IP Address of sourceip")); 563 printf(" %s\n", _("name or IP Address of sourceip"));
550 printf(" %s\n", "-I, --sourceif=IF"); 564 printf(" %s\n", "-I, --sourceif=IF");
@@ -565,7 +579,8 @@ void print_help(void) {
565#endif 579#endif
566 printf(UT_VERBOSE); 580 printf(UT_VERBOSE);
567 printf("\n"); 581 printf("\n");
568 printf(" %s\n", _("THRESHOLD is <rta>,<pl>%% where <rta> is the round trip average travel time (ms)")); 582 printf(" %s\n",
583 _("THRESHOLD is <rta>,<pl>%% where <rta> is the round trip average travel time (ms)"));
569 printf(" %s\n", _("which triggers a WARNING or CRITICAL state, and <pl> is the percentage of")); 584 printf(" %s\n", _("which triggers a WARNING or CRITICAL state, and <pl> is the percentage of"));
570 printf(" %s\n", _("packet loss to trigger an alarm state.")); 585 printf(" %s\n", _("packet loss to trigger an alarm state."));
571 586
@@ -577,5 +592,6 @@ void print_help(void) {
577 592
578void print_usage(void) { 593void print_usage(void) {
579 printf("%s\n", _("Usage:")); 594 printf("%s\n", _("Usage:"));
580 printf(" %s <host_address> -w limit -c limit [-b size] [-n number] [-T number] [-i number]\n", progname); 595 printf(" %s <host_address> -w limit -c limit [-b size] [-n number] [-T number] [-i number]\n",
596 progname);
581} 597}
diff --git a/plugins/check_fping.d/config.h b/plugins/check_fping.d/config.h
index d95e9ded..d3e50565 100644
--- a/plugins/check_fping.d/config.h
+++ b/plugins/check_fping.d/config.h
@@ -36,7 +36,6 @@ typedef struct {
36 unsigned int fwmark; 36 unsigned int fwmark;
37 bool fwmark_set; 37 bool fwmark_set;
38 38
39
40 // only available with fping version >= 5.3 39 // only available with fping version >= 5.3
41 // Setting icmp_timestamp tells fping to use ICMP Timestamp (ICMP type 13) instead 40 // Setting icmp_timestamp tells fping to use ICMP Timestamp (ICMP type 13) instead
42 // of ICMP Echo 41 // of ICMP Echo
diff --git a/plugins/check_game.c b/plugins/check_game.c
index c0193b03..974a7253 100644
--- a/plugins/check_game.c
+++ b/plugins/check_game.c
@@ -77,7 +77,8 @@ int main(int argc, char **argv) {
77 77
78 /* create the command line to execute */ 78 /* create the command line to execute */
79 char *command_line = NULL; 79 char *command_line = NULL;
80 xasprintf(&command_line, "%s -raw %s -%s %s", PATH_TO_QSTAT, QSTAT_DATA_DELIMITER, config.game_type, config.server_ip); 80 xasprintf(&command_line, "%s -raw %s -%s %s", PATH_TO_QSTAT, QSTAT_DATA_DELIMITER,
81 config.game_type, config.server_ip);
81 82
82 if (config.port) { 83 if (config.port) {
83 xasprintf(&command_line, "%s:%-d", command_line, config.port); 84 xasprintf(&command_line, "%s:%-d", command_line, config.port);
@@ -130,11 +131,13 @@ int main(int argc, char **argv) {
130 printf(_("CRITICAL - Game server timeout\n")); 131 printf(_("CRITICAL - Game server timeout\n"));
131 result = STATE_CRITICAL; 132 result = STATE_CRITICAL;
132 } else { 133 } else {
133 printf("OK: %s/%s %s (%s), Ping: %s ms|%s %s\n", ret[config.qstat_game_players], ret[config.qstat_game_players_max], 134 printf("OK: %s/%s %s (%s), Ping: %s ms|%s %s\n", ret[config.qstat_game_players],
134 ret[config.qstat_game_field], ret[config.qstat_map_field], ret[config.qstat_ping_field], 135 ret[config.qstat_game_players_max], ret[config.qstat_game_field],
135 perfdata("players", atol(ret[config.qstat_game_players]), "", false, 0, false, 0, true, 0, true, 136 ret[config.qstat_map_field], ret[config.qstat_ping_field],
136 atol(ret[config.qstat_game_players_max])), 137 perfdata("players", atol(ret[config.qstat_game_players]), "", false, 0, false, 0,
137 fperfdata("ping", strtod(ret[config.qstat_ping_field], NULL), "", false, 0, false, 0, true, 0, false, 0)); 138 true, 0, true, atol(ret[config.qstat_game_players_max])),
139 fperfdata("ping", strtod(ret[config.qstat_ping_field], NULL), "", false, 0, false, 0,
140 true, 0, false, 0));
138 } 141 }
139 142
140 exit(result); 143 exit(result);
@@ -144,19 +147,20 @@ int main(int argc, char **argv) {
144#define max_players_field_index 130 147#define max_players_field_index 130
145 148
146check_game_config_wrapper process_arguments(int argc, char **argv) { 149check_game_config_wrapper process_arguments(int argc, char **argv) {
147 static struct option long_opts[] = {{"help", no_argument, 0, 'h'}, 150 static struct option long_opts[] = {
148 {"version", no_argument, 0, 'V'}, 151 {"help", no_argument, 0, 'h'},
149 {"verbose", no_argument, 0, 'v'}, 152 {"version", no_argument, 0, 'V'},
150 {"timeout", required_argument, 0, 't'}, 153 {"verbose", no_argument, 0, 'v'},
151 {"hostname", required_argument, 0, 'H'}, 154 {"timeout", required_argument, 0, 't'},
152 {"port", required_argument, 0, 'P'}, 155 {"hostname", required_argument, 0, 'H'},
153 {"game-type", required_argument, 0, 'G'}, 156 {"port", required_argument, 0, 'P'},
154 {"map-field", required_argument, 0, 'm'}, 157 {"game-type", required_argument, 0, 'G'},
155 {"ping-field", required_argument, 0, 'p'}, 158 {"map-field", required_argument, 0, 'm'},
156 {"game-field", required_argument, 0, 'g'}, 159 {"ping-field", required_argument, 0, 'p'},
157 {"players-field", required_argument, 0, players_field_index}, 160 {"game-field", required_argument, 0, 'g'},
158 {"max-players-field", required_argument, 0, max_players_field_index}, 161 {"players-field", required_argument, 0, players_field_index},
159 {0, 0, 0, 0}}; 162 {"max-players-field", required_argument, 0, max_players_field_index},
163 {0, 0, 0, 0}};
160 164
161 check_game_config_wrapper result = { 165 check_game_config_wrapper result = {
162 .config = check_game_config_init(), 166 .config = check_game_config_init(),
@@ -216,21 +220,24 @@ check_game_config_wrapper process_arguments(int argc, char **argv) {
216 break; 220 break;
217 case 'p': /* index of ping field */ 221 case 'p': /* index of ping field */
218 result.config.qstat_ping_field = atoi(optarg); 222 result.config.qstat_ping_field = atoi(optarg);
219 if (result.config.qstat_ping_field < 0 || result.config.qstat_ping_field > QSTAT_MAX_RETURN_ARGS) { 223 if (result.config.qstat_ping_field < 0 ||
224 result.config.qstat_ping_field > QSTAT_MAX_RETURN_ARGS) {
220 result.errorcode = ERROR; 225 result.errorcode = ERROR;
221 return result; 226 return result;
222 } 227 }
223 break; 228 break;
224 case 'm': /* index on map field */ 229 case 'm': /* index on map field */
225 result.config.qstat_map_field = atoi(optarg); 230 result.config.qstat_map_field = atoi(optarg);
226 if (result.config.qstat_map_field < 0 || result.config.qstat_map_field > QSTAT_MAX_RETURN_ARGS) { 231 if (result.config.qstat_map_field < 0 ||
232 result.config.qstat_map_field > QSTAT_MAX_RETURN_ARGS) {
227 result.errorcode = ERROR; 233 result.errorcode = ERROR;
228 return result; 234 return result;
229 } 235 }
230 break; 236 break;
231 case 'g': /* index of game field */ 237 case 'g': /* index of game field */
232 result.config.qstat_game_field = atoi(optarg); 238 result.config.qstat_game_field = atoi(optarg);
233 if (result.config.qstat_game_field < 0 || result.config.qstat_game_field > QSTAT_MAX_RETURN_ARGS) { 239 if (result.config.qstat_game_field < 0 ||
240 result.config.qstat_game_field > QSTAT_MAX_RETURN_ARGS) {
234 result.errorcode = ERROR; 241 result.errorcode = ERROR;
235 return result; 242 return result;
236 } 243 }
@@ -240,14 +247,16 @@ check_game_config_wrapper process_arguments(int argc, char **argv) {
240 if (result.config.qstat_game_players_max == 0) { 247 if (result.config.qstat_game_players_max == 0) {
241 result.config.qstat_game_players_max = result.config.qstat_game_players - 1; 248 result.config.qstat_game_players_max = result.config.qstat_game_players - 1;
242 } 249 }
243 if (result.config.qstat_game_players < 0 || result.config.qstat_game_players > QSTAT_MAX_RETURN_ARGS) { 250 if (result.config.qstat_game_players < 0 ||
251 result.config.qstat_game_players > QSTAT_MAX_RETURN_ARGS) {
244 result.errorcode = ERROR; 252 result.errorcode = ERROR;
245 return result; 253 return result;
246 } 254 }
247 break; 255 break;
248 case max_players_field_index: /* index of max players field */ 256 case max_players_field_index: /* index of max players field */
249 result.config.qstat_game_players_max = atoi(optarg); 257 result.config.qstat_game_players_max = atoi(optarg);
250 if (result.config.qstat_game_players_max < 0 || result.config.qstat_game_players_max > QSTAT_MAX_RETURN_ARGS) { 258 if (result.config.qstat_game_players_max < 0 ||
259 result.config.qstat_game_players_max > QSTAT_MAX_RETURN_ARGS) {
251 result.errorcode = ERROR; 260 result.errorcode = ERROR;
252 return result; 261 return result;
253 } 262 }
@@ -286,7 +295,7 @@ void print_help(void) {
286 printf(UT_HELP_VRSN); 295 printf(UT_HELP_VRSN);
287 printf(UT_EXTRA_OPTS); 296 printf(UT_EXTRA_OPTS);
288 printf(" -H, --hostname=ADDRESS\n" 297 printf(" -H, --hostname=ADDRESS\n"
289 " Host name, IP Address, or unix socket (must be an absolute path)\n"); 298 " Host name, IP Address, or unix socket (must be an absolute path)\n");
290 printf(" %s\n", "-P"); 299 printf(" %s\n", "-P");
291 printf(" %s\n", _("Optional port to connect to")); 300 printf(" %s\n", _("Optional port to connect to"));
292 printf(" %s\n", "-g"); 301 printf(" %s\n", "-g");
@@ -300,8 +309,10 @@ void print_help(void) {
300 309
301 printf("\n"); 310 printf("\n");
302 printf("%s\n", _("Notes:")); 311 printf("%s\n", _("Notes:"));
303 printf(" %s\n", _("This plugin uses the 'qstat' command, the popular game server status query tool.")); 312 printf(" %s\n",
304 printf(" %s\n", _("If you don't have the package installed, you will need to download it from")); 313 _("This plugin uses the 'qstat' command, the popular game server status query tool."));
314 printf(" %s\n",
315 _("If you don't have the package installed, you will need to download it from"));
305 printf(" %s\n", _("https://github.com/multiplay/qstat before you can use this plugin.")); 316 printf(" %s\n", _("https://github.com/multiplay/qstat before you can use this plugin."));
306 317
307 printf(UT_SUPPORT); 318 printf(UT_SUPPORT);
@@ -309,7 +320,8 @@ void print_help(void) {
309 320
310void print_usage(void) { 321void print_usage(void) {
311 printf("%s\n", _("Usage:")); 322 printf("%s\n", _("Usage:"));
312 printf(" %s [-hvV] [-P port] [-t timeout] [-g game_field] [-m map_field] [-p ping_field] [-G game-time] [-H hostname] <game> " 323 printf(" %s [-hvV] [-P port] [-t timeout] [-g game_field] [-m map_field] [-p ping_field] [-G "
324 "game-time] [-H hostname] <game> "
313 "<ip_address>\n", 325 "<ip_address>\n",
314 progname); 326 progname);
315} 327}
diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c
index 62417fd6..9907abc5 100644
--- a/plugins/check_hpjd.c
+++ b/plugins/check_hpjd.c
@@ -85,13 +85,16 @@ int main(int argc, char **argv) {
85 char query_string[512]; 85 char query_string[512];
86 /* removed ' 2>1' at end of command 10/27/1999 - EG */ 86 /* removed ' 2>1' at end of command 10/27/1999 - EG */
87 /* create the query string */ 87 /* create the query string */
88 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, 88 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",
89 HPJD_INTERVENTION_REQUIRED, HPJD_GD_PERIPHERAL_ERROR, HPJD_GD_PAPER_JAM, HPJD_GD_PAPER_OUT, HPJD_GD_TONER_LOW, 89 HPJD_LINE_STATUS, HPJD_PAPER_STATUS, HPJD_INTERVENTION_REQUIRED,
90 HPJD_GD_PAGE_PUNT, HPJD_GD_MEMORY_OUT, HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT, HPJD_GD_STATUS_DISPLAY); 90 HPJD_GD_PERIPHERAL_ERROR, HPJD_GD_PAPER_JAM, HPJD_GD_PAPER_OUT, HPJD_GD_TONER_LOW,
91 HPJD_GD_PAGE_PUNT, HPJD_GD_MEMORY_OUT, HPJD_GD_DOOR_OPEN, HPJD_GD_PAPER_OUTPUT,
92 HPJD_GD_STATUS_DISPLAY);
91 93
92 /* get the command to run */ 94 /* get the command to run */
93 char command_line[1024]; 95 char command_line[1024];
94 sprintf(command_line, "%s -OQa -m : -v 1 -c %s %s:%u %s", PATH_TO_SNMPGET, config.community, config.address, config.port, query_string); 96 sprintf(command_line, "%s -OQa -m : -v 1 -c %s %s:%u %s", PATH_TO_SNMPGET, config.community,
97 config.address, config.port, query_string);
95 98
96 /* run the command */ 99 /* run the command */
97 child_process = spopen(command_line); 100 child_process = spopen(command_line);
@@ -177,7 +180,8 @@ int main(int argc, char **argv) {
177 strcpy(display_message, temp_buffer + 1); 180 strcpy(display_message, temp_buffer + 1);
178 break; 181 break;
179 default: /* fold multiline message */ 182 default: /* fold multiline message */
180 strncat(display_message, input_buffer, sizeof(display_message) - strlen(display_message) - 1); 183 strncat(display_message, input_buffer,
184 sizeof(display_message) - strlen(display_message) - 1);
181 } 185 }
182 } 186 }
183 187
diff --git a/plugins/check_ldap.c b/plugins/check_ldap.c
index 597644bd..77a33304 100644
--- a/plugins/check_ldap.c
+++ b/plugins/check_ldap.c
@@ -108,7 +108,8 @@ int main(int argc, char *argv[]) {
108 108
109#ifdef HAVE_LDAP_SET_OPTION 109#ifdef HAVE_LDAP_SET_OPTION
110 /* set ldap options */ 110 /* set ldap options */
111 if (ldap_set_option(ldap_connection, LDAP_OPT_PROTOCOL_VERSION, &config.ld_protocol) != LDAP_OPT_SUCCESS) { 111 if (ldap_set_option(ldap_connection, LDAP_OPT_PROTOCOL_VERSION, &config.ld_protocol) !=
112 LDAP_OPT_SUCCESS) {
112 printf(_("Could not set protocol version %d\n"), config.ld_protocol); 113 printf(_("Could not set protocol version %d\n"), config.ld_protocol);
113 return STATE_CRITICAL; 114 return STATE_CRITICAL;
114 } 115 }
@@ -135,7 +136,8 @@ int main(int argc, char *argv[]) {
135 } else if (config.starttls) { 136 } else if (config.starttls) {
136#if defined(HAVE_LDAP_SET_OPTION) && defined(HAVE_LDAP_START_TLS_S) 137#if defined(HAVE_LDAP_SET_OPTION) && defined(HAVE_LDAP_START_TLS_S)
137 /* ldap with startTLS: set option version */ 138 /* ldap with startTLS: set option version */
138 if (ldap_get_option(ldap_connection, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS) { 139 if (ldap_get_option(ldap_connection, LDAP_OPT_PROTOCOL_VERSION, &version) ==
140 LDAP_OPT_SUCCESS) {
139 if (version < LDAP_VERSION3) { 141 if (version < LDAP_VERSION3) {
140 version = LDAP_VERSION3; 142 version = LDAP_VERSION3;
141 ldap_set_option(ldap_connection, LDAP_OPT_PROTOCOL_VERSION, &version); 143 ldap_set_option(ldap_connection, LDAP_OPT_PROTOCOL_VERSION, &version);
@@ -156,7 +158,8 @@ int main(int argc, char *argv[]) {
156 } 158 }
157 159
158 /* bind to the ldap server */ 160 /* bind to the ldap server */
159 if (ldap_bind_s(ldap_connection, config.ld_binddn, config.ld_passwd, LDAP_AUTH_SIMPLE) != LDAP_SUCCESS) { 161 if (ldap_bind_s(ldap_connection, config.ld_binddn, config.ld_passwd, LDAP_AUTH_SIMPLE) !=
162 LDAP_SUCCESS) {
160 if (verbose) { 163 if (verbose) {
161 ldap_perror(ldap_connection, "ldap_bind"); 164 ldap_perror(ldap_connection, "ldap_bind");
162 } 165 }
@@ -168,8 +171,10 @@ int main(int argc, char *argv[]) {
168 int num_entries = 0; 171 int num_entries = 0;
169 /* do a search of all objectclasses in the base dn */ 172 /* do a search of all objectclasses in the base dn */
170 if (ldap_search_s(ldap_connection, config.ld_base, 173 if (ldap_search_s(ldap_connection, config.ld_base,
171 (config.crit_entries != NULL || config.warn_entries != NULL) ? LDAP_SCOPE_SUBTREE : LDAP_SCOPE_BASE, config.ld_attr, 174 (config.crit_entries != NULL || config.warn_entries != NULL)
172 NULL, 0, &result) != LDAP_SUCCESS) { 175 ? LDAP_SCOPE_SUBTREE
176 : LDAP_SCOPE_BASE,
177 config.ld_attr, NULL, 0, &result) != LDAP_SUCCESS) {
173 if (verbose) { 178 if (verbose) {
174 ldap_perror(ldap_connection, "ldap_search"); 179 ldap_perror(ldap_connection, "ldap_search");
175 } 180 }
@@ -215,14 +220,16 @@ int main(int argc, char *argv[]) {
215 220
216 /* print out the result */ 221 /* print out the result */
217 if (config.crit_entries != NULL || config.warn_entries != NULL) { 222 if (config.crit_entries != NULL || config.warn_entries != NULL) {
218 printf(_("LDAP %s - found %d entries in %.3f seconds|%s %s\n"), state_text(status), num_entries, elapsed_time, 223 printf(_("LDAP %s - found %d entries in %.3f seconds|%s %s\n"), state_text(status),
219 fperfdata("time", elapsed_time, "s", config.warn_time_set, config.warn_time, config.crit_time_set, config.crit_time, true, 0, 224 num_entries, elapsed_time,
220 false, 0), 225 fperfdata("time", elapsed_time, "s", config.warn_time_set, config.warn_time,
221 sperfdata("entries", (double)num_entries, "", config.warn_entries, config.crit_entries, true, 0.0, false, 0.0)); 226 config.crit_time_set, config.crit_time, true, 0, false, 0),
227 sperfdata("entries", (double)num_entries, "", config.warn_entries,
228 config.crit_entries, true, 0.0, false, 0.0));
222 } else { 229 } else {
223 printf(_("LDAP %s - %.3f seconds response time|%s\n"), state_text(status), elapsed_time, 230 printf(_("LDAP %s - %.3f seconds response time|%s\n"), state_text(status), elapsed_time,
224 fperfdata("time", elapsed_time, "s", config.warn_time_set, config.warn_time, config.crit_time_set, config.crit_time, true, 0, 231 fperfdata("time", elapsed_time, "s", config.warn_time_set, config.warn_time,
225 false, 0)); 232 config.crit_time_set, config.crit_time, true, 0, false, 0));
226 } 233 }
227 234
228 exit(status); 235 exit(status);
@@ -273,7 +280,8 @@ check_ldap_config_wrapper process_arguments(int argc, char **argv) {
273 280
274 int option = 0; 281 int option = 0;
275 while (true) { 282 while (true) {
276 int option_index = getopt_long(argc, argv, "hvV234TS6t:c:w:H:b:p:a:D:P:C:W:", longopts, &option); 283 int option_index =
284 getopt_long(argc, argv, "hvV234TS6t:c:w:H:b:p:a:D:P:C:W:", longopts, &option);
277 285
278 if (option_index == -1 || option_index == EOF) { 286 if (option_index == -1 || option_index == EOF) {
279 break; 287 break;
@@ -381,7 +389,8 @@ check_ldap_config_wrapper process_arguments(int argc, char **argv) {
381 result.config.ld_port = DEFAULT_PORT; 389 result.config.ld_port = DEFAULT_PORT;
382 } 390 }
383 391
384 if (strstr(argv[0], "check_ldaps") && !result.config.starttls && !result.config.ssl_on_connect) { 392 if (strstr(argv[0], "check_ldaps") && !result.config.starttls &&
393 !result.config.ssl_on_connect) {
385 result.config.starttls = true; 394 result.config.starttls = true;
386 } 395 }
387 396
@@ -398,7 +407,8 @@ check_ldap_config_wrapper validate_arguments(check_ldap_config_wrapper config_wr
398 } 407 }
399 408
400 if (config_wrapper.config.crit_entries != NULL || config_wrapper.config.warn_entries != NULL) { 409 if (config_wrapper.config.crit_entries != NULL || config_wrapper.config.warn_entries != NULL) {
401 set_thresholds(&config_wrapper.config.entries_thresholds, config_wrapper.config.warn_entries, config_wrapper.config.crit_entries); 410 set_thresholds(&config_wrapper.config.entries_thresholds,
411 config_wrapper.config.warn_entries, config_wrapper.config.crit_entries);
402 } 412 }
403 413
404 if (config_wrapper.config.ld_passwd == NULL) { 414 if (config_wrapper.config.ld_passwd == NULL) {
@@ -435,11 +445,13 @@ void print_help(void) {
435 printf(" %s\n", "-D [--bind]"); 445 printf(" %s\n", "-D [--bind]");
436 printf(" %s\n", _("ldap bind DN (if required)")); 446 printf(" %s\n", _("ldap bind DN (if required)"));
437 printf(" %s\n", "-P [--pass]"); 447 printf(" %s\n", "-P [--pass]");
438 printf(" %s\n", _("ldap password (if required, or set the password through environment variable 'LDAP_PASSWORD')")); 448 printf(" %s\n", _("ldap password (if required, or set the password through environment "
449 "variable 'LDAP_PASSWORD')"));
439 printf(" %s\n", "-T [--starttls]"); 450 printf(" %s\n", "-T [--starttls]");
440 printf(" %s\n", _("use starttls mechanism introduced in protocol version 3")); 451 printf(" %s\n", _("use starttls mechanism introduced in protocol version 3"));
441 printf(" %s\n", "-S [--ssl]"); 452 printf(" %s\n", "-S [--ssl]");
442 printf(" %s %i\n", _("use ldaps (ldap v2 ssl method). this also sets the default port to"), LDAPS_PORT); 453 printf(" %s %i\n", _("use ldaps (ldap v2 ssl method). this also sets the default port to"),
454 LDAPS_PORT);
443 455
444#ifdef HAVE_LDAP_SET_OPTION 456#ifdef HAVE_LDAP_SET_OPTION
445 printf(" %s\n", "-2 [--ver2]"); 457 printf(" %s\n", "-2 [--ver2]");
@@ -463,9 +475,11 @@ void print_help(void) {
463 printf("\n"); 475 printf("\n");
464 printf("%s\n", _("Notes:")); 476 printf("%s\n", _("Notes:"));
465 printf(" %s\n", _("If this plugin is called via 'check_ldaps', method 'STARTTLS' will be")); 477 printf(" %s\n", _("If this plugin is called via 'check_ldaps', method 'STARTTLS' will be"));
466 printf(_(" implied (using default port %i) unless --port=636 is specified. In that case\n"), DEFAULT_PORT); 478 printf(_(" implied (using default port %i) unless --port=636 is specified. In that case\n"),
479 DEFAULT_PORT);
467 printf(" %s\n", _("'SSL on connect' will be used no matter how the plugin was called.")); 480 printf(" %s\n", _("'SSL on connect' will be used no matter how the plugin was called."));
468 printf(" %s\n", _("This detection is deprecated, please use 'check_ldap' with the '--starttls' or '--ssl' flags")); 481 printf(" %s\n", _("This detection is deprecated, please use 'check_ldap' with the '--starttls' "
482 "or '--ssl' flags"));
469 printf(" %s\n", _("to define the behaviour explicitly instead.")); 483 printf(" %s\n", _("to define the behaviour explicitly instead."));
470 printf(" %s\n", _("The parameters --warn-entries and --crit-entries are optional.")); 484 printf(" %s\n", _("The parameters --warn-entries and --crit-entries are optional."));
471 485
diff --git a/plugins/check_load.c b/plugins/check_load.c
index 2925bff3..644cd604 100644
--- a/plugins/check_load.c
+++ b/plugins/check_load.c
@@ -168,7 +168,8 @@ int main(int argc, char **argv) {
168 mp_subcheck scaled_load_sc1 = mp_subcheck_init(); 168 mp_subcheck scaled_load_sc1 = mp_subcheck_init();
169 scaled_load_sc1 = mp_set_subcheck_state(scaled_load_sc1, mp_get_pd_status(pd_scaled_load1)); 169 scaled_load_sc1 = mp_set_subcheck_state(scaled_load_sc1, mp_get_pd_status(pd_scaled_load1));
170 mp_add_perfdata_to_subcheck(&scaled_load_sc1, pd_scaled_load1); 170 mp_add_perfdata_to_subcheck(&scaled_load_sc1, pd_scaled_load1);
171 xasprintf(&scaled_load_sc1.output, "1 Minute: %s", pd_value_to_string(pd_scaled_load1.value)); 171 xasprintf(&scaled_load_sc1.output, "1 Minute: %s",
172 pd_value_to_string(pd_scaled_load1.value));
172 mp_add_subcheck_to_subcheck(&scaled_load_sc, scaled_load_sc1); 173 mp_add_subcheck_to_subcheck(&scaled_load_sc, scaled_load_sc1);
173 174
174 mp_perfdata pd_scaled_load5 = perfdata_init(); 175 mp_perfdata pd_scaled_load5 = perfdata_init();
@@ -179,7 +180,8 @@ int main(int argc, char **argv) {
179 mp_subcheck scaled_load_sc5 = mp_subcheck_init(); 180 mp_subcheck scaled_load_sc5 = mp_subcheck_init();
180 scaled_load_sc5 = mp_set_subcheck_state(scaled_load_sc5, mp_get_pd_status(pd_scaled_load5)); 181 scaled_load_sc5 = mp_set_subcheck_state(scaled_load_sc5, mp_get_pd_status(pd_scaled_load5));
181 mp_add_perfdata_to_subcheck(&scaled_load_sc5, pd_scaled_load5); 182 mp_add_perfdata_to_subcheck(&scaled_load_sc5, pd_scaled_load5);
182 xasprintf(&scaled_load_sc5.output, "5 Minutes: %s", pd_value_to_string(pd_scaled_load5.value)); 183 xasprintf(&scaled_load_sc5.output, "5 Minutes: %s",
184 pd_value_to_string(pd_scaled_load5.value));
183 mp_add_subcheck_to_subcheck(&scaled_load_sc, scaled_load_sc5); 185 mp_add_subcheck_to_subcheck(&scaled_load_sc, scaled_load_sc5);
184 186
185 mp_perfdata pd_scaled_load15 = perfdata_init(); 187 mp_perfdata pd_scaled_load15 = perfdata_init();
@@ -188,9 +190,11 @@ int main(int argc, char **argv) {
188 pd_scaled_load15 = mp_pd_set_thresholds(pd_scaled_load15, config.th_load[2]); 190 pd_scaled_load15 = mp_pd_set_thresholds(pd_scaled_load15, config.th_load[2]);
189 191
190 mp_subcheck scaled_load_sc15 = mp_subcheck_init(); 192 mp_subcheck scaled_load_sc15 = mp_subcheck_init();
191 scaled_load_sc15 = mp_set_subcheck_state(scaled_load_sc15, mp_get_pd_status(pd_scaled_load15)); 193 scaled_load_sc15 =
194 mp_set_subcheck_state(scaled_load_sc15, mp_get_pd_status(pd_scaled_load15));
192 mp_add_perfdata_to_subcheck(&scaled_load_sc15, pd_scaled_load15); 195 mp_add_perfdata_to_subcheck(&scaled_load_sc15, pd_scaled_load15);
193 xasprintf(&scaled_load_sc15.output, "15 Minutes: %s", pd_value_to_string(pd_scaled_load15.value)); 196 xasprintf(&scaled_load_sc15.output, "15 Minutes: %s",
197 pd_value_to_string(pd_scaled_load15.value));
194 mp_add_subcheck_to_subcheck(&scaled_load_sc, scaled_load_sc15); 198 mp_add_subcheck_to_subcheck(&scaled_load_sc, scaled_load_sc15);
195 199
196 mp_add_subcheck_to_check(&overall, scaled_load_sc); 200 mp_add_subcheck_to_check(&overall, scaled_load_sc);
@@ -245,11 +249,13 @@ int main(int argc, char **argv) {
245 mp_subcheck top_proc_sc = mp_subcheck_init(); 249 mp_subcheck top_proc_sc = mp_subcheck_init();
246 top_proc_sc = mp_set_subcheck_state(top_proc_sc, STATE_OK); 250 top_proc_sc = mp_set_subcheck_state(top_proc_sc, STATE_OK);
247 top_processes_result top_proc = print_top_consuming_processes(config.n_procs_to_show); 251 top_processes_result top_proc = print_top_consuming_processes(config.n_procs_to_show);
248 xasprintf(&top_proc_sc.output, "Top %lu CPU time consuming processes", config.n_procs_to_show); 252 xasprintf(&top_proc_sc.output, "Top %lu CPU time consuming processes",
253 config.n_procs_to_show);
249 254
250 if (top_proc.errorcode == OK) { 255 if (top_proc.errorcode == OK) {
251 for (unsigned long i = 0; i < config.n_procs_to_show; i++) { 256 for (unsigned long i = 0; i < config.n_procs_to_show; i++) {
252 xasprintf(&top_proc_sc.output, "%s\n%s", top_proc_sc.output, top_proc.top_processes[i]); 257 xasprintf(&top_proc_sc.output, "%s\n%s", top_proc_sc.output,
258 top_proc.top_processes[i]);
253 } 259 }
254 } 260 }
255 261
@@ -417,7 +423,8 @@ void print_help(void) {
417 423
418void print_usage(void) { 424void print_usage(void) {
419 printf("%s\n", _("Usage:")); 425 printf("%s\n", _("Usage:"));
420 printf("%s [-r] -w WLOAD1,WLOAD5,WLOAD15 -c CLOAD1,CLOAD5,CLOAD15 [-n NUMBER_OF_PROCS]\n", progname); 426 printf("%s [-r] -w WLOAD1,WLOAD5,WLOAD15 -c CLOAD1,CLOAD5,CLOAD15 [-n NUMBER_OF_PROCS]\n",
427 progname);
421} 428}
422 429
423#ifdef PS_USES_PROCPCPU 430#ifdef PS_USES_PROCPCPU
@@ -445,8 +452,8 @@ static top_processes_result print_top_consuming_processes(unsigned long n_procs_
445 top_processes_result result = { 452 top_processes_result result = {
446 .errorcode = OK, 453 .errorcode = OK,
447 }; 454 };
448 struct output chld_out; 455 output chld_out;
449 struct output chld_err; 456 output chld_err;
450 if (np_runcmd(PS_COMMAND, &chld_out, &chld_err, 0) != 0) { 457 if (np_runcmd(PS_COMMAND, &chld_out, &chld_err, 0) != 0) {
451 fprintf(stderr, _("'%s' exited with non-zero status.\n"), PS_COMMAND); 458 fprintf(stderr, _("'%s' exited with non-zero status.\n"), PS_COMMAND);
452 result.errorcode = ERROR; 459 result.errorcode = ERROR;
@@ -462,7 +469,8 @@ static top_processes_result print_top_consuming_processes(unsigned long n_procs_
462#ifdef PS_USES_PROCPCPU 469#ifdef PS_USES_PROCPCPU
463 qsort(chld_out.line + 1, chld_out.lines - 1, sizeof(char *), cmpstringp); 470 qsort(chld_out.line + 1, chld_out.lines - 1, sizeof(char *), cmpstringp);
464#endif /* PS_USES_PROCPCPU */ 471#endif /* PS_USES_PROCPCPU */
465 unsigned long lines_to_show = chld_out.lines < (size_t)(n_procs_to_show + 1) ? chld_out.lines : n_procs_to_show + 1; 472 unsigned long lines_to_show =
473 chld_out.lines < (size_t)(n_procs_to_show + 1) ? chld_out.lines : n_procs_to_show + 1;
466 474
467 result.top_processes = calloc(lines_to_show, sizeof(char *)); 475 result.top_processes = calloc(lines_to_show, sizeof(char *));
468 if (result.top_processes == NULL) { 476 if (result.top_processes == NULL) {
diff --git a/plugins/check_mrtg.c b/plugins/check_mrtg.c
index 5bd276dc..4a17049a 100644
--- a/plugins/check_mrtg.c
+++ b/plugins/check_mrtg.c
@@ -129,7 +129,8 @@ int main(int argc, char **argv) {
129 time_t current_time; 129 time_t current_time;
130 time(&current_time); 130 time(&current_time);
131 if (config.expire_minutes > 0 && (current_time - timestamp) > (config.expire_minutes * 60)) { 131 if (config.expire_minutes > 0 && (current_time - timestamp) > (config.expire_minutes * 60)) {
132 printf(_("MRTG data has expired (%d minutes old)\n"), (int)((current_time - timestamp) / 60)); 132 printf(_("MRTG data has expired (%d minutes old)\n"),
133 (int)((current_time - timestamp) / 60));
133 return STATE_WARNING; 134 return STATE_WARNING;
134 } 135 }
135 136
@@ -148,20 +149,29 @@ int main(int argc, char **argv) {
148 result = STATE_WARNING; 149 result = STATE_WARNING;
149 } 150 }
150 151
151 printf("%s. %s = %lu %s|%s\n", (config.use_average) ? _("Avg") : _("Max"), config.label, rate, config.units, 152 printf("%s. %s = %lu %s|%s\n", (config.use_average) ? _("Avg") : _("Max"), config.label, rate,
152 perfdata(config.label, (long)rate, config.units, config.value_warning_threshold_set, (long)config.value_warning_threshold, 153 config.units,
153 config.value_critical_threshold_set, (long)config.value_critical_threshold, 0, 0, 0, 0)); 154 perfdata(config.label, (long)rate, config.units, config.value_warning_threshold_set,
155 (long)config.value_warning_threshold, config.value_critical_threshold_set,
156 (long)config.value_critical_threshold, 0, 0, 0, 0));
154 157
155 return result; 158 return result;
156} 159}
157 160
158/* process command-line arguments */ 161/* process command-line arguments */
159check_mrtg_config_wrapper process_arguments(int argc, char **argv) { 162check_mrtg_config_wrapper process_arguments(int argc, char **argv) {
160 static struct option longopts[] = { 163 static struct option longopts[] = {{"logfile", required_argument, 0, 'F'},
161 {"logfile", required_argument, 0, 'F'}, {"expires", required_argument, 0, 'e'}, {"aggregation", required_argument, 0, 'a'}, 164 {"expires", required_argument, 0, 'e'},
162 {"variable", required_argument, 0, 'v'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, 165 {"aggregation", required_argument, 0, 'a'},
163 {"label", required_argument, 0, 'l'}, {"units", required_argument, 0, 'u'}, {"variable", required_argument, 0, 'v'}, 166 {"variable", required_argument, 0, 'v'},
164 {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; 167 {"critical", required_argument, 0, 'c'},
168 {"warning", required_argument, 0, 'w'},
169 {"label", required_argument, 0, 'l'},
170 {"units", required_argument, 0, 'u'},
171 {"variable", required_argument, 0, 'v'},
172 {"version", no_argument, 0, 'V'},
173 {"help", no_argument, 0, 'h'},
174 {0, 0, 0, 0}};
165 175
166 check_mrtg_config_wrapper result = { 176 check_mrtg_config_wrapper result = {
167 .errorcode = OK, 177 .errorcode = OK,
@@ -242,7 +252,9 @@ check_mrtg_config_wrapper process_arguments(int argc, char **argv) {
242 if (is_intpos(argv[option_char])) { 252 if (is_intpos(argv[option_char])) {
243 result.config.expire_minutes = atoi(argv[option_char++]); 253 result.config.expire_minutes = atoi(argv[option_char++]);
244 } else { 254 } else {
245 die(STATE_UNKNOWN, _("%s is not a valid expiration time\nUse '%s -h' for additional help\n"), argv[option_char], progname); 255 die(STATE_UNKNOWN,
256 _("%s is not a valid expiration time\nUse '%s -h' for additional help\n"),
257 argv[option_char], progname);
246 } 258 }
247 } 259 }
248 260
@@ -334,25 +346,32 @@ void print_help(void) {
334 printf(" %s\n", _("\"Bytes Per Second\", \"%% Utilization\")")); 346 printf(" %s\n", _("\"Bytes Per Second\", \"%% Utilization\")"));
335 347
336 printf("\n"); 348 printf("\n");
337 printf(" %s\n", _("If the value exceeds the <vwl> threshold, a WARNING status is returned. If")); 349 printf(" %s\n",
350 _("If the value exceeds the <vwl> threshold, a WARNING status is returned. If"));
338 printf(" %s\n", _("the value exceeds the <vcl> threshold, a CRITICAL status is returned. If")); 351 printf(" %s\n", _("the value exceeds the <vcl> threshold, a CRITICAL status is returned. If"));
339 printf(" %s\n", _("the data in the log file is older than <expire_minutes> old, a WARNING")); 352 printf(" %s\n", _("the data in the log file is older than <expire_minutes> old, a WARNING"));
340 printf(" %s\n", _("status is returned and a warning message is printed.")); 353 printf(" %s\n", _("status is returned and a warning message is printed."));
341 354
342 printf("\n"); 355 printf("\n");
343 printf(" %s\n", _("This plugin is useful for monitoring MRTG data that does not correspond to")); 356 printf(" %s\n",
344 printf(" %s\n", _("bandwidth usage. (Use the check_mrtgtraf plugin for monitoring bandwidth).")); 357 _("This plugin is useful for monitoring MRTG data that does not correspond to"));
345 printf(" %s\n", _("It can be used to monitor any kind of data that MRTG is monitoring - errors,")); 358 printf(" %s\n",
346 printf(" %s\n", _("packets/sec, etc. I use MRTG in conjunction with the Novell NLM that allows")); 359 _("bandwidth usage. (Use the check_mrtgtraf plugin for monitoring bandwidth)."));
360 printf(" %s\n",
361 _("It can be used to monitor any kind of data that MRTG is monitoring - errors,"));
362 printf(" %s\n",
363 _("packets/sec, etc. I use MRTG in conjunction with the Novell NLM that allows"));
347 printf(" %s\n", _("me to track processor utilization, user connections, drive space, etc and")); 364 printf(" %s\n", _("me to track processor utilization, user connections, drive space, etc and"));
348 printf(" %s\n\n", _("this plugin works well for monitoring that kind of data as well.")); 365 printf(" %s\n\n", _("this plugin works well for monitoring that kind of data as well."));
349 366
350 printf("%s\n", _("Notes:")); 367 printf("%s\n", _("Notes:"));
351 printf(" %s\n", _("- This plugin only monitors one of the two variables stored in the MRTG log")); 368 printf(" %s\n",
369 _("- This plugin only monitors one of the two variables stored in the MRTG log"));
352 printf(" %s\n", _("file. If you want to monitor both values you will have to define two")); 370 printf(" %s\n", _("file. If you want to monitor both values you will have to define two"));
353 printf(" %s\n", _("commands with different values for the <variable> argument. Of course,")); 371 printf(" %s\n", _("commands with different values for the <variable> argument. Of course,"));
354 printf(" %s\n", _("you can always hack the code to make this plugin work for you...")); 372 printf(" %s\n", _("you can always hack the code to make this plugin work for you..."));
355 printf(" %s\n", _("- MRTG stands for the Multi Router Traffic Grapher. It can be downloaded from")); 373 printf(" %s\n",
374 _("- MRTG stands for the Multi Router Traffic Grapher. It can be downloaded from"));
356 printf(" %s\n", "http://ee-staff.ethz.ch/~oetiker/webtools/mrtg/mrtg.html"); 375 printf(" %s\n", "http://ee-staff.ethz.ch/~oetiker/webtools/mrtg/mrtg.html");
357 376
358 printf(UT_SUPPORT); 377 printf(UT_SUPPORT);
diff --git a/plugins/check_mrtgtraf.c b/plugins/check_mrtgtraf.c
index 8c7cf8aa..10ce936f 100644
--- a/plugins/check_mrtgtraf.c
+++ b/plugins/check_mrtgtraf.c
@@ -122,7 +122,8 @@ int main(int argc, char **argv) {
122 time_t current_time; 122 time_t current_time;
123 time(&current_time); 123 time(&current_time);
124 if ((config.expire_minutes > 0) && (current_time - timestamp) > (config.expire_minutes * 60)) { 124 if ((config.expire_minutes > 0) && (current_time - timestamp) > (config.expire_minutes * 60)) {
125 die(STATE_WARNING, _("MRTG data has expired (%d minutes old)\n"), (int)((current_time - timestamp) / 60)); 125 die(STATE_WARNING, _("MRTG data has expired (%d minutes old)\n"),
126 (int)((current_time - timestamp) / 60));
126 } 127 }
127 128
128 unsigned long incoming_rate = 0L; 129 unsigned long incoming_rate = 0L;
@@ -177,21 +178,26 @@ int main(int argc, char **argv) {
177 } 178 }
178 179
179 int result = STATE_OK; 180 int result = STATE_OK;
180 if (incoming_rate > config.incoming_critical_threshold || outgoing_rate > config.outgoing_critical_threshold) { 181 if (incoming_rate > config.incoming_critical_threshold ||
182 outgoing_rate > config.outgoing_critical_threshold) {
181 result = STATE_CRITICAL; 183 result = STATE_CRITICAL;
182 } else if (incoming_rate > config.incoming_warning_threshold || outgoing_rate > config.outgoing_warning_threshold) { 184 } else if (incoming_rate > config.incoming_warning_threshold ||
185 outgoing_rate > config.outgoing_warning_threshold) {
183 result = STATE_WARNING; 186 result = STATE_WARNING;
184 } 187 }
185 188
186 char *error_message; 189 char *error_message;
187 xasprintf(&error_message, _("%s. In = %0.1f %s/s, %s. Out = %0.1f %s/s|%s %s\n"), (config.use_average) ? _("Avg") : _("Max"), 190 xasprintf(&error_message, _("%s. In = %0.1f %s/s, %s. Out = %0.1f %s/s|%s %s\n"),
188 adjusted_incoming_rate, incoming_speed_rating, (config.use_average) ? _("Avg") : _("Max"), adjusted_outgoing_rate, 191 (config.use_average) ? _("Avg") : _("Max"), adjusted_incoming_rate,
189 outgoing_speed_rating, 192 incoming_speed_rating, (config.use_average) ? _("Avg") : _("Max"),
190 fperfdata("in", adjusted_incoming_rate, incoming_speed_rating, (int)config.incoming_warning_threshold, 193 adjusted_outgoing_rate, outgoing_speed_rating,
191 config.incoming_warning_threshold, (int)config.incoming_critical_threshold, config.incoming_critical_threshold, 194 fperfdata("in", adjusted_incoming_rate, incoming_speed_rating,
195 (int)config.incoming_warning_threshold, config.incoming_warning_threshold,
196 (int)config.incoming_critical_threshold, config.incoming_critical_threshold,
192 true, 0, false, 0), 197 true, 0, false, 0),
193 fperfdata("out", adjusted_outgoing_rate, outgoing_speed_rating, (int)config.outgoing_warning_threshold, 198 fperfdata("out", adjusted_outgoing_rate, outgoing_speed_rating,
194 config.outgoing_warning_threshold, (int)config.outgoing_critical_threshold, config.outgoing_critical_threshold, 199 (int)config.outgoing_warning_threshold, config.outgoing_warning_threshold,
200 (int)config.outgoing_critical_threshold, config.outgoing_critical_threshold,
195 true, 0, false, 0)); 201 true, 0, false, 0));
196 202
197 printf(_("Traffic %s - %s\n"), state_text(result), error_message); 203 printf(_("Traffic %s - %s\n"), state_text(result), error_message);
@@ -249,10 +255,12 @@ check_mrtgtraf_config_wrapper process_arguments(int argc, char **argv) {
249 result.config.use_average = (bool)(strcmp(optarg, "MAX")); 255 result.config.use_average = (bool)(strcmp(optarg, "MAX"));
250 break; 256 break;
251 case 'c': /* warning threshold */ 257 case 'c': /* warning threshold */
252 sscanf(optarg, "%lu,%lu", &result.config.incoming_critical_threshold, &result.config.outgoing_critical_threshold); 258 sscanf(optarg, "%lu,%lu", &result.config.incoming_critical_threshold,
259 &result.config.outgoing_critical_threshold);
253 break; 260 break;
254 case 'w': /* critical threshold */ 261 case 'w': /* critical threshold */
255 sscanf(optarg, "%lu,%lu", &result.config.incoming_warning_threshold, &result.config.outgoing_warning_threshold); 262 sscanf(optarg, "%lu,%lu", &result.config.incoming_warning_threshold,
263 &result.config.outgoing_warning_threshold);
256 break; 264 break;
257 case 'V': /* version */ 265 case 'V': /* version */
258 print_revision(progname, NP_VERSION); 266 print_revision(progname, NP_VERSION);
diff --git a/plugins/check_mysql.c b/plugins/check_mysql.c
index ca3422b5..3d7ec4cd 100644
--- a/plugins/check_mysql.c
+++ b/plugins/check_mysql.c
@@ -50,15 +50,23 @@ static int verbose = 0;
50 50
51#define LENGTH_METRIC_UNIT 6 51#define LENGTH_METRIC_UNIT 6
52static const char *metric_unit[LENGTH_METRIC_UNIT] = { 52static const char *metric_unit[LENGTH_METRIC_UNIT] = {
53 "Open_files", "Open_tables", "Qcache_free_memory", "Qcache_queries_in_cache", "Threads_connected", "Threads_running"}; 53 "Open_files", "Open_tables", "Qcache_free_memory", "Qcache_queries_in_cache",
54 "Threads_connected", "Threads_running"};
54 55
55#define LENGTH_METRIC_COUNTER 9 56#define LENGTH_METRIC_COUNTER 9
56static const char *metric_counter[LENGTH_METRIC_COUNTER] = { 57static const char *metric_counter[LENGTH_METRIC_COUNTER] = {"Connections",
57 "Connections", "Qcache_hits", "Qcache_inserts", "Qcache_lowmem_prunes", "Qcache_not_cached", "Queries", 58 "Qcache_hits",
58 "Questions", "Table_locks_waited", "Uptime"}; 59 "Qcache_inserts",
59 60 "Qcache_lowmem_prunes",
60#define MYSQLDUMP_THREADS_QUERY \ 61 "Qcache_not_cached",
61 "SELECT COUNT(1) mysqldumpThreads FROM information_schema.processlist WHERE info LIKE 'SELECT /*!40001 SQL_NO_CACHE */%'" 62 "Queries",
63 "Questions",
64 "Table_locks_waited",
65 "Uptime"};
66
67#define MYSQLDUMP_THREADS_QUERY \
68 "SELECT COUNT(1) mysqldumpThreads FROM information_schema.processlist WHERE info LIKE " \
69 "'SELECT /*!40001 SQL_NO_CACHE */%'"
62 70
63typedef struct { 71typedef struct {
64 int errorcode; 72 int errorcode;
@@ -99,16 +107,19 @@ int main(int argc, char **argv) {
99 } 107 }
100 108
101 if (config.ssl) { 109 if (config.ssl) {
102 mysql_ssl_set(&mysql, config.key, config.cert, config.ca_cert, config.ca_dir, config.ciphers); 110 mysql_ssl_set(&mysql, config.key, config.cert, config.ca_cert, config.ca_dir,
111 config.ciphers);
103 } 112 }
104 /* establish a connection to the server and error checking */ 113 /* establish a connection to the server and error checking */
105 if (!mysql_real_connect(&mysql, config.db_host, config.db_user, config.db_pass, config.db, config.db_port, config.db_socket, 0)) { 114 if (!mysql_real_connect(&mysql, config.db_host, config.db_user, config.db_pass, config.db,
115 config.db_port, config.db_socket, 0)) {
106 /* Depending on internally-selected auth plugin MySQL might return */ 116 /* Depending on internally-selected auth plugin MySQL might return */
107 /* ER_ACCESS_DENIED_NO_PASSWORD_ERROR or ER_ACCESS_DENIED_ERROR. */ 117 /* ER_ACCESS_DENIED_NO_PASSWORD_ERROR or ER_ACCESS_DENIED_ERROR. */
108 /* Semantically these errors are the same. */ 118 /* Semantically these errors are the same. */
109 if (config.ignore_auth && 119 if (config.ignore_auth && (mysql_errno(&mysql) == ER_ACCESS_DENIED_ERROR ||
110 (mysql_errno(&mysql) == ER_ACCESS_DENIED_ERROR || mysql_errno(&mysql) == ER_ACCESS_DENIED_NO_PASSWORD_ERROR)) { 120 mysql_errno(&mysql) == ER_ACCESS_DENIED_NO_PASSWORD_ERROR)) {
111 printf("MySQL OK - Version: %s (protocol %d)\n", mysql_get_server_info(&mysql), mysql_get_proto_info(&mysql)); 121 printf("MySQL OK - Version: %s (protocol %d)\n", mysql_get_server_info(&mysql),
122 mysql_get_proto_info(&mysql));
112 mysql_close(&mysql); 123 mysql_close(&mysql);
113 return STATE_OK; 124 return STATE_OK;
114 } 125 }
@@ -157,13 +168,17 @@ int main(int argc, char **argv) {
157 while ((row = mysql_fetch_row(res)) != NULL) { 168 while ((row = mysql_fetch_row(res)) != NULL) {
158 for (int i = 0; i < LENGTH_METRIC_UNIT; i++) { 169 for (int i = 0; i < LENGTH_METRIC_UNIT; i++) {
159 if (strcmp(row[0], metric_unit[i]) == 0) { 170 if (strcmp(row[0], metric_unit[i]) == 0) {
160 xasprintf(&perf, "%s%s ", perf, perfdata(metric_unit[i], atol(row[1]), "", false, 0, false, 0, false, 0, false, 0)); 171 xasprintf(&perf, "%s%s ", perf,
172 perfdata(metric_unit[i], atol(row[1]), "", false, 0, false, 0, false,
173 0, false, 0));
161 continue; 174 continue;
162 } 175 }
163 } 176 }
164 for (int i = 0; i < LENGTH_METRIC_COUNTER; i++) { 177 for (int i = 0; i < LENGTH_METRIC_COUNTER; i++) {
165 if (strcmp(row[0], metric_counter[i]) == 0) { 178 if (strcmp(row[0], metric_counter[i]) == 0) {
166 xasprintf(&perf, "%s%s ", perf, perfdata(metric_counter[i], atol(row[1]), "c", false, 0, false, 0, false, 0, false, 0)); 179 xasprintf(&perf, "%s%s ", perf,
180 perfdata(metric_counter[i], atol(row[1]), "c", false, 0, false, 0,
181 false, 0, false, 0));
167 continue; 182 continue;
168 } 183 }
169 } 184 }
@@ -189,8 +204,8 @@ int main(int argc, char **argv) {
189 unsigned long minor_version = (server_verion_int % 10000) / 100; 204 unsigned long minor_version = (server_verion_int % 10000) / 100;
190 unsigned long patch_version = (server_verion_int % 100); 205 unsigned long patch_version = (server_verion_int % 100);
191 if (verbose) { 206 if (verbose) {
192 printf("Found MariaDB: %s, main version: %lu, minor version: %lu, patch version: %lu\n", server_version, major_version, 207 printf("Found MariaDB: %s, main version: %lu, minor version: %lu, patch version: %lu\n",
193 minor_version, patch_version); 208 server_version, major_version, minor_version, patch_version);
194 } 209 }
195 210
196 if (strstr(server_version, "MariaDB") != NULL) { 211 if (strstr(server_version, "MariaDB") != NULL) {
@@ -292,11 +307,15 @@ int main(int argc, char **argv) {
292 } 307 }
293 308
294 /* Save replica status in replica_result */ 309 /* Save replica status in replica_result */
295 snprintf(replica_result, REPLICA_RESULTSIZE, "Replica IO: %s Replica SQL: %s Seconds Behind Master: %s", row[replica_io_field], 310 snprintf(replica_result, REPLICA_RESULTSIZE,
296 row[replica_sql_field], seconds_behind_field != -1 ? row[seconds_behind_field] : "Unknown"); 311 "Replica IO: %s Replica SQL: %s Seconds Behind Master: %s",
297 312 row[replica_io_field], row[replica_sql_field],
298 /* Raise critical error if SQL THREAD or IO THREAD are stopped, but only if there are no mysqldump threads running */ 313 seconds_behind_field != -1 ? row[seconds_behind_field] : "Unknown");
299 if (strcmp(row[replica_io_field], "Yes") != 0 || strcmp(row[replica_sql_field], "Yes") != 0) { 314
315 /* Raise critical error if SQL THREAD or IO THREAD are stopped, but only if there are no
316 * mysqldump threads running */
317 if (strcmp(row[replica_io_field], "Yes") != 0 ||
318 strcmp(row[replica_sql_field], "Yes") != 0) {
300 MYSQL_RES *res_mysqldump; 319 MYSQL_RES *res_mysqldump;
301 MYSQL_ROW row_mysqldump; 320 MYSQL_ROW row_mysqldump;
302 unsigned int mysqldump_threads = 0; 321 unsigned int mysqldump_threads = 0;
@@ -325,20 +344,23 @@ int main(int argc, char **argv) {
325 if (seconds_behind_field == -1) { 344 if (seconds_behind_field == -1) {
326 printf("seconds_behind_field not found\n"); 345 printf("seconds_behind_field not found\n");
327 } else { 346 } else {
328 printf("seconds_behind_field(index %d)=%s\n", seconds_behind_field, row[seconds_behind_field]); 347 printf("seconds_behind_field(index %d)=%s\n", seconds_behind_field,
348 row[seconds_behind_field]);
329 } 349 }
330 } 350 }
331 351
332 /* Check Seconds Behind against threshold */ 352 /* Check Seconds Behind against threshold */
333 if ((seconds_behind_field != -1) && (row[seconds_behind_field] != NULL && strcmp(row[seconds_behind_field], "NULL") != 0)) { 353 if ((seconds_behind_field != -1) && (row[seconds_behind_field] != NULL &&
354 strcmp(row[seconds_behind_field], "NULL") != 0)) {
334 double value = atof(row[seconds_behind_field]); 355 double value = atof(row[seconds_behind_field]);
335 int status; 356 int status;
336 357
337 status = get_status(value, config.my_threshold); 358 status = get_status(value, config.my_threshold);
338 359
339 xasprintf(&perf, "%s %s", perf, 360 xasprintf(&perf, "%s %s", perf,
340 fperfdata("seconds behind master", value, "s", true, (double)config.warning_time, true, 361 fperfdata("seconds behind master", value, "s", true,
341 (double)config.critical_time, false, 0, false, 0)); 362 (double)config.warning_time, true, (double)config.critical_time,
363 false, 0, false, 0));
342 364
343 if (status == STATE_WARNING) { 365 if (status == STATE_WARNING) {
344 printf("SLOW_REPLICA %s: %s|%s\n", _("WARNING"), replica_result, perf); 366 printf("SLOW_REPLICA %s: %s|%s\n", _("WARNING"), replica_result, perf);
@@ -410,7 +432,8 @@ check_mysql_config_wrapper process_arguments(int argc, char **argv) {
410 432
411 int option = 0; 433 int option = 0;
412 while (true) { 434 while (true) {
413 int option_index = getopt_long(argc, argv, "hlvVnSP:p:u:d:H:s:c:w:a:k:C:D:L:f:g:", longopts, &option); 435 int option_index =
436 getopt_long(argc, argv, "hlvVnSP:p:u:d:H:s:c:w:a:k:C:D:L:f:g:", longopts, &option);
414 437
415 if (option_index == -1 || option_index == EOF) { 438 if (option_index == -1 || option_index == EOF) {
416 break; 439 break;
@@ -580,15 +603,17 @@ void print_help(void) {
580 printf(" ==> %s <==\n", _("IMPORTANT: THIS FORM OF AUTHENTICATION IS NOT SECURE!!!")); 603 printf(" ==> %s <==\n", _("IMPORTANT: THIS FORM OF AUTHENTICATION IS NOT SECURE!!!"));
581 printf(" %s\n", _("Your clear-text password could be visible as a process table entry")); 604 printf(" %s\n", _("Your clear-text password could be visible as a process table entry"));
582 printf(" %s\n", "-S, --check-slave"); 605 printf(" %s\n", "-S, --check-slave");
583 printf(" %s\n", 606 printf(" %s\n", _("Check if the slave thread is running properly. This option is deprecated "
584 _("Check if the slave thread is running properly. This option is deprecated in favour of check-replica, which does the same")); 607 "in favour of check-replica, which does the same"));
585 printf(" %s\n", "--check-replica"); 608 printf(" %s\n", "--check-replica");
586 printf(" %s\n", _("Check if the replica thread is running properly.")); 609 printf(" %s\n", _("Check if the replica thread is running properly."));
587 printf(" %s\n", "-w, --warning"); 610 printf(" %s\n", "-w, --warning");
588 printf(" %s\n", _("Exit with WARNING status if replica server is more than INTEGER seconds")); 611 printf(" %s\n",
612 _("Exit with WARNING status if replica server is more than INTEGER seconds"));
589 printf(" %s\n", _("behind master")); 613 printf(" %s\n", _("behind master"));
590 printf(" %s\n", "-c, --critical"); 614 printf(" %s\n", "-c, --critical");
591 printf(" %s\n", _("Exit with CRITICAL status if replica server is more then INTEGER seconds")); 615 printf(" %s\n",
616 _("Exit with CRITICAL status if replica server is more then INTEGER seconds"));
592 printf(" %s\n", _("behind master")); 617 printf(" %s\n", _("behind master"));
593 printf(" %s\n", "-l, --ssl"); 618 printf(" %s\n", "-l, --ssl");
594 printf(" %s\n", _("Use ssl encryption")); 619 printf(" %s\n", _("Use ssl encryption"));
@@ -604,7 +629,8 @@ void print_help(void) {
604 printf(" %s\n", _("List of valid SSL ciphers")); 629 printf(" %s\n", _("List of valid SSL ciphers"));
605 630
606 printf("\n"); 631 printf("\n");
607 printf(" %s\n", _("There are no required arguments. By default, the local database is checked")); 632 printf(" %s\n",
633 _("There are no required arguments. By default, the local database is checked"));
608 printf(" %s\n", _("using the default unix socket. You can force TCP on localhost by using an")); 634 printf(" %s\n", _("using the default unix socket. You can force TCP on localhost by using an"));
609 printf(" %s\n", _("IP address or FQDN ('localhost' will use the socket as well).")); 635 printf(" %s\n", _("IP address or FQDN ('localhost' will use the socket as well)."));
610 636
diff --git a/plugins/check_mysql_query.c b/plugins/check_mysql_query.c
index 5e04a94b..c7e84deb 100644
--- a/plugins/check_mysql_query.c
+++ b/plugins/check_mysql_query.c
@@ -47,7 +47,8 @@ typedef struct {
47 check_mysql_query_config config; 47 check_mysql_query_config config;
48} check_mysql_query_config_wrapper; 48} check_mysql_query_config_wrapper;
49static check_mysql_query_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/); 49static check_mysql_query_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
50static check_mysql_query_config_wrapper validate_arguments(check_mysql_query_config_wrapper /*config_wrapper*/); 50static check_mysql_query_config_wrapper
51 validate_arguments(check_mysql_query_config_wrapper /*config_wrapper*/);
51static void print_help(void); 52static void print_help(void);
52void print_usage(void); 53void print_usage(void);
53 54
@@ -83,7 +84,8 @@ int main(int argc, char **argv) {
83 } 84 }
84 85
85 /* establish a connection to the server and error checking */ 86 /* establish a connection to the server and error checking */
86 if (!mysql_real_connect(&mysql, config.db_host, config.db_user, config.db_pass, config.db, config.db_port, config.db_socket, 0)) { 87 if (!mysql_real_connect(&mysql, config.db_host, config.db_user, config.db_pass, config.db,
88 config.db_port, config.db_socket, 0)) {
87 if (mysql_errno(&mysql) == CR_UNKNOWN_HOST) { 89 if (mysql_errno(&mysql) == CR_UNKNOWN_HOST) {
88 die(STATE_WARNING, "QUERY %s: %s\n", _("WARNING"), mysql_error(&mysql)); 90 die(STATE_WARNING, "QUERY %s: %s\n", _("WARNING"), mysql_error(&mysql));
89 } else if (mysql_errno(&mysql) == CR_VERSION_ERROR) { 91 } else if (mysql_errno(&mysql) == CR_VERSION_ERROR) {
@@ -155,8 +157,11 @@ int main(int argc, char **argv) {
155 printf("QUERY %s: ", _("CRITICAL")); 157 printf("QUERY %s: ", _("CRITICAL"));
156 } 158 }
157 printf(_("'%s' returned %f | %s"), config.sql_query, value, 159 printf(_("'%s' returned %f | %s"), config.sql_query, value,
158 fperfdata("result", value, "", config.my_thresholds->warning, config.my_thresholds->warning ? config.my_thresholds->warning->end : 0, 160 fperfdata("result", value, "", config.my_thresholds->warning,
159 config.my_thresholds->critical, config.my_thresholds->critical ? config.my_thresholds->critical->end : 0, false, 0, false, 0)); 161 config.my_thresholds->warning ? config.my_thresholds->warning->end : 0,
162 config.my_thresholds->critical,
163 config.my_thresholds->critical ? config.my_thresholds->critical->end : 0,
164 false, 0, false, 0));
160 printf("\n"); 165 printf("\n");
161 166
162 return status; 167 return status;
@@ -164,12 +169,21 @@ int main(int argc, char **argv) {
164 169
165/* process command-line arguments */ 170/* process command-line arguments */
166check_mysql_query_config_wrapper process_arguments(int argc, char **argv) { 171check_mysql_query_config_wrapper process_arguments(int argc, char **argv) {
167 static struct option longopts[] = { 172 static struct option longopts[] = {{"hostname", required_argument, 0, 'H'},
168 {"hostname", required_argument, 0, 'H'}, {"socket", required_argument, 0, 's'}, {"database", required_argument, 0, 'd'}, 173 {"socket", required_argument, 0, 's'},
169 {"username", required_argument, 0, 'u'}, {"password", required_argument, 0, 'p'}, {"file", required_argument, 0, 'f'}, 174 {"database", required_argument, 0, 'd'},
170 {"group", required_argument, 0, 'g'}, {"port", required_argument, 0, 'P'}, {"verbose", no_argument, 0, 'v'}, 175 {"username", required_argument, 0, 'u'},
171 {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {"query", required_argument, 0, 'q'}, 176 {"password", required_argument, 0, 'p'},
172 {"warning", required_argument, 0, 'w'}, {"critical", required_argument, 0, 'c'}, {0, 0, 0, 0}}; 177 {"file", required_argument, 0, 'f'},
178 {"group", required_argument, 0, 'g'},
179 {"port", required_argument, 0, 'P'},
180 {"verbose", no_argument, 0, 'v'},
181 {"version", no_argument, 0, 'V'},
182 {"help", no_argument, 0, 'h'},
183 {"query", required_argument, 0, 'q'},
184 {"warning", required_argument, 0, 'w'},
185 {"critical", required_argument, 0, 'c'},
186 {0, 0, 0, 0}};
173 187
174 check_mysql_query_config_wrapper result = { 188 check_mysql_query_config_wrapper result = {
175 .errorcode = OK, 189 .errorcode = OK,
@@ -255,7 +269,8 @@ check_mysql_query_config_wrapper process_arguments(int argc, char **argv) {
255 return validate_arguments(result); 269 return validate_arguments(result);
256} 270}
257 271
258check_mysql_query_config_wrapper validate_arguments(check_mysql_query_config_wrapper config_wrapper) { 272check_mysql_query_config_wrapper
273validate_arguments(check_mysql_query_config_wrapper config_wrapper) {
259 if (config_wrapper.config.sql_query == NULL) { 274 if (config_wrapper.config.sql_query == NULL) {
260 usage("Must specify a SQL query to run"); 275 usage("Must specify a SQL query to run");
261 } 276 }
diff --git a/plugins/check_nt.c b/plugins/check_nt.c
index 7dd23e5c..35ca92cd 100644
--- a/plugins/check_nt.c
+++ b/plugins/check_nt.c
@@ -96,7 +96,8 @@ int main(int argc, char **argv) {
96 xasprintf(&send_buffer, "%s&1", config.req_password); 96 xasprintf(&send_buffer, "%s&1", config.req_password);
97 fetch_data(config.server_address, config.server_port, send_buffer); 97 fetch_data(config.server_address, config.server_port, send_buffer);
98 if (config.value_list != NULL && strcmp(recv_buffer, config.value_list) != 0) { 98 if (config.value_list != NULL && strcmp(recv_buffer, config.value_list) != 0) {
99 xasprintf(&output_message, _("Wrong client version - running: %s, required: %s"), recv_buffer, config.value_list); 99 xasprintf(&output_message, _("Wrong client version - running: %s, required: %s"),
100 recv_buffer, config.value_list);
100 return_code = STATE_WARNING; 101 return_code = STATE_WARNING;
101 } else { 102 } else {
102 xasprintf(&output_message, "%s", recv_buffer); 103 xasprintf(&output_message, "%s", recv_buffer);
@@ -116,9 +117,12 @@ int main(int argc, char **argv) {
116 117
117 /* loop until one of the parameters is wrong or not present */ 118 /* loop until one of the parameters is wrong or not present */
118 int offset = 0; 119 int offset = 0;
119 while (lvalue_list[0 + offset] > (unsigned long)0 && lvalue_list[0 + offset] <= (unsigned long)17280 && 120 while (lvalue_list[0 + offset] > (unsigned long)0 &&
120 lvalue_list[1 + offset] > (unsigned long)0 && lvalue_list[1 + offset] <= (unsigned long)100 && 121 lvalue_list[0 + offset] <= (unsigned long)17280 &&
121 lvalue_list[2 + offset] > (unsigned long)0 && lvalue_list[2 + offset] <= (unsigned long)100) { 122 lvalue_list[1 + offset] > (unsigned long)0 &&
123 lvalue_list[1 + offset] <= (unsigned long)100 &&
124 lvalue_list[2 + offset] > (unsigned long)0 &&
125 lvalue_list[2 + offset] <= (unsigned long)100) {
122 126
123 /* Send request and retrieve data */ 127 /* Send request and retrieve data */
124 xasprintf(&send_buffer, "%s&2&%lu", config.req_password, lvalue_list[0 + offset]); 128 xasprintf(&send_buffer, "%s&2&%lu", config.req_password, lvalue_list[0 + offset]);
@@ -133,10 +137,12 @@ int main(int argc, char **argv) {
133 return_code = STATE_WARNING; 137 return_code = STATE_WARNING;
134 } 138 }
135 139
136 xasprintf(&output_message, _(" %lu%% (%lu min average)"), utilization, lvalue_list[0 + offset]); 140 xasprintf(&output_message, _(" %lu%% (%lu min average)"), utilization,
141 lvalue_list[0 + offset]);
137 xasprintf(&temp_string, "%s%s", temp_string, output_message); 142 xasprintf(&temp_string, "%s%s", temp_string, output_message);
138 xasprintf(&perfdata, _(" '%lu min avg Load'=%lu%%;%lu;%lu;0;100"), lvalue_list[0 + offset], utilization, 143 xasprintf(&perfdata, _(" '%lu min avg Load'=%lu%%;%lu;%lu;0;100"),
139 lvalue_list[1 + offset], lvalue_list[2 + offset]); 144 lvalue_list[0 + offset], utilization, lvalue_list[1 + offset],
145 lvalue_list[2 + offset]);
140 xasprintf(&temp_string_perf, "%s%s", temp_string_perf, perfdata); 146 xasprintf(&temp_string_perf, "%s%s", temp_string_perf, perfdata);
141 offset += 3; /* move across the array */ 147 offset += 3; /* move across the array */
142 } 148 }
@@ -154,8 +160,10 @@ int main(int argc, char **argv) {
154 if (config.value_list == NULL) { 160 if (config.value_list == NULL) {
155 tmp_value_list = "minutes"; 161 tmp_value_list = "minutes";
156 } 162 }
157 if (strncmp(tmp_value_list, "seconds", strlen("seconds") + 1) && strncmp(tmp_value_list, "minutes", strlen("minutes") + 1) && 163 if (strncmp(tmp_value_list, "seconds", strlen("seconds") + 1) &&
158 strncmp(config.value_list, "hours", strlen("hours") + 1) && strncmp(tmp_value_list, "days", strlen("days") + 1)) { 164 strncmp(tmp_value_list, "minutes", strlen("minutes") + 1) &&
165 strncmp(config.value_list, "hours", strlen("hours") + 1) &&
166 strncmp(tmp_value_list, "days", strlen("days") + 1)) {
159 167
160 output_message = strdup(_("wrong -l argument")); 168 output_message = strdup(_("wrong -l argument"));
161 } else { 169 } else {
@@ -175,8 +183,9 @@ int main(int argc, char **argv) {
175 } 183 }
176 /* else uptime in seconds, nothing to do */ 184 /* else uptime in seconds, nothing to do */
177 185
178 xasprintf(&output_message, _("System Uptime - %u day(s) %u hour(s) %u minute(s) |uptime=%lu"), updays, uphours, upminutes, 186 xasprintf(&output_message,
179 uptime); 187 _("System Uptime - %u day(s) %u hour(s) %u minute(s) |uptime=%lu"), updays,
188 uphours, upminutes, uptime);
180 189
181 if (config.check_critical_value && uptime <= config.critical_value) { 190 if (config.check_critical_value && uptime <= config.critical_value) {
182 return_code = STATE_CRITICAL; 191 return_code = STATE_CRITICAL;
@@ -207,20 +216,27 @@ int main(int argc, char **argv) {
207 } 216 }
208 217
209 if (total_disk_space > 0 && free_disk_space >= 0) { 218 if (total_disk_space > 0 && free_disk_space >= 0) {
210 double percent_used_space = ((total_disk_space - free_disk_space) / total_disk_space) * 100; 219 double percent_used_space =
220 ((total_disk_space - free_disk_space) / total_disk_space) * 100;
211 double warning_used_space = ((float)config.warning_value / 100) * total_disk_space; 221 double warning_used_space = ((float)config.warning_value / 100) * total_disk_space;
212 double critical_used_space = ((float)config.critical_value / 100) * total_disk_space; 222 double critical_used_space =
213 223 ((float)config.critical_value / 100) * total_disk_space;
214 xasprintf(&temp_string, _("%s:\\ - total: %.2f Gb - used: %.2f Gb (%.0f%%) - free %.2f Gb (%.0f%%)"), config.value_list, 224
215 total_disk_space / 1073741824, (total_disk_space - free_disk_space) / 1073741824, percent_used_space, 225 xasprintf(
216 free_disk_space / 1073741824, (free_disk_space / total_disk_space) * 100); 226 &temp_string,
217 xasprintf(&temp_string_perf, _("'%s:\\ Used Space'=%.2fGb;%.2f;%.2f;0.00;%.2f"), config.value_list, 227 _("%s:\\ - total: %.2f Gb - used: %.2f Gb (%.0f%%) - free %.2f Gb (%.0f%%)"),
218 (total_disk_space - free_disk_space) / 1073741824, warning_used_space / 1073741824, 228 config.value_list, total_disk_space / 1073741824,
219 critical_used_space / 1073741824, total_disk_space / 1073741824); 229 (total_disk_space - free_disk_space) / 1073741824, percent_used_space,
230 free_disk_space / 1073741824, (free_disk_space / total_disk_space) * 100);
231 xasprintf(&temp_string_perf, _("'%s:\\ Used Space'=%.2fGb;%.2f;%.2f;0.00;%.2f"),
232 config.value_list, (total_disk_space - free_disk_space) / 1073741824,
233 warning_used_space / 1073741824, critical_used_space / 1073741824,
234 total_disk_space / 1073741824);
220 235
221 if (config.check_critical_value && percent_used_space >= config.critical_value) { 236 if (config.check_critical_value && percent_used_space >= config.critical_value) {
222 return_code = STATE_CRITICAL; 237 return_code = STATE_CRITICAL;
223 } else if (config.check_warning_value && percent_used_space >= config.warning_value) { 238 } else if (config.check_warning_value &&
239 percent_used_space >= config.warning_value) {
224 return_code = STATE_WARNING; 240 return_code = STATE_WARNING;
225 } else { 241 } else {
226 return_code = STATE_OK; 242 return_code = STATE_OK;
@@ -239,8 +255,10 @@ int main(int argc, char **argv) {
239 if (config.value_list == NULL) { 255 if (config.value_list == NULL) {
240 output_message = strdup(_("No service/process specified")); 256 output_message = strdup(_("No service/process specified"));
241 } else { 257 } else {
242 preparelist(config.value_list); /* replace , between services with & to send the request */ 258 preparelist(
243 xasprintf(&send_buffer, "%s&%u&%s&%s", config.req_password, (config.vars_to_check == CHECK_SERVICESTATE) ? 5 : 6, 259 config.value_list); /* replace , between services with & to send the request */
260 xasprintf(&send_buffer, "%s&%u&%s&%s", config.req_password,
261 (config.vars_to_check == CHECK_SERVICESTATE) ? 5 : 6,
244 (config.show_all) ? "ShowAll" : "ShowFail", config.value_list); 262 (config.show_all) ? "ShowAll" : "ShowFail", config.value_list);
245 fetch_data(config.server_address, config.server_port, send_buffer); 263 fetch_data(config.server_address, config.server_port, send_buffer);
246 char *numstr = strtok(recv_buffer, "&"); 264 char *numstr = strtok(recv_buffer, "&");
@@ -271,10 +289,14 @@ int main(int argc, char **argv) {
271 289
272 /* Divisor should be 1048567, not 3044515, as we are measuring "Commit Charge" here, 290 /* Divisor should be 1048567, not 3044515, as we are measuring "Commit Charge" here,
273 which equals RAM + Pagefiles. */ 291 which equals RAM + Pagefiles. */
274 xasprintf(&output_message, _("Memory usage: total:%.2f MB - used: %.2f MB (%.0f%%) - free: %.2f MB (%.0f%%)"), 292 xasprintf(
275 mem_commitLimit / 1048567, mem_commitByte / 1048567, percent_used_space, (mem_commitLimit - mem_commitByte) / 1048567, 293 &output_message,
276 (mem_commitLimit - mem_commitByte) / mem_commitLimit * 100); 294 _("Memory usage: total:%.2f MB - used: %.2f MB (%.0f%%) - free: %.2f MB (%.0f%%)"),
277 xasprintf(&perfdata, _("'Memory usage'=%.2fMB;%.2f;%.2f;0.00;%.2f"), mem_commitByte / 1048567, warning_used_space / 1048567, 295 mem_commitLimit / 1048567, mem_commitByte / 1048567, percent_used_space,
296 (mem_commitLimit - mem_commitByte) / 1048567,
297 (mem_commitLimit - mem_commitByte) / mem_commitLimit * 100);
298 xasprintf(&perfdata, _("'Memory usage'=%.2fMB;%.2f;%.2f;0.00;%.2f"),
299 mem_commitByte / 1048567, warning_used_space / 1048567,
278 critical_used_space / 1048567, mem_commitLimit / 1048567); 300 critical_used_space / 1048567, mem_commitLimit / 1048567);
279 301
280 return_code = STATE_OK; 302 return_code = STATE_OK;
@@ -302,16 +324,17 @@ int main(int argc, char **argv) {
302 the counter unit - that is, the dimensions of the counter you're getting. Examples: 324 the counter unit - that is, the dimensions of the counter you're getting. Examples:
303 pages/s, packets transferred, etc. 325 pages/s, packets transferred, etc.
304 326
305 4) If you want, you may provide the minimum and maximum values to expect. They aren't mandatory, 327 4) If you want, you may provide the minimum and maximum values to expect. They aren't
306 but once specified they MUST have the same order of magnitude and units of -w and -c; otherwise. 328 mandatory, but once specified they MUST have the same order of magnitude and units of -w and
307 strange things will happen when you make graphs of your data. 329 -c; otherwise. strange things will happen when you make graphs of your data.
308 */ 330 */
309 331
310 double counter_value = 0.0; 332 double counter_value = 0.0;
311 if (config.value_list == NULL) { 333 if (config.value_list == NULL) {
312 output_message = strdup(_("No counter specified")); 334 output_message = strdup(_("No counter specified"));
313 } else { 335 } else {
314 preparelist(config.value_list); /* replace , between services with & to send the request */ 336 preparelist(
337 config.value_list); /* replace , between services with & to send the request */
315 bool isPercent = (strchr(config.value_list, '%') != NULL); 338 bool isPercent = (strchr(config.value_list, '%') != NULL);
316 339
317 strtok(config.value_list, "&"); /* burn the first parameters */ 340 strtok(config.value_list, "&"); /* burn the first parameters */
@@ -358,15 +381,18 @@ int main(int argc, char **argv) {
358 if (allRight) { 381 if (allRight) {
359 /* Let's format the output string, finally... */ 382 /* Let's format the output string, finally... */
360 if (strstr(description, "%") == NULL) { 383 if (strstr(description, "%") == NULL) {
361 xasprintf(&output_message, "%s = %.2f %s", description, counter_value, counter_unit); 384 xasprintf(&output_message, "%s = %.2f %s", description, counter_value,
385 counter_unit);
362 } else { 386 } else {
363 /* has formatting, will segv if wrong */ 387 /* has formatting, will segv if wrong */
364 xasprintf(&output_message, description, counter_value); 388 xasprintf(&output_message, description, counter_value);
365 } 389 }
366 xasprintf(&output_message, "%s |", output_message); 390 xasprintf(&output_message, "%s |", output_message);
367 xasprintf(&output_message, "%s %s", output_message, 391 xasprintf(&output_message, "%s %s", output_message,
368 fperfdata(description, counter_value, counter_unit, 1, config.warning_value, 1, config.critical_value, 392 fperfdata(description, counter_value, counter_unit, 1,
369 (!(isPercent) && (minval != NULL)), fminval, (!(isPercent) && (minval != NULL)), fmaxval)); 393 config.warning_value, 1, config.critical_value,
394 (!(isPercent) && (minval != NULL)), fminval,
395 (!(isPercent) && (minval != NULL)), fmaxval));
370 } 396 }
371 } 397 }
372 398
@@ -391,7 +417,8 @@ int main(int argc, char **argv) {
391 if (config.value_list == NULL) { 417 if (config.value_list == NULL) {
392 output_message = strdup(_("No counter specified")); 418 output_message = strdup(_("No counter specified"));
393 } else { 419 } else {
394 preparelist(config.value_list); /* replace , between services with & to send the request */ 420 preparelist(
421 config.value_list); /* replace , between services with & to send the request */
395 xasprintf(&send_buffer, "%s&9&%s", config.req_password, config.value_list); 422 xasprintf(&send_buffer, "%s&9&%s", config.req_password, config.value_list);
396 fetch_data(config.server_address, config.server_port, send_buffer); 423 fetch_data(config.server_address, config.server_port, send_buffer);
397 unsigned long age_in_minutes = atoi(strtok(recv_buffer, "&")); 424 unsigned long age_in_minutes = atoi(strtok(recv_buffer, "&"));
@@ -724,25 +751,31 @@ void print_help(void) {
724 printf(" %s\n", "\"%%.f %%%% paging file used.\""); 751 printf(" %s\n", "\"%%.f %%%% paging file used.\"");
725 printf(" %s\n", "INSTANCES ="); 752 printf(" %s\n", "INSTANCES =");
726 printf(" %s\n", _("Check any performance counter object of Windows NT/2000.")); 753 printf(" %s\n", _("Check any performance counter object of Windows NT/2000."));
727 printf(" %s\n", _("Syntax: check_nt -H <hostname> -p <port> -v INSTANCES -l <counter object>")); 754 printf(" %s\n",
755 _("Syntax: check_nt -H <hostname> -p <port> -v INSTANCES -l <counter object>"));
728 printf(" %s\n", _("<counter object> is a Windows Perfmon Counter object (eg. Process),")); 756 printf(" %s\n", _("<counter object> is a Windows Perfmon Counter object (eg. Process),"));
729 printf(" %s\n", _("if it is two words, it should be enclosed in quotes")); 757 printf(" %s\n", _("if it is two words, it should be enclosed in quotes"));
730 printf(" %s\n", _("The returned results will be a comma-separated list of instances on ")); 758 printf(" %s\n", _("The returned results will be a comma-separated list of instances on "));
731 printf(" %s\n", _(" the selected computer for that object.")); 759 printf(" %s\n", _(" the selected computer for that object."));
732 printf(" %s\n", _("The purpose of this is to be run from command line to determine what instances")); 760 printf(" %s\n",
733 printf(" %s\n", _(" are available for monitoring without having to log onto the Windows server")); 761 _("The purpose of this is to be run from command line to determine what instances"));
762 printf(" %s\n",
763 _(" are available for monitoring without having to log onto the Windows server"));
734 printf(" %s\n", _(" to run Perfmon directly.")); 764 printf(" %s\n", _(" to run Perfmon directly."));
735 printf(" %s\n", _("It can also be used in scripts that automatically create the monitoring service")); 765 printf(" %s\n",
766 _("It can also be used in scripts that automatically create the monitoring service"));
736 printf(" %s\n", _(" configuration files.")); 767 printf(" %s\n", _(" configuration files."));
737 printf(" %s\n", _("Some examples:")); 768 printf(" %s\n", _("Some examples:"));
738 printf(" %s\n\n", _("check_nt -H 192.168.1.1 -p 1248 -v INSTANCES -l Process")); 769 printf(" %s\n\n", _("check_nt -H 192.168.1.1 -p 1248 -v INSTANCES -l Process"));
739 770
740 printf("%s\n", _("Notes:")); 771 printf("%s\n", _("Notes:"));
741 printf(" %s\n", _("- The NSClient service should be running on the server to get any information")); 772 printf(" %s\n",
773 _("- The NSClient service should be running on the server to get any information"));
742 printf(" %s\n", "(http://nsclient.ready2run.nl)."); 774 printf(" %s\n", "(http://nsclient.ready2run.nl).");
743 printf(" %s\n", _("- Critical thresholds should be lower than warning thresholds")); 775 printf(" %s\n", _("- Critical thresholds should be lower than warning thresholds"));
744 printf(" %s\n", _("- Default port 1248 is sometimes in use by other services. The error")); 776 printf(" %s\n", _("- Default port 1248 is sometimes in use by other services. The error"));
745 printf(" %s\n", _("output when this happens contains \"Cannot map xxxxx to protocol number\".")); 777 printf(" %s\n",
778 _("output when this happens contains \"Cannot map xxxxx to protocol number\"."));
746 printf(" %s\n", _("One fix for this is to change the port to something else on check_nt ")); 779 printf(" %s\n", _("One fix for this is to change the port to something else on check_nt "));
747 printf(" %s\n", _("and on the client service it\'s connecting to.")); 780 printf(" %s\n", _("and on the client service it\'s connecting to."));
748 781
diff --git a/plugins/check_ntp.c b/plugins/check_ntp.c
index d33f8786..b22cc3c1 100644
--- a/plugins/check_ntp.c
+++ b/plugins/check_ntp.c
@@ -1,34 +1,34 @@
1/***************************************************************************** 1/*****************************************************************************
2* 2 *
3* Monitoring check_ntp plugin 3 * Monitoring check_ntp plugin
4* 4 *
5* License: GPL 5 * License: GPL
6* Copyright (c) 2006 Sean Finney <seanius@seanius.net> 6 * Copyright (c) 2006 Sean Finney <seanius@seanius.net>
7* Copyright (c) 2006-2024 Monitoring Plugins Development Team 7 * Copyright (c) 2006-2024 Monitoring Plugins Development Team
8* 8 *
9* Description: 9 * Description:
10* 10 *
11* This file contains the check_ntp plugin 11 * This file contains the check_ntp plugin
12* 12 *
13* This plugin to check ntp servers independent of any commandline 13 * This plugin to check ntp servers independent of any commandline
14* programs or external libraries. 14 * programs or external libraries.
15* 15 *
16* 16 *
17* This program is free software: you can redistribute it and/or modify 17 * This program is free software: you can redistribute it and/or modify
18* it under the terms of the GNU General Public License as published by 18 * it under the terms of the GNU General Public License as published by
19* the Free Software Foundation, either version 3 of the License, or 19 * the Free Software Foundation, either version 3 of the License, or
20* (at your option) any later version. 20 * (at your option) any later version.
21* 21 *
22* This program is distributed in the hope that it will be useful, 22 * This program is distributed in the hope that it will be useful,
23* but WITHOUT ANY WARRANTY; without even the implied warranty of 23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25* GNU General Public License for more details. 25 * GNU General Public License for more details.
26* 26 *
27* You should have received a copy of the GNU General Public License 27 * You should have received a copy of the GNU General Public License
28* along with this program. If not, see <http://www.gnu.org/licenses/>. 28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29* 29 *
30* 30 *
31*****************************************************************************/ 31 *****************************************************************************/
32 32
33const char *progname = "check_ntp"; 33const char *progname = "check_ntp";
34const char *copyright = "2006-2024"; 34const char *copyright = "2006-2024";
@@ -38,24 +38,24 @@ const char *email = "devel@monitoring-plugins.org";
38#include "netutils.h" 38#include "netutils.h"
39#include "utils.h" 39#include "utils.h"
40 40
41static char *server_address=NULL; 41static char *server_address = NULL;
42static int verbose=0; 42static int verbose = 0;
43static bool do_offset = false; 43static bool do_offset = false;
44static char *owarn="60"; 44static char *owarn = "60";
45static char *ocrit="120"; 45static char *ocrit = "120";
46static bool do_jitter = false; 46static bool do_jitter = false;
47static char *jwarn="5000"; 47static char *jwarn = "5000";
48static char *jcrit="10000"; 48static char *jcrit = "10000";
49 49
50static int process_arguments (int /*argc*/, char ** /*argv*/); 50static int process_arguments(int /*argc*/, char ** /*argv*/);
51static thresholds *offset_thresholds = NULL; 51static thresholds *offset_thresholds = NULL;
52static thresholds *jitter_thresholds = NULL; 52static thresholds *jitter_thresholds = NULL;
53static void print_help (void); 53static void print_help(void);
54void print_usage (void); 54void print_usage(void);
55 55
56/* number of times to perform each request to get a good average. */ 56/* number of times to perform each request to get a good average. */
57#ifndef AVG_NUM 57#ifndef AVG_NUM
58#define AVG_NUM 4 58# define AVG_NUM 4
59#endif 59#endif
60 60
61/* max size of control message data */ 61/* max size of control message data */
@@ -63,17 +63,17 @@ void print_usage (void);
63 63
64/* this structure holds everything in an ntp request/response as per rfc1305 */ 64/* this structure holds everything in an ntp request/response as per rfc1305 */
65typedef struct { 65typedef struct {
66 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */ 66 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
67 uint8_t stratum; /* clock stratum */ 67 uint8_t stratum; /* clock stratum */
68 int8_t poll; /* polling interval */ 68 int8_t poll; /* polling interval */
69 int8_t precision; /* precision of the local clock */ 69 int8_t precision; /* precision of the local clock */
70 int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */ 70 int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
71 uint32_t rtdisp; /* like above, but for max err to primary src */ 71 uint32_t rtdisp; /* like above, but for max err to primary src */
72 uint32_t refid; /* ref clock identifier */ 72 uint32_t refid; /* ref clock identifier */
73 uint64_t refts; /* reference timestamp. local time local clock */ 73 uint64_t refts; /* reference timestamp. local time local clock */
74 uint64_t origts; /* time at which request departed client */ 74 uint64_t origts; /* time at which request departed client */
75 uint64_t rxts; /* time at which request arrived at server */ 75 uint64_t rxts; /* time at which request arrived at server */
76 uint64_t txts; /* time at which request departed server */ 76 uint64_t txts; /* time at which request departed server */
77} ntp_message; 77} ntp_message;
78 78
79/* this structure holds data about results from querying offset from a peer */ 79/* this structure holds data about results from querying offset from a peer */
@@ -84,20 +84,20 @@ typedef struct {
84 double rtdelay; /* converted from the ntp_message */ 84 double rtdelay; /* converted from the ntp_message */
85 double rtdisp; /* converted from the ntp_message */ 85 double rtdisp; /* converted from the ntp_message */
86 double offset[AVG_NUM]; /* offsets from each response */ 86 double offset[AVG_NUM]; /* offsets from each response */
87 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */ 87 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
88} ntp_server_results; 88} ntp_server_results;
89 89
90/* this structure holds everything in an ntp control message as per rfc1305 */ 90/* this structure holds everything in an ntp control message as per rfc1305 */
91typedef struct { 91typedef struct {
92 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */ 92 uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
93 uint8_t op; /* R,E,M bits and Opcode */ 93 uint8_t op; /* R,E,M bits and Opcode */
94 uint16_t seq; /* Packet sequence */ 94 uint16_t seq; /* Packet sequence */
95 uint16_t status; /* Clock status */ 95 uint16_t status; /* Clock status */
96 uint16_t assoc; /* Association */ 96 uint16_t assoc; /* Association */
97 uint16_t offset; /* Similar to TCP sequence # */ 97 uint16_t offset; /* Similar to TCP sequence # */
98 uint16_t count; /* # bytes of data */ 98 uint16_t count; /* # bytes of data */
99 char data[MAX_CM_SIZE]; /* ASCII data of the request */ 99 char data[MAX_CM_SIZE]; /* ASCII data of the request */
100 /* NB: not necessarily NULL terminated! */ 100 /* NB: not necessarily NULL terminated! */
101} ntp_control_message; 101} ntp_control_message;
102 102
103/* this is an association/status-word pair found in control packet responses */ 103/* this is an association/status-word pair found in control packet responses */
@@ -108,38 +108,50 @@ typedef struct {
108 108
109/* bits 1,2 are the leap indicator */ 109/* bits 1,2 are the leap indicator */
110#define LI_MASK 0xc0 110#define LI_MASK 0xc0
111#define LI(x) ((x&LI_MASK)>>6) 111#define LI(x) ((x & LI_MASK) >> 6)
112#define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0) 112#define LI_SET(x, y) \
113 do { \
114 x |= ((y << 6) & LI_MASK); \
115 } while (0)
113/* and these are the values of the leap indicator */ 116/* and these are the values of the leap indicator */
114#define LI_NOWARNING 0x00 117#define LI_NOWARNING 0x00
115#define LI_EXTRASEC 0x01 118#define LI_EXTRASEC 0x01
116#define LI_MISSINGSEC 0x02 119#define LI_MISSINGSEC 0x02
117#define LI_ALARM 0x03 120#define LI_ALARM 0x03
118/* bits 3,4,5 are the ntp version */ 121/* bits 3,4,5 are the ntp version */
119#define VN_MASK 0x38 122#define VN_MASK 0x38
120#define VN(x) ((x&VN_MASK)>>3) 123#define VN(x) ((x & VN_MASK) >> 3)
121#define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0) 124#define VN_SET(x, y) \
125 do { \
126 x |= ((y << 3) & VN_MASK); \
127 } while (0)
122#define VN_RESERVED 0x02 128#define VN_RESERVED 0x02
123/* bits 6,7,8 are the ntp mode */ 129/* bits 6,7,8 are the ntp mode */
124#define MODE_MASK 0x07 130#define MODE_MASK 0x07
125#define MODE(x) (x&MODE_MASK) 131#define MODE(x) (x & MODE_MASK)
126#define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0) 132#define MODE_SET(x, y) \
133 do { \
134 x |= (y & MODE_MASK); \
135 } while (0)
127/* here are some values */ 136/* here are some values */
128#define MODE_CLIENT 0x03 137#define MODE_CLIENT 0x03
129#define MODE_CONTROLMSG 0x06 138#define MODE_CONTROLMSG 0x06
130/* In control message, bits 8-10 are R,E,M bits */ 139/* In control message, bits 8-10 are R,E,M bits */
131#define REM_MASK 0xe0 140#define REM_MASK 0xe0
132#define REM_RESP 0x80 141#define REM_RESP 0x80
133#define REM_ERROR 0x40 142#define REM_ERROR 0x40
134#define REM_MORE 0x20 143#define REM_MORE 0x20
135/* In control message, bits 11 - 15 are opcode */ 144/* In control message, bits 11 - 15 are opcode */
136#define OP_MASK 0x1f 145#define OP_MASK 0x1f
137#define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0) 146#define OP_SET(x, y) \
147 do { \
148 x |= (y & OP_MASK); \
149 } while (0)
138#define OP_READSTAT 0x01 150#define OP_READSTAT 0x01
139#define OP_READVAR 0x02 151#define OP_READVAR 0x02
140/* In peer status bytes, bits 6,7,8 determine clock selection status */ 152/* In peer status bytes, bits 6,7,8 determine clock selection status */
141#define PEER_SEL(x) ((ntohs(x)>>8)&0x07) 153#define PEER_SEL(x) ((ntohs(x) >> 8) & 0x07)
142#define PEER_INCLUDED 0x04 154#define PEER_INCLUDED 0x04
143#define PEER_SYNCSOURCE 0x06 155#define PEER_SYNCSOURCE 0x06
144 156
145/** 157/**
@@ -153,82 +165,92 @@ typedef struct {
153 165
154/* macros to access the left/right 16 bits of a 32-bit ntp "fixed point" 166/* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
155 number. note that these can be used as lvalues too */ 167 number. note that these can be used as lvalues too */
156#define L16(x) (((uint16_t*)&x)[0]) 168#define L16(x) (((uint16_t *)&x)[0])
157#define R16(x) (((uint16_t*)&x)[1]) 169#define R16(x) (((uint16_t *)&x)[1])
158/* macros to access the left/right 32 bits of a 64-bit ntp "fixed point" 170/* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
159 number. these too can be used as lvalues */ 171 number. these too can be used as lvalues */
160#define L32(x) (((uint32_t*)&x)[0]) 172#define L32(x) (((uint32_t *)&x)[0])
161#define R32(x) (((uint32_t*)&x)[1]) 173#define R32(x) (((uint32_t *)&x)[1])
162 174
163/* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */ 175/* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
164#define EPOCHDIFF 0x83aa7e80UL 176#define EPOCHDIFF 0x83aa7e80UL
165 177
166/* extract a 32-bit ntp fixed point number into a double */ 178/* extract a 32-bit ntp fixed point number into a double */
167#define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0) 179#define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x)) / 65536.0)
168 180
169/* likewise for a 64-bit ntp fp number */ 181/* likewise for a 64-bit ntp fp number */
170#define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\ 182#define NTP64asDOUBLE(n) \
171 (ntohl(L32(n))-EPOCHDIFF) + \ 183 (double)(((uint64_t)n) ? (ntohl(L32(n)) - EPOCHDIFF) + \
172 (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\ 184 (.00000001 * (0.5 + (double)(ntohl(R32(n)) / 42.94967296))) \
173 0) 185 : 0)
174 186
175/* convert a struct timeval to a double */ 187/* convert a struct timeval to a double */
176#define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec)) 188#define TVasDOUBLE(x) (double)(x.tv_sec + (0.000001 * x.tv_usec))
177 189
178/* convert an ntp 64-bit fp number to a struct timeval */ 190/* convert an ntp 64-bit fp number to a struct timeval */
179#define NTP64toTV(n,t) \ 191#define NTP64toTV(n, t) \
180 do{ if(!n) t.tv_sec = t.tv_usec = 0; \ 192 do { \
181 else { \ 193 if (!n) \
182 t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \ 194 t.tv_sec = t.tv_usec = 0; \
183 t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \ 195 else { \
184 } \ 196 t.tv_sec = ntohl(L32(n)) - EPOCHDIFF; \
185 }while(0) 197 t.tv_usec = (int)(0.5 + (double)(ntohl(R32(n)) / 4294.967296)); \
198 } \
199 } while (0)
186 200
187/* convert a struct timeval to an ntp 64-bit fp number */ 201/* convert a struct timeval to an ntp 64-bit fp number */
188#define TVtoNTP64(t,n) \ 202#define TVtoNTP64(t, n) \
189 do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \ 203 do { \
190 else { \ 204 if (!t.tv_usec && !t.tv_sec) \
191 L32(n)=htonl(t.tv_sec + EPOCHDIFF); \ 205 n = 0x0UL; \
192 R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \ 206 else { \
193 } \ 207 L32(n) = htonl(t.tv_sec + EPOCHDIFF); \
194 } while(0) 208 R32(n) = htonl((uint64_t)((4294.967296 * t.tv_usec) + .5)); \
209 } \
210 } while (0)
195 211
196/* NTP control message header is 12 bytes, plus any data in the data 212/* NTP control message header is 12 bytes, plus any data in the data
197 * field, plus null padding to the nearest 32-bit boundary per rfc. 213 * field, plus null padding to the nearest 32-bit boundary per rfc.
198 */ 214 */
199#define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((ntohs(m.count)%4)?4-(ntohs(m.count)%4):0)) 215#define SIZEOF_NTPCM(m) \
216 (12 + ntohs(m.count) + ((ntohs(m.count) % 4) ? 4 - (ntohs(m.count) % 4) : 0))
200 217
201/* finally, a little helper or two for debugging: */ 218/* finally, a little helper or two for debugging: */
202#define DBG(x) do{if(verbose>1){ x; }}while(0); 219#define DBG(x) \
203#define PRINTSOCKADDR(x) \ 220 do { \
204 do{ \ 221 if (verbose > 1) { \
205 printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\ 222 x; \
206 }while(0); 223 } \
224 } while (0);
225#define PRINTSOCKADDR(x) \
226 do { \
227 printf("%u.%u.%u.%u", (x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff); \
228 } while (0);
207 229
208/* calculate the offset of the local clock */ 230/* calculate the offset of the local clock */
209static inline double calc_offset(const ntp_message *m, const struct timeval *t){ 231static inline double calc_offset(const ntp_message *m, const struct timeval *t) {
210 double client_tx, peer_rx, peer_tx, client_rx; 232 double client_tx, peer_rx, peer_tx, client_rx;
211 client_tx = NTP64asDOUBLE(m->origts); 233 client_tx = NTP64asDOUBLE(m->origts);
212 peer_rx = NTP64asDOUBLE(m->rxts); 234 peer_rx = NTP64asDOUBLE(m->rxts);
213 peer_tx = NTP64asDOUBLE(m->txts); 235 peer_tx = NTP64asDOUBLE(m->txts);
214 client_rx=TVasDOUBLE((*t)); 236 client_rx = TVasDOUBLE((*t));
215 return (.5*((peer_tx-client_rx)+(peer_rx-client_tx))); 237 return (.5 * ((peer_tx - client_rx) + (peer_rx - client_tx)));
216} 238}
217 239
218/* print out a ntp packet in human readable/debuggable format */ 240/* print out a ntp packet in human readable/debuggable format */
219void print_ntp_message(const ntp_message *p){ 241void print_ntp_message(const ntp_message *p) {
220 struct timeval ref, orig, rx, tx; 242 struct timeval ref, orig, rx, tx;
221 243
222 NTP64toTV(p->refts,ref); 244 NTP64toTV(p->refts, ref);
223 NTP64toTV(p->origts,orig); 245 NTP64toTV(p->origts, orig);
224 NTP64toTV(p->rxts,rx); 246 NTP64toTV(p->rxts, rx);
225 NTP64toTV(p->txts,tx); 247 NTP64toTV(p->txts, tx);
226 248
227 printf("packet contents:\n"); 249 printf("packet contents:\n");
228 printf("\tflags: 0x%.2x\n", p->flags); 250 printf("\tflags: 0x%.2x\n", p->flags);
229 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK); 251 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags & LI_MASK);
230 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK); 252 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags & VN_MASK);
231 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK); 253 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags & MODE_MASK);
232 printf("\tstratum = %d\n", p->stratum); 254 printf("\tstratum = %d\n", p->stratum);
233 printf("\tpoll = %g\n", pow(2, p->poll)); 255 printf("\tpoll = %g\n", pow(2, p->poll));
234 printf("\tprecision = %g\n", pow(2, p->precision)); 256 printf("\tprecision = %g\n", pow(2, p->precision));
@@ -241,32 +263,31 @@ void print_ntp_message(const ntp_message *p){
241 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts)); 263 printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
242} 264}
243 265
244void print_ntp_control_message(const ntp_control_message *p){ 266void print_ntp_control_message(const ntp_control_message *p) {
245 int i=0, numpeers=0; 267 int i = 0, numpeers = 0;
246 const ntp_assoc_status_pair *peer=NULL; 268 const ntp_assoc_status_pair *peer = NULL;
247 269
248 printf("control packet contents:\n"); 270 printf("control packet contents:\n");
249 printf("\tflags: 0x%.2x , 0x%.2x\n", p->flags, p->op); 271 printf("\tflags: 0x%.2x , 0x%.2x\n", p->flags, p->op);
250 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK); 272 printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags & LI_MASK);
251 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK); 273 printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags & VN_MASK);
252 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK); 274 printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags & MODE_MASK);
253 printf("\t response=%d (0x%.2x)\n", (p->op&REM_RESP)>0, p->op&REM_RESP); 275 printf("\t response=%d (0x%.2x)\n", (p->op & REM_RESP) > 0, p->op & REM_RESP);
254 printf("\t more=%d (0x%.2x)\n", (p->op&REM_MORE)>0, p->op&REM_MORE); 276 printf("\t more=%d (0x%.2x)\n", (p->op & REM_MORE) > 0, p->op & REM_MORE);
255 printf("\t error=%d (0x%.2x)\n", (p->op&REM_ERROR)>0, p->op&REM_ERROR); 277 printf("\t error=%d (0x%.2x)\n", (p->op & REM_ERROR) > 0, p->op & REM_ERROR);
256 printf("\t op=%d (0x%.2x)\n", p->op&OP_MASK, p->op&OP_MASK); 278 printf("\t op=%d (0x%.2x)\n", p->op & OP_MASK, p->op & OP_MASK);
257 printf("\tsequence: %d (0x%.2x)\n", ntohs(p->seq), ntohs(p->seq)); 279 printf("\tsequence: %d (0x%.2x)\n", ntohs(p->seq), ntohs(p->seq));
258 printf("\tstatus: %d (0x%.2x)\n", ntohs(p->status), ntohs(p->status)); 280 printf("\tstatus: %d (0x%.2x)\n", ntohs(p->status), ntohs(p->status));
259 printf("\tassoc: %d (0x%.2x)\n", ntohs(p->assoc), ntohs(p->assoc)); 281 printf("\tassoc: %d (0x%.2x)\n", ntohs(p->assoc), ntohs(p->assoc));
260 printf("\toffset: %d (0x%.2x)\n", ntohs(p->offset), ntohs(p->offset)); 282 printf("\toffset: %d (0x%.2x)\n", ntohs(p->offset), ntohs(p->offset));
261 printf("\tcount: %d (0x%.2x)\n", ntohs(p->count), ntohs(p->count)); 283 printf("\tcount: %d (0x%.2x)\n", ntohs(p->count), ntohs(p->count));
262 numpeers=ntohs(p->count)/(sizeof(ntp_assoc_status_pair)); 284 numpeers = ntohs(p->count) / (sizeof(ntp_assoc_status_pair));
263 if(p->op&REM_RESP && p->op&OP_READSTAT){ 285 if (p->op & REM_RESP && p->op & OP_READSTAT) {
264 peer=(ntp_assoc_status_pair*)p->data; 286 peer = (ntp_assoc_status_pair *)p->data;
265 for(i=0;i<numpeers;i++){ 287 for (i = 0; i < numpeers; i++) {
266 printf("\tpeer id %.2x status %.2x", 288 printf("\tpeer id %.2x status %.2x", ntohs(peer[i].assoc), ntohs(peer[i].status));
267 ntohs(peer[i].assoc), ntohs(peer[i].status)); 289 if (PEER_SEL(peer[i].status) >= PEER_INCLUDED) {
268 if (PEER_SEL(peer[i].status) >= PEER_INCLUDED){ 290 if (PEER_SEL(peer[i].status) >= PEER_SYNCSOURCE) {
269 if(PEER_SEL(peer[i].status) >= PEER_SYNCSOURCE){
270 printf(" <-- current sync source"); 291 printf(" <-- current sync source");
271 } else { 292 } else {
272 printf(" <-- current sync candidate"); 293 printf(" <-- current sync candidate");
@@ -277,41 +298,45 @@ void print_ntp_control_message(const ntp_control_message *p){
277 } 298 }
278} 299}
279 300
280void setup_request(ntp_message *p){ 301void setup_request(ntp_message *p) {
281 struct timeval t; 302 struct timeval t;
282 303
283 memset(p, 0, sizeof(ntp_message)); 304 memset(p, 0, sizeof(ntp_message));
284 LI_SET(p->flags, LI_ALARM); 305 LI_SET(p->flags, LI_ALARM);
285 VN_SET(p->flags, 4); 306 VN_SET(p->flags, 4);
286 MODE_SET(p->flags, MODE_CLIENT); 307 MODE_SET(p->flags, MODE_CLIENT);
287 p->poll=4; 308 p->poll = 4;
288 p->precision=(int8_t)0xfa; 309 p->precision = (int8_t)0xfa;
289 L16(p->rtdelay)=htons(1); 310 L16(p->rtdelay) = htons(1);
290 L16(p->rtdisp)=htons(1); 311 L16(p->rtdisp) = htons(1);
291 312
292 gettimeofday(&t, NULL); 313 gettimeofday(&t, NULL);
293 TVtoNTP64(t,p->txts); 314 TVtoNTP64(t, p->txts);
294} 315}
295 316
296/* select the "best" server from a list of servers, and return its index. 317/* select the "best" server from a list of servers, and return its index.
297 * this is done by filtering servers based on stratum, dispersion, and 318 * this is done by filtering servers based on stratum, dispersion, and
298 * finally round-trip delay. */ 319 * finally round-trip delay. */
299int best_offset_server(const ntp_server_results *slist, int nservers){ 320int best_offset_server(const ntp_server_results *slist, int nservers) {
300 int cserver=0, best_server=-1; 321 int cserver = 0, best_server = -1;
301 322
302 /* for each server */ 323 /* for each server */
303 for(cserver=0; cserver<nservers; cserver++){ 324 for (cserver = 0; cserver < nservers; cserver++) {
304 /* We don't want any servers that fails these tests */ 325 /* We don't want any servers that fails these tests */
305 /* Sort out servers that didn't respond or responede with a 0 stratum; 326 /* Sort out servers that didn't respond or responede with a 0 stratum;
306 * stratum 0 is for reference clocks so no NTP server should ever report 327 * stratum 0 is for reference clocks so no NTP server should ever report
307 * a stratum 0 */ 328 * a stratum 0 */
308 if ( slist[cserver].stratum == 0){ 329 if (slist[cserver].stratum == 0) {
309 if (verbose) printf("discarding peer %d: stratum=%d\n", cserver, slist[cserver].stratum); 330 if (verbose) {
331 printf("discarding peer %d: stratum=%d\n", cserver, slist[cserver].stratum);
332 }
310 continue; 333 continue;
311 } 334 }
312 /* Sort out servers with error flags */ 335 /* Sort out servers with error flags */
313 if ( LI(slist[cserver].flags) == LI_ALARM ){ 336 if (LI(slist[cserver].flags) == LI_ALARM) {
314 if (verbose) printf("discarding peer %d: flags=%d\n", cserver, LI(slist[cserver].flags)); 337 if (verbose) {
338 printf("discarding peer %d: flags=%d\n", cserver, LI(slist[cserver].flags));
339 }
315 continue; 340 continue;
316 } 341 }
317 342
@@ -325,13 +350,13 @@ int best_offset_server(const ntp_server_results *slist, int nservers){
325 /* compare the server to the best one we've seen so far */ 350 /* compare the server to the best one we've seen so far */
326 /* does it have an equal or better stratum? */ 351 /* does it have an equal or better stratum? */
327 DBG(printf("comparing peer %d with peer %d\n", cserver, best_server)); 352 DBG(printf("comparing peer %d with peer %d\n", cserver, best_server));
328 if(slist[cserver].stratum <= slist[best_server].stratum){ 353 if (slist[cserver].stratum <= slist[best_server].stratum) {
329 DBG(printf("stratum for peer %d <= peer %d\n", cserver, best_server)); 354 DBG(printf("stratum for peer %d <= peer %d\n", cserver, best_server));
330 /* does it have an equal or better dispersion? */ 355 /* does it have an equal or better dispersion? */
331 if(slist[cserver].rtdisp <= slist[best_server].rtdisp){ 356 if (slist[cserver].rtdisp <= slist[best_server].rtdisp) {
332 DBG(printf("dispersion for peer %d <= peer %d\n", cserver, best_server)); 357 DBG(printf("dispersion for peer %d <= peer %d\n", cserver, best_server));
333 /* does it have a better rtdelay? */ 358 /* does it have a better rtdelay? */
334 if(slist[cserver].rtdelay < slist[best_server].rtdelay){ 359 if (slist[cserver].rtdelay < slist[best_server].rtdelay) {
335 DBG(printf("rtdelay for peer %d < peer %d\n", cserver, best_server)); 360 DBG(printf("rtdelay for peer %d < peer %d\n", cserver, best_server));
336 best_server = cserver; 361 best_server = cserver;
337 DBG(printf("peer %d is now our best candidate\n", best_server)); 362 DBG(printf("peer %d is now our best candidate\n", best_server));
@@ -340,7 +365,7 @@ int best_offset_server(const ntp_server_results *slist, int nservers){
340 } 365 }
341 } 366 }
342 367
343 if(best_server >= 0) { 368 if (best_server >= 0) {
344 DBG(printf("best server selected: peer %d\n", best_server)); 369 DBG(printf("best server selected: peer %d\n", best_server));
345 return best_server; 370 return best_server;
346 } else { 371 } else {
@@ -354,16 +379,16 @@ int best_offset_server(const ntp_server_results *slist, int nservers){
354 * we don't waste time sitting around waiting for single packets. 379 * we don't waste time sitting around waiting for single packets.
355 * - we also "manually" handle resolving host names and connecting, because 380 * - we also "manually" handle resolving host names and connecting, because
356 * we have to do it in a way that our lazy macros don't handle currently :( */ 381 * we have to do it in a way that our lazy macros don't handle currently :( */
357double offset_request(const char *host, int *status){ 382double offset_request(const char *host, int *status) {
358 int i=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0; 383 int i = 0, ga_result = 0, num_hosts = 0, *socklist = NULL, respnum = 0;
359 int servers_completed=0, one_read=0, servers_readable=0, best_index=-1; 384 int servers_completed = 0, one_read = 0, servers_readable = 0, best_index = -1;
360 time_t now_time=0, start_ts=0; 385 time_t now_time = 0, start_ts = 0;
361 ntp_message *req=NULL; 386 ntp_message *req = NULL;
362 double avg_offset=0.; 387 double avg_offset = 0.;
363 struct timeval recv_time; 388 struct timeval recv_time;
364 struct addrinfo *ai=NULL, *ai_tmp=NULL, hints; 389 struct addrinfo *ai = NULL, *ai_tmp = NULL, hints;
365 struct pollfd *ufds=NULL; 390 struct pollfd *ufds = NULL;
366 ntp_server_results *servers=NULL; 391 ntp_server_results *servers = NULL;
367 392
368 /* setup hints to only return results from getaddrinfo that we'd like */ 393 /* setup hints to only return results from getaddrinfo that we'd like */
369 memset(&hints, 0, sizeof(struct addrinfo)); 394 memset(&hints, 0, sizeof(struct addrinfo));
@@ -373,97 +398,112 @@ double offset_request(const char *host, int *status){
373 398
374 /* fill in ai with the list of hosts resolved by the host name */ 399 /* fill in ai with the list of hosts resolved by the host name */
375 ga_result = getaddrinfo(host, "123", &hints, &ai); 400 ga_result = getaddrinfo(host, "123", &hints, &ai);
376 if(ga_result!=0){ 401 if (ga_result != 0) {
377 die(STATE_UNKNOWN, "error getting address for %s: %s\n", 402 die(STATE_UNKNOWN, "error getting address for %s: %s\n", host, gai_strerror(ga_result));
378 host, gai_strerror(ga_result));
379 } 403 }
380 404
381 /* count the number of returned hosts, and allocate stuff accordingly */ 405 /* count the number of returned hosts, and allocate stuff accordingly */
382 for(ai_tmp=ai; ai_tmp!=NULL; ai_tmp=ai_tmp->ai_next){ num_hosts++; } 406 for (ai_tmp = ai; ai_tmp != NULL; ai_tmp = ai_tmp->ai_next) {
383 req=(ntp_message*)malloc(sizeof(ntp_message)*num_hosts); 407 num_hosts++;
384 if(req==NULL) die(STATE_UNKNOWN, "can not allocate ntp message array"); 408 }
385 socklist=(int*)malloc(sizeof(int)*num_hosts); 409 req = (ntp_message *)malloc(sizeof(ntp_message) * num_hosts);
386 if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array"); 410 if (req == NULL) {
387 ufds=(struct pollfd*)malloc(sizeof(struct pollfd)*num_hosts); 411 die(STATE_UNKNOWN, "can not allocate ntp message array");
388 if(ufds==NULL) die(STATE_UNKNOWN, "can not allocate socket array"); 412 }
389 servers=(ntp_server_results*)malloc(sizeof(ntp_server_results)*num_hosts); 413 socklist = (int *)malloc(sizeof(int) * num_hosts);
390 if(servers==NULL) die(STATE_UNKNOWN, "can not allocate server array"); 414 if (socklist == NULL) {
391 memset(servers, 0, sizeof(ntp_server_results)*num_hosts); 415 die(STATE_UNKNOWN, "can not allocate socket array");
416 }
417 ufds = (struct pollfd *)malloc(sizeof(struct pollfd) * num_hosts);
418 if (ufds == NULL) {
419 die(STATE_UNKNOWN, "can not allocate socket array");
420 }
421 servers = (ntp_server_results *)malloc(sizeof(ntp_server_results) * num_hosts);
422 if (servers == NULL) {
423 die(STATE_UNKNOWN, "can not allocate server array");
424 }
425 memset(servers, 0, sizeof(ntp_server_results) * num_hosts);
392 DBG(printf("Found %d peers to check\n", num_hosts)); 426 DBG(printf("Found %d peers to check\n", num_hosts));
393 427
394 /* setup each socket for writing, and the corresponding struct pollfd */ 428 /* setup each socket for writing, and the corresponding struct pollfd */
395 ai_tmp=ai; 429 ai_tmp = ai;
396 for(i=0;ai_tmp;i++){ 430 for (i = 0; ai_tmp; i++) {
397 socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP); 431 socklist[i] = socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
398 if(socklist[i] == -1) { 432 if (socklist[i] == -1) {
399 perror(NULL); 433 perror(NULL);
400 die(STATE_UNKNOWN, "can not create new socket"); 434 die(STATE_UNKNOWN, "can not create new socket");
401 } 435 }
402 if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){ 436 if (connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)) {
403 /* don't die here, because it is enough if there is one server 437 /* don't die here, because it is enough if there is one server
404 answering in time. This also would break for dual ipv4/6 stacked 438 answering in time. This also would break for dual ipv4/6 stacked
405 ntp servers when the client only supports on of them. 439 ntp servers when the client only supports on of them.
406 */ 440 */
407 DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno))); 441 DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno)));
408 } else { 442 } else {
409 ufds[i].fd=socklist[i]; 443 ufds[i].fd = socklist[i];
410 ufds[i].events=POLLIN; 444 ufds[i].events = POLLIN;
411 ufds[i].revents=0; 445 ufds[i].revents = 0;
412 } 446 }
413 ai_tmp = ai_tmp->ai_next; 447 ai_tmp = ai_tmp->ai_next;
414 } 448 }
415 449
416 /* now do AVG_NUM checks to each host. we stop before timeout/2 seconds 450 /* now do AVG_NUM checks to each host. we stop before timeout/2 seconds
417 * have passed in order to ensure post-processing and jitter time. */ 451 * have passed in order to ensure post-processing and jitter time. */
418 now_time=start_ts=time(NULL); 452 now_time = start_ts = time(NULL);
419 while(servers_completed<num_hosts && now_time-start_ts <= socket_timeout/2){ 453 while (servers_completed < num_hosts && now_time - start_ts <= socket_timeout / 2) {
420 /* loop through each server and find each one which hasn't 454 /* loop through each server and find each one which hasn't
421 * been touched in the past second or so and is still lacking 455 * been touched in the past second or so and is still lacking
422 * some responses. for each of these servers, send a new request, 456 * some responses. for each of these servers, send a new request,
423 * and update the "waiting" timestamp with the current time. */ 457 * and update the "waiting" timestamp with the current time. */
424 now_time=time(NULL); 458 now_time = time(NULL);
425 459
426 for(i=0; i<num_hosts; i++){ 460 for (i = 0; i < num_hosts; i++) {
427 if(servers[i].waiting<now_time && servers[i].num_responses<AVG_NUM){ 461 if (servers[i].waiting < now_time && servers[i].num_responses < AVG_NUM) {
428 if(verbose && servers[i].waiting != 0) printf("re-"); 462 if (verbose && servers[i].waiting != 0) {
429 if(verbose) printf("sending request to peer %d\n", i); 463 printf("re-");
464 }
465 if (verbose) {
466 printf("sending request to peer %d\n", i);
467 }
430 setup_request(&req[i]); 468 setup_request(&req[i]);
431 write(socklist[i], &req[i], sizeof(ntp_message)); 469 write(socklist[i], &req[i], sizeof(ntp_message));
432 servers[i].waiting=now_time; 470 servers[i].waiting = now_time;
433 break; 471 break;
434 } 472 }
435 } 473 }
436 474
437 /* quickly poll for any sockets with pending data */ 475 /* quickly poll for any sockets with pending data */
438 servers_readable=poll(ufds, num_hosts, 100); 476 servers_readable = poll(ufds, num_hosts, 100);
439 if(servers_readable==-1){ 477 if (servers_readable == -1) {
440 perror("polling ntp sockets"); 478 perror("polling ntp sockets");
441 die(STATE_UNKNOWN, "communication errors"); 479 die(STATE_UNKNOWN, "communication errors");
442 } 480 }
443 481
444 /* read from any sockets with pending data */ 482 /* read from any sockets with pending data */
445 for(i=0; servers_readable && i<num_hosts; i++){ 483 for (i = 0; servers_readable && i < num_hosts; i++) {
446 if(ufds[i].revents&POLLIN && servers[i].num_responses < AVG_NUM){ 484 if (ufds[i].revents & POLLIN && servers[i].num_responses < AVG_NUM) {
447 if(verbose) { 485 if (verbose) {
448 printf("response from peer %d: ", i); 486 printf("response from peer %d: ", i);
449 } 487 }
450 488
451 read(ufds[i].fd, &req[i], sizeof(ntp_message)); 489 read(ufds[i].fd, &req[i], sizeof(ntp_message));
452 gettimeofday(&recv_time, NULL); 490 gettimeofday(&recv_time, NULL);
453 DBG(print_ntp_message(&req[i])); 491 DBG(print_ntp_message(&req[i]));
454 respnum=servers[i].num_responses++; 492 respnum = servers[i].num_responses++;
455 servers[i].offset[respnum]=calc_offset(&req[i], &recv_time); 493 servers[i].offset[respnum] = calc_offset(&req[i], &recv_time);
456 if(verbose) { 494 if (verbose) {
457 printf("offset %.10g\n", servers[i].offset[respnum]); 495 printf("offset %.10g\n", servers[i].offset[respnum]);
458 } 496 }
459 servers[i].stratum=req[i].stratum; 497 servers[i].stratum = req[i].stratum;
460 servers[i].rtdisp=NTP32asDOUBLE(req[i].rtdisp); 498 servers[i].rtdisp = NTP32asDOUBLE(req[i].rtdisp);
461 servers[i].rtdelay=NTP32asDOUBLE(req[i].rtdelay); 499 servers[i].rtdelay = NTP32asDOUBLE(req[i].rtdelay);
462 servers[i].waiting=0; 500 servers[i].waiting = 0;
463 servers[i].flags=req[i].flags; 501 servers[i].flags = req[i].flags;
464 servers_readable--; 502 servers_readable--;
465 one_read = 1; 503 one_read = 1;
466 if(servers[i].num_responses==AVG_NUM) servers_completed++; 504 if (servers[i].num_responses == AVG_NUM) {
505 servers_completed++;
506 }
467 } 507 }
468 } 508 }
469 /* lather, rinse, repeat. */ 509 /* lather, rinse, repeat. */
@@ -474,15 +514,15 @@ double offset_request(const char *host, int *status){
474 } 514 }
475 515
476 /* now, pick the best server from the list */ 516 /* now, pick the best server from the list */
477 best_index=best_offset_server(servers, num_hosts); 517 best_index = best_offset_server(servers, num_hosts);
478 if(best_index < 0){ 518 if (best_index < 0) {
479 *status=STATE_UNKNOWN; 519 *status = STATE_UNKNOWN;
480 } else { 520 } else {
481 /* finally, calculate the average offset */ 521 /* finally, calculate the average offset */
482 for(i=0; i<servers[best_index].num_responses;i++){ 522 for (i = 0; i < servers[best_index].num_responses; i++) {
483 avg_offset+=servers[best_index].offset[i]; 523 avg_offset += servers[best_index].offset[i];
484 } 524 }
485 avg_offset/=servers[best_index].num_responses; 525 avg_offset /= servers[best_index].num_responses;
486 } 526 }
487 527
488 /* cleanup */ 528 /* cleanup */
@@ -496,12 +536,13 @@ double offset_request(const char *host, int *status){
496 free(req); 536 free(req);
497 freeaddrinfo(ai); 537 freeaddrinfo(ai);
498 538
499 if(verbose) printf("overall average offset: %.10g\n", avg_offset); 539 if (verbose) {
540 printf("overall average offset: %.10g\n", avg_offset);
541 }
500 return avg_offset; 542 return avg_offset;
501} 543}
502 544
503void 545void setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq) {
504setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
505 memset(p, 0, sizeof(ntp_control_message)); 546 memset(p, 0, sizeof(ntp_control_message));
506 LI_SET(p->flags, LI_NOWARNING); 547 LI_SET(p->flags, LI_NOWARNING);
507 VN_SET(p->flags, VN_RESERVED); 548 VN_SET(p->flags, VN_RESERVED);
@@ -512,16 +553,16 @@ setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
512} 553}
513 554
514/* XXX handle responses with the error bit set */ 555/* XXX handle responses with the error bit set */
515double jitter_request(int *status){ 556double jitter_request(int *status) {
516 int conn=-1, i, npeers=0, num_candidates=0; 557 int conn = -1, i, npeers = 0, num_candidates = 0;
517 bool syncsource_found = false; 558 bool syncsource_found = false;
518 int run=0, min_peer_sel=PEER_INCLUDED, num_selected=0, num_valid=0; 559 int run = 0, min_peer_sel = PEER_INCLUDED, num_selected = 0, num_valid = 0;
519 int peers_size=0, peer_offset=0; 560 int peers_size = 0, peer_offset = 0;
520 ntp_assoc_status_pair *peers=NULL; 561 ntp_assoc_status_pair *peers = NULL;
521 ntp_control_message req; 562 ntp_control_message req;
522 const char *getvar = "jitter"; 563 const char *getvar = "jitter";
523 double rval = 0.0, jitter = -1.0; 564 double rval = 0.0, jitter = -1.0;
524 char *startofvalue=NULL, *nptr=NULL; 565 char *startofvalue = NULL, *nptr = NULL;
525 void *tmp; 566 void *tmp;
526 567
527 /* Long-winded explanation: 568 /* Long-winded explanation:
@@ -542,54 +583,62 @@ double jitter_request(int *status){
542 583
543 /* keep sending requests until the server stops setting the 584 /* keep sending requests until the server stops setting the
544 * REM_MORE bit, though usually this is only 1 packet. */ 585 * REM_MORE bit, though usually this is only 1 packet. */
545 do{ 586 do {
546 setup_control_request(&req, OP_READSTAT, 1); 587 setup_control_request(&req, OP_READSTAT, 1);
547 DBG(printf("sending READSTAT request")); 588 DBG(printf("sending READSTAT request"));
548 write(conn, &req, SIZEOF_NTPCM(req)); 589 write(conn, &req, SIZEOF_NTPCM(req));
549 DBG(print_ntp_control_message(&req)); 590 DBG(print_ntp_control_message(&req));
550 /* Attempt to read the largest size packet possible */ 591 /* Attempt to read the largest size packet possible */
551 req.count=htons(MAX_CM_SIZE); 592 req.count = htons(MAX_CM_SIZE);
552 DBG(printf("receiving READSTAT response")) 593 DBG(printf("receiving READSTAT response"))
553 read(conn, &req, SIZEOF_NTPCM(req)); 594 read(conn, &req, SIZEOF_NTPCM(req));
554 DBG(print_ntp_control_message(&req)); 595 DBG(print_ntp_control_message(&req));
555 /* Each peer identifier is 4 bytes in the data section, which 596 /* Each peer identifier is 4 bytes in the data section, which
556 * we represent as a ntp_assoc_status_pair datatype. 597 * we represent as a ntp_assoc_status_pair datatype.
557 */ 598 */
558 peers_size+=ntohs(req.count); 599 peers_size += ntohs(req.count);
559 if((tmp=realloc(peers, peers_size)) == NULL) 600 if ((tmp = realloc(peers, peers_size)) == NULL) {
560 free(peers), die(STATE_UNKNOWN, "can not (re)allocate 'peers' buffer\n"); 601 free(peers), die(STATE_UNKNOWN, "can not (re)allocate 'peers' buffer\n");
561 peers=tmp; 602 }
562 memcpy((void*)((ptrdiff_t)peers+peer_offset), (void*)req.data, ntohs(req.count)); 603 peers = tmp;
563 npeers=peers_size/sizeof(ntp_assoc_status_pair); 604 memcpy((void *)((ptrdiff_t)peers + peer_offset), (void *)req.data, ntohs(req.count));
564 peer_offset+=ntohs(req.count); 605 npeers = peers_size / sizeof(ntp_assoc_status_pair);
565 } while(req.op&REM_MORE); 606 peer_offset += ntohs(req.count);
607 } while (req.op & REM_MORE);
566 608
567 /* first, let's find out if we have a sync source, or if there are 609 /* first, let's find out if we have a sync source, or if there are
568 * at least some candidates. in the case of the latter we'll issue 610 * at least some candidates. in the case of the latter we'll issue
569 * a warning but go ahead with the check on them. */ 611 * a warning but go ahead with the check on them. */
570 for (i = 0; i < npeers; i++){ 612 for (i = 0; i < npeers; i++) {
571 if (PEER_SEL(peers[i].status) >= PEER_INCLUDED){ 613 if (PEER_SEL(peers[i].status) >= PEER_INCLUDED) {
572 num_candidates++; 614 num_candidates++;
573 if(PEER_SEL(peers[i].status) >= PEER_SYNCSOURCE){ 615 if (PEER_SEL(peers[i].status) >= PEER_SYNCSOURCE) {
574 syncsource_found = true; 616 syncsource_found = true;
575 min_peer_sel=PEER_SYNCSOURCE; 617 min_peer_sel = PEER_SYNCSOURCE;
576 } 618 }
577 } 619 }
578 } 620 }
579 if(verbose) printf("%d candidate peers available\n", num_candidates); 621 if (verbose) {
580 if(verbose && syncsource_found) printf("synchronization source found\n"); 622 printf("%d candidate peers available\n", num_candidates);
581 if(! syncsource_found){ 623 }
624 if (verbose && syncsource_found) {
625 printf("synchronization source found\n");
626 }
627 if (!syncsource_found) {
582 *status = STATE_UNKNOWN; 628 *status = STATE_UNKNOWN;
583 if(verbose) printf("warning: no synchronization source found\n"); 629 if (verbose) {
630 printf("warning: no synchronization source found\n");
631 }
584 } 632 }
585 633
586 634 for (run = 0; run < AVG_NUM; run++) {
587 for (run=0; run<AVG_NUM; run++){ 635 if (verbose) {
588 if(verbose) printf("jitter run %d of %d\n", run+1, AVG_NUM); 636 printf("jitter run %d of %d\n", run + 1, AVG_NUM);
589 for (i = 0; i < npeers; i++){ 637 }
638 for (i = 0; i < npeers; i++) {
590 /* Only query this server if it is the current sync source */ 639 /* Only query this server if it is the current sync source */
591 if (PEER_SEL(peers[i].status) >= min_peer_sel){ 640 if (PEER_SEL(peers[i].status) >= min_peer_sel) {
592 char jitter_data[MAX_CM_SIZE+1]; 641 char jitter_data[MAX_CM_SIZE + 1];
593 size_t jitter_data_count; 642 size_t jitter_data_count;
594 643
595 num_selected++; 644 num_selected++;
@@ -602,7 +651,7 @@ double jitter_request(int *status){
602 */ 651 */
603 /* Older servers doesn't know what jitter is, so if we get an 652 /* Older servers doesn't know what jitter is, so if we get an
604 * error on the first pass we redo it with "dispersion" */ 653 * error on the first pass we redo it with "dispersion" */
605 strncpy(req.data, getvar, MAX_CM_SIZE-1); 654 strncpy(req.data, getvar, MAX_CM_SIZE - 1);
606 req.count = htons(strlen(getvar)); 655 req.count = htons(strlen(getvar));
607 DBG(printf("sending READVAR request...\n")); 656 DBG(printf("sending READVAR request...\n"));
608 write(conn, &req, SIZEOF_NTPCM(req)); 657 write(conn, &req, SIZEOF_NTPCM(req));
@@ -613,8 +662,11 @@ double jitter_request(int *status){
613 read(conn, &req, SIZEOF_NTPCM(req)); 662 read(conn, &req, SIZEOF_NTPCM(req));
614 DBG(print_ntp_control_message(&req)); 663 DBG(print_ntp_control_message(&req));
615 664
616 if(req.op&REM_ERROR && strstr(getvar, "jitter")) { 665 if (req.op & REM_ERROR && strstr(getvar, "jitter")) {
617 if(verbose) printf("The 'jitter' command failed (old ntp server?)\nRestarting with 'dispersion'...\n"); 666 if (verbose) {
667 printf("The 'jitter' command failed (old ntp server?)\nRestarting with "
668 "'dispersion'...\n");
669 }
618 getvar = "dispersion"; 670 getvar = "dispersion";
619 num_selected--; 671 num_selected--;
620 i--; 672 i--;
@@ -622,32 +674,33 @@ double jitter_request(int *status){
622 } 674 }
623 675
624 /* get to the float value */ 676 /* get to the float value */
625 if(verbose) { 677 if (verbose) {
626 printf("parsing jitter from peer %.2x: ", ntohs(peers[i].assoc)); 678 printf("parsing jitter from peer %.2x: ", ntohs(peers[i].assoc));
627 } 679 }
628 if((jitter_data_count = ntohs(req.count)) >= sizeof(jitter_data)){ 680 if ((jitter_data_count = ntohs(req.count)) >= sizeof(jitter_data)) {
629 die(STATE_UNKNOWN, 681 die(STATE_UNKNOWN, _("jitter response too large (%lu bytes)\n"),
630 _("jitter response too large (%lu bytes)\n"), 682 (unsigned long)jitter_data_count);
631 (unsigned long)jitter_data_count);
632 } 683 }
633 memcpy(jitter_data, req.data, jitter_data_count); 684 memcpy(jitter_data, req.data, jitter_data_count);
634 jitter_data[jitter_data_count] = '\0'; 685 jitter_data[jitter_data_count] = '\0';
635 startofvalue = strchr(jitter_data, '='); 686 startofvalue = strchr(jitter_data, '=');
636 if(startofvalue != NULL) { 687 if (startofvalue != NULL) {
637 startofvalue++; 688 startofvalue++;
638 jitter = strtod(startofvalue, &nptr); 689 jitter = strtod(startofvalue, &nptr);
639 } 690 }
640 if(startofvalue == NULL || startofvalue==nptr){ 691 if (startofvalue == NULL || startofvalue == nptr) {
641 printf("warning: unable to read server jitter response.\n"); 692 printf("warning: unable to read server jitter response.\n");
642 *status = STATE_UNKNOWN; 693 *status = STATE_UNKNOWN;
643 } else { 694 } else {
644 if(verbose) printf("%g\n", jitter); 695 if (verbose) {
696 printf("%g\n", jitter);
697 }
645 num_valid++; 698 num_valid++;
646 rval += jitter; 699 rval += jitter;
647 } 700 }
648 } 701 }
649 } 702 }
650 if(verbose){ 703 if (verbose) {
651 printf("jitter parsed from %d/%d peers\n", num_valid, num_selected); 704 printf("jitter parsed from %d/%d peers\n", num_valid, num_selected);
652 } 705 }
653 } 706 }
@@ -655,37 +708,33 @@ double jitter_request(int *status){
655 rval = num_valid ? rval / num_valid : -1.0; 708 rval = num_valid ? rval / num_valid : -1.0;
656 709
657 close(conn); 710 close(conn);
658 if(peers!=NULL) free(peers); 711 if (peers != NULL) {
712 free(peers);
713 }
659 /* If we return -1.0, it means no synchronization source was found */ 714 /* If we return -1.0, it means no synchronization source was found */
660 return rval; 715 return rval;
661} 716}
662 717
663int process_arguments(int argc, char **argv){ 718int process_arguments(int argc, char **argv) {
664 int c; 719 int c;
665 int option=0; 720 int option = 0;
666 static struct option longopts[] = { 721 static struct option longopts[] = {
667 {"version", no_argument, 0, 'V'}, 722 {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'},
668 {"help", no_argument, 0, 'h'}, 723 {"verbose", no_argument, 0, 'v'}, {"use-ipv4", no_argument, 0, '4'},
669 {"verbose", no_argument, 0, 'v'}, 724 {"use-ipv6", no_argument, 0, '6'}, {"warning", required_argument, 0, 'w'},
670 {"use-ipv4", no_argument, 0, '4'}, 725 {"critical", required_argument, 0, 'c'}, {"jwarn", required_argument, 0, 'j'},
671 {"use-ipv6", no_argument, 0, '6'}, 726 {"jcrit", required_argument, 0, 'k'}, {"timeout", required_argument, 0, 't'},
672 {"warning", required_argument, 0, 'w'}, 727 {"hostname", required_argument, 0, 'H'}, {0, 0, 0, 0}};
673 {"critical", required_argument, 0, 'c'}, 728
674 {"jwarn", required_argument, 0, 'j'}, 729 if (argc < 2) {
675 {"jcrit", required_argument, 0, 'k'}, 730 usage("\n");
676 {"timeout", required_argument, 0, 't'}, 731 }
677 {"hostname", required_argument, 0, 'H'},
678 {0, 0, 0, 0}
679 };
680
681
682 if (argc < 2)
683 usage ("\n");
684 732
685 while (1) { 733 while (1) {
686 c = getopt_long (argc, argv, "Vhv46w:c:j:k:t:H:", longopts, &option); 734 c = getopt_long(argc, argv, "Vhv46w:c:j:k:t:H:", longopts, &option);
687 if (c == -1 || c == EOF || c == 1) 735 if (c == -1 || c == EOF || c == 1) {
688 break; 736 break;
737 }
689 738
690 switch (c) { 739 switch (c) {
691 case 'h': 740 case 'h':
@@ -716,12 +765,13 @@ int process_arguments(int argc, char **argv){
716 jcrit = optarg; 765 jcrit = optarg;
717 break; 766 break;
718 case 'H': 767 case 'H':
719 if(!is_host(optarg)) 768 if (!is_host(optarg)) {
720 usage2(_("Invalid hostname/address"), optarg); 769 usage2(_("Invalid hostname/address"), optarg);
770 }
721 server_address = strdup(optarg); 771 server_address = strdup(optarg);
722 break; 772 break;
723 case 't': 773 case 't':
724 socket_timeout=atoi(optarg); 774 socket_timeout = atoi(optarg);
725 break; 775 break;
726 case '4': 776 case '4':
727 address_family = AF_INET; 777 address_family = AF_INET;
@@ -730,64 +780,59 @@ int process_arguments(int argc, char **argv){
730#ifdef USE_IPV6 780#ifdef USE_IPV6
731 address_family = AF_INET6; 781 address_family = AF_INET6;
732#else 782#else
733 usage4 (_("IPv6 support not available")); 783 usage4(_("IPv6 support not available"));
734#endif 784#endif
735 break; 785 break;
736 case '?': 786 case '?':
737 /* print short usage statement if args not parsable */ 787 /* print short usage statement if args not parsable */
738 usage5 (); 788 usage5();
739 break; 789 break;
740 } 790 }
741 } 791 }
742 792
743 if(server_address == NULL){ 793 if (server_address == NULL) {
744 usage4(_("Hostname was not supplied")); 794 usage4(_("Hostname was not supplied"));
745 } 795 }
746 796
747 return 0; 797 return 0;
748} 798}
749 799
750char *perfd_offset (double offset) 800char *perfd_offset(double offset) {
751{ 801 return fperfdata("offset", offset, "s", true, offset_thresholds->warning->end, true,
752 return fperfdata ("offset", offset, "s", 802 offset_thresholds->critical->end, false, 0, false, 0);
753 true, offset_thresholds->warning->end,
754 true, offset_thresholds->critical->end,
755 false, 0, false, 0);
756} 803}
757 804
758char *perfd_jitter (double jitter) 805char *perfd_jitter(double jitter) {
759{ 806 return fperfdata("jitter", jitter, "s", do_jitter, jitter_thresholds->warning->end, do_jitter,
760 return fperfdata ("jitter", jitter, "s", 807 jitter_thresholds->critical->end, true, 0, false, 0);
761 do_jitter, jitter_thresholds->warning->end,
762 do_jitter, jitter_thresholds->critical->end,
763 true, 0, false, 0);
764} 808}
765 809
766int main(int argc, char *argv[]){ 810int main(int argc, char *argv[]) {
767 int result, offset_result, jitter_result; 811 int result, offset_result, jitter_result;
768 double offset=0, jitter=0; 812 double offset = 0, jitter = 0;
769 char *result_line, *perfdata_line; 813 char *result_line, *perfdata_line;
770 814
771 setlocale (LC_ALL, ""); 815 setlocale(LC_ALL, "");
772 bindtextdomain (PACKAGE, LOCALEDIR); 816 bindtextdomain(PACKAGE, LOCALEDIR);
773 textdomain (PACKAGE); 817 textdomain(PACKAGE);
774 818
775 result = offset_result = jitter_result = STATE_OK; 819 result = offset_result = jitter_result = STATE_OK;
776 820
777 /* Parse extra opts if any */ 821 /* Parse extra opts if any */
778 argv=np_extra_opts (&argc, argv, progname); 822 argv = np_extra_opts(&argc, argv, progname);
779 823
780 if (process_arguments (argc, argv) == ERROR) 824 if (process_arguments(argc, argv) == ERROR) {
781 usage4 (_("Could not parse arguments")); 825 usage4(_("Could not parse arguments"));
826 }
782 827
783 set_thresholds(&offset_thresholds, owarn, ocrit); 828 set_thresholds(&offset_thresholds, owarn, ocrit);
784 set_thresholds(&jitter_thresholds, jwarn, jcrit); 829 set_thresholds(&jitter_thresholds, jwarn, jcrit);
785 830
786 /* initialize alarm signal handling */ 831 /* initialize alarm signal handling */
787 signal (SIGALRM, socket_timeout_alarm_handler); 832 signal(SIGALRM, socket_timeout_alarm_handler);
788 833
789 /* set socket timeout */ 834 /* set socket timeout */
790 alarm (socket_timeout); 835 alarm(socket_timeout);
791 836
792 offset = offset_request(server_address, &offset_result); 837 offset = offset_request(server_address, &offset_result);
793 /* check_ntp used to always return CRITICAL if offset_result == STATE_UNKNOWN. 838 /* check_ntp used to always return CRITICAL if offset_result == STATE_UNKNOWN.
@@ -803,31 +848,32 @@ int main(int argc, char *argv[]){
803 * servers recognize. Trying to check the jitter on OpenNTPD 848 * servers recognize. Trying to check the jitter on OpenNTPD
804 * (for example) will result in an error 849 * (for example) will result in an error
805 */ 850 */
806 if(do_jitter){ 851 if (do_jitter) {
807 jitter=jitter_request(&jitter_result); 852 jitter = jitter_request(&jitter_result);
808 result = max_state_alt(result, get_status(jitter, jitter_thresholds)); 853 result = max_state_alt(result, get_status(jitter, jitter_thresholds));
809 /* -1 indicates that we couldn't calculate the jitter 854 /* -1 indicates that we couldn't calculate the jitter
810 * Only overrides STATE_OK from the offset */ 855 * Only overrides STATE_OK from the offset */
811 if(jitter == -1.0 && result == STATE_OK) 856 if (jitter == -1.0 && result == STATE_OK) {
812 result = STATE_UNKNOWN; 857 result = STATE_UNKNOWN;
858 }
813 } 859 }
814 result = max_state_alt(result, jitter_result); 860 result = max_state_alt(result, jitter_result);
815 861
816 switch (result) { 862 switch (result) {
817 case STATE_CRITICAL : 863 case STATE_CRITICAL:
818 xasprintf(&result_line, _("NTP CRITICAL:")); 864 xasprintf(&result_line, _("NTP CRITICAL:"));
819 break; 865 break;
820 case STATE_WARNING : 866 case STATE_WARNING:
821 xasprintf(&result_line, _("NTP WARNING:")); 867 xasprintf(&result_line, _("NTP WARNING:"));
822 break; 868 break;
823 case STATE_OK : 869 case STATE_OK:
824 xasprintf(&result_line, _("NTP OK:")); 870 xasprintf(&result_line, _("NTP OK:"));
825 break; 871 break;
826 default : 872 default:
827 xasprintf(&result_line, _("NTP UNKNOWN:")); 873 xasprintf(&result_line, _("NTP UNKNOWN:"));
828 break; 874 break;
829 } 875 }
830 if(offset_result == STATE_UNKNOWN){ 876 if (offset_result == STATE_UNKNOWN) {
831 xasprintf(&result_line, "%s %s", result_line, _("Offset unknown")); 877 xasprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
832 xasprintf(&perfdata_line, ""); 878 xasprintf(&perfdata_line, "");
833 } else { 879 } else {
@@ -836,41 +882,41 @@ int main(int argc, char *argv[]){
836 } 882 }
837 if (do_jitter) { 883 if (do_jitter) {
838 xasprintf(&result_line, "%s, jitter=%f", result_line, jitter); 884 xasprintf(&result_line, "%s, jitter=%f", result_line, jitter);
839 xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter)); 885 xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter));
840 } 886 }
841 printf("%s|%s\n", result_line, perfdata_line); 887 printf("%s|%s\n", result_line, perfdata_line);
842 888
843 if(server_address!=NULL) free(server_address); 889 if (server_address != NULL) {
890 free(server_address);
891 }
844 return result; 892 return result;
845} 893}
846 894
847 895void print_help(void) {
848
849void print_help(void){
850 print_revision(progname, NP_VERSION); 896 print_revision(progname, NP_VERSION);
851 897
852 printf ("Copyright (c) 2006 Sean Finney\n"); 898 printf("Copyright (c) 2006 Sean Finney\n");
853 printf (COPYRIGHT, copyright, email); 899 printf(COPYRIGHT, copyright, email);
854 900
855 printf ("%s\n", _("This plugin checks the selected ntp server")); 901 printf("%s\n", _("This plugin checks the selected ntp server"));
856 902
857 printf ("\n\n"); 903 printf("\n\n");
858 904
859 print_usage(); 905 print_usage();
860 printf (UT_HELP_VRSN); 906 printf(UT_HELP_VRSN);
861 printf (UT_EXTRA_OPTS); 907 printf(UT_EXTRA_OPTS);
862 printf (UT_HOST_PORT, 'p', "123"); 908 printf(UT_HOST_PORT, 'p', "123");
863 printf (UT_IPv46); 909 printf(UT_IPv46);
864 printf (" %s\n", "-w, --warning=THRESHOLD"); 910 printf(" %s\n", "-w, --warning=THRESHOLD");
865 printf (" %s\n", _("Offset to result in warning status (seconds)")); 911 printf(" %s\n", _("Offset to result in warning status (seconds)"));
866 printf (" %s\n", "-c, --critical=THRESHOLD"); 912 printf(" %s\n", "-c, --critical=THRESHOLD");
867 printf (" %s\n", _("Offset to result in critical status (seconds)")); 913 printf(" %s\n", _("Offset to result in critical status (seconds)"));
868 printf (" %s\n", "-j, --jwarn=THRESHOLD"); 914 printf(" %s\n", "-j, --jwarn=THRESHOLD");
869 printf (" %s\n", _("Warning threshold for jitter")); 915 printf(" %s\n", _("Warning threshold for jitter"));
870 printf (" %s\n", "-k, --jcrit=THRESHOLD"); 916 printf(" %s\n", "-k, --jcrit=THRESHOLD");
871 printf (" %s\n", _("Critical threshold for jitter")); 917 printf(" %s\n", _("Critical threshold for jitter"));
872 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); 918 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
873 printf (UT_VERBOSE); 919 printf(UT_VERBOSE);
874 920
875 printf("\n"); 921 printf("\n");
876 printf("%s\n", _("Notes:")); 922 printf("%s\n", _("Notes:"));
@@ -881,21 +927,21 @@ void print_help(void){
881 printf(" %s\n", _("Normal offset check:")); 927 printf(" %s\n", _("Normal offset check:"));
882 printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1")); 928 printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1"));
883 printf("\n"); 929 printf("\n");
884 printf(" %s\n", _("Check jitter too, avoiding critical notifications if jitter isn't available")); 930 printf(" %s\n",
931 _("Check jitter too, avoiding critical notifications if jitter isn't available"));
885 printf(" %s\n", _("(See Notes above for more details on thresholds formats):")); 932 printf(" %s\n", _("(See Notes above for more details on thresholds formats):"));
886 printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1 -j -1:100 -k -1:200")); 933 printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1 -j -1:100 -k -1:200"));
887 934
888 printf (UT_SUPPORT); 935 printf(UT_SUPPORT);
889 936
890 printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or")); 937 printf("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
891 printf ("%s\n\n", _("check_ntp_time instead.")); 938 printf("%s\n\n", _("check_ntp_time instead."));
892} 939}
893 940
894void 941void print_usage(void) {
895print_usage(void) 942 printf("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
896{ 943 printf("%s\n\n", _("check_ntp_time instead."));
897 printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or")); 944 printf("%s\n", _("Usage:"));
898 printf ("%s\n\n", _("check_ntp_time instead.")); 945 printf(" %s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-4|-6] [-v verbose]\n",
899 printf ("%s\n", _("Usage:")); 946 progname);
900 printf(" %s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-4|-6] [-v verbose]\n", progname);
901} 947}
diff --git a/plugins/check_ntp_peer.c b/plugins/check_ntp_peer.c
index 5c4ff386..24d1c9b5 100644
--- a/plugins/check_ntp_peer.c
+++ b/plugins/check_ntp_peer.c
@@ -83,9 +83,9 @@ typedef struct {
83/* bits 1,2 are the leap indicator */ 83/* bits 1,2 are the leap indicator */
84#define LI_MASK 0xc0 84#define LI_MASK 0xc0
85#define LI(x) ((x & LI_MASK) >> 6) 85#define LI(x) ((x & LI_MASK) >> 6)
86#define LI_SET(x, y) \ 86#define LI_SET(x, y) \
87 do { \ 87 do { \
88 x |= ((y << 6) & LI_MASK); \ 88 x |= ((y << 6) & LI_MASK); \
89 } while (0) 89 } while (0)
90/* and these are the values of the leap indicator */ 90/* and these are the values of the leap indicator */
91#define LI_NOWARNING 0x00 91#define LI_NOWARNING 0x00
@@ -95,17 +95,17 @@ typedef struct {
95/* bits 3,4,5 are the ntp version */ 95/* bits 3,4,5 are the ntp version */
96#define VN_MASK 0x38 96#define VN_MASK 0x38
97#define VN(x) ((x & VN_MASK) >> 3) 97#define VN(x) ((x & VN_MASK) >> 3)
98#define VN_SET(x, y) \ 98#define VN_SET(x, y) \
99 do { \ 99 do { \
100 x |= ((y << 3) & VN_MASK); \ 100 x |= ((y << 3) & VN_MASK); \
101 } while (0) 101 } while (0)
102#define VN_RESERVED 0x02 102#define VN_RESERVED 0x02
103/* bits 6,7,8 are the ntp mode */ 103/* bits 6,7,8 are the ntp mode */
104#define MODE_MASK 0x07 104#define MODE_MASK 0x07
105#define MODE(x) (x & MODE_MASK) 105#define MODE(x) (x & MODE_MASK)
106#define MODE_SET(x, y) \ 106#define MODE_SET(x, y) \
107 do { \ 107 do { \
108 x |= (y & MODE_MASK); \ 108 x |= (y & MODE_MASK); \
109 } while (0) 109 } while (0)
110/* here are some values */ 110/* here are some values */
111#define MODE_CLIENT 0x03 111#define MODE_CLIENT 0x03
@@ -117,9 +117,9 @@ typedef struct {
117#define REM_MORE 0x20 117#define REM_MORE 0x20
118/* In control message, bits 11 - 15 are opcode */ 118/* In control message, bits 11 - 15 are opcode */
119#define OP_MASK 0x1f 119#define OP_MASK 0x1f
120#define OP_SET(x, y) \ 120#define OP_SET(x, y) \
121 do { \ 121 do { \
122 x |= (y & OP_MASK); \ 122 x |= (y & OP_MASK); \
123 } while (0) 123 } while (0)
124#define OP_READSTAT 0x01 124#define OP_READSTAT 0x01
125#define OP_READVAR 0x02 125#define OP_READVAR 0x02
@@ -132,18 +132,19 @@ typedef struct {
132/* NTP control message header is 12 bytes, plus any data in the data 132/* NTP control message header is 12 bytes, plus any data in the data
133 * field, plus null padding to the nearest 32-bit boundary per rfc. 133 * field, plus null padding to the nearest 32-bit boundary per rfc.
134 */ 134 */
135#define SIZEOF_NTPCM(m) (12 + ntohs(m.count) + ((ntohs(m.count) % 4) ? 4 - (ntohs(m.count) % 4) : 0)) 135#define SIZEOF_NTPCM(m) \
136 (12 + ntohs(m.count) + ((ntohs(m.count) % 4) ? 4 - (ntohs(m.count) % 4) : 0))
136 137
137/* finally, a little helper or two for debugging: */ 138/* finally, a little helper or two for debugging: */
138#define DBG(x) \ 139#define DBG(x) \
139 do { \ 140 do { \
140 if (verbose > 1) { \ 141 if (verbose > 1) { \
141 x; \ 142 x; \
142 } \ 143 } \
143 } while (0); 144 } while (0);
144#define PRINTSOCKADDR(x) \ 145#define PRINTSOCKADDR(x) \
145 do { \ 146 do { \
146 printf("%u.%u.%u.%u", (x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff); \ 147 printf("%u.%u.%u.%u", (x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff); \
147 } while (0); 148 } while (0);
148 149
149void print_ntp_control_message(const ntp_control_message *message) { 150void print_ntp_control_message(const ntp_control_message *message) {
@@ -360,7 +361,8 @@ ntp_request_result ntp_request(const check_ntp_peer_config config) {
360 if (req.op & REM_ERROR) { 361 if (req.op & REM_ERROR) {
361 if (strstr(getvar, "jitter")) { 362 if (strstr(getvar, "jitter")) {
362 if (verbose) { 363 if (verbose) {
363 printf("The command failed. This is usually caused by servers refusing the 'jitter'\nvariable. Restarting with " 364 printf("The command failed. This is usually caused by servers refusing the "
365 "'jitter'\nvariable. Restarting with "
364 "'dispersion'...\n"); 366 "'dispersion'...\n");
365 } 367 }
366 getvar = "stratum,offset,dispersion"; 368 getvar = "stratum,offset,dispersion";
@@ -404,7 +406,8 @@ ntp_request_result ntp_request(const check_ntp_peer_config config) {
404 if (verbose) { 406 if (verbose) {
405 printf("%.10g\n", tmp_offset); 407 printf("%.10g\n", tmp_offset);
406 } 408 }
407 if (result.offset_result == STATE_UNKNOWN || fabs(tmp_offset) < fabs(result.offset)) { 409 if (result.offset_result == STATE_UNKNOWN ||
410 fabs(tmp_offset) < fabs(result.offset)) {
408 result.offset = tmp_offset; 411 result.offset = tmp_offset;
409 result.offset_result = STATE_OK; 412 result.offset_result = STATE_OK;
410 } else { 413 } else {
@@ -416,10 +419,12 @@ ntp_request_result ntp_request(const check_ntp_peer_config config) {
416 if (config.do_jitter) { 419 if (config.do_jitter) {
417 /* get the jitter */ 420 /* get the jitter */
418 if (verbose) { 421 if (verbose) {
419 printf("parsing %s from peer %.2x: ", strstr(getvar, "dispersion") != NULL ? "dispersion" : "jitter", 422 printf("parsing %s from peer %.2x: ",
423 strstr(getvar, "dispersion") != NULL ? "dispersion" : "jitter",
420 ntohs(peers[i].assoc)); 424 ntohs(peers[i].assoc));
421 } 425 }
422 value = np_extract_ntpvar(data, strstr(getvar, "dispersion") != NULL ? "dispersion" : "jitter"); 426 value = np_extract_ntpvar(data, strstr(getvar, "dispersion") != NULL ? "dispersion"
427 : "jitter");
423 nptr = NULL; 428 nptr = NULL;
424 /* Convert the value if we have one */ 429 /* Convert the value if we have one */
425 if (value != NULL) { 430 if (value != NULL) {
@@ -471,12 +476,15 @@ ntp_request_result ntp_request(const check_ntp_peer_config config) {
471 476
472check_ntp_peer_config_wrapper process_arguments(int argc, char **argv) { 477check_ntp_peer_config_wrapper process_arguments(int argc, char **argv) {
473 static struct option longopts[] = { 478 static struct option longopts[] = {
474 {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {"verbose", no_argument, 0, 'v'}, 479 {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'},
475 {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {"quiet", no_argument, 0, 'q'}, 480 {"verbose", no_argument, 0, 'v'}, {"use-ipv4", no_argument, 0, '4'},
476 {"warning", required_argument, 0, 'w'}, {"critical", required_argument, 0, 'c'}, {"swarn", required_argument, 0, 'W'}, 481 {"use-ipv6", no_argument, 0, '6'}, {"quiet", no_argument, 0, 'q'},
477 {"scrit", required_argument, 0, 'C'}, {"jwarn", required_argument, 0, 'j'}, {"jcrit", required_argument, 0, 'k'}, 482 {"warning", required_argument, 0, 'w'}, {"critical", required_argument, 0, 'c'},
478 {"twarn", required_argument, 0, 'm'}, {"tcrit", required_argument, 0, 'n'}, {"timeout", required_argument, 0, 't'}, 483 {"swarn", required_argument, 0, 'W'}, {"scrit", required_argument, 0, 'C'},
479 {"hostname", required_argument, 0, 'H'}, {"port", required_argument, 0, 'p'}, {0, 0, 0, 0}}; 484 {"jwarn", required_argument, 0, 'j'}, {"jcrit", required_argument, 0, 'k'},
485 {"twarn", required_argument, 0, 'm'}, {"tcrit", required_argument, 0, 'n'},
486 {"timeout", required_argument, 0, 't'}, {"hostname", required_argument, 0, 'H'},
487 {"port", required_argument, 0, 'p'}, {0, 0, 0, 0}};
480 488
481 if (argc < 2) { 489 if (argc < 2) {
482 usage("\n"); 490 usage("\n");
@@ -489,7 +497,8 @@ check_ntp_peer_config_wrapper process_arguments(int argc, char **argv) {
489 497
490 while (true) { 498 while (true) {
491 int option = 0; 499 int option = 0;
492 int option_char = getopt_long(argc, argv, "Vhv46qw:c:W:C:j:k:m:n:t:H:p:", longopts, &option); 500 int option_char =
501 getopt_long(argc, argv, "Vhv46qw:c:W:C:j:k:m:n:t:H:p:", longopts, &option);
493 if (option_char == -1 || option_char == EOF || option_char == 1) { 502 if (option_char == -1 || option_char == EOF || option_char == 1) {
494 break; 503 break;
495 } 504 }
@@ -581,22 +590,24 @@ check_ntp_peer_config_wrapper process_arguments(int argc, char **argv) {
581} 590}
582 591
583char *perfd_offset(double offset, thresholds *offset_thresholds) { 592char *perfd_offset(double offset, thresholds *offset_thresholds) {
584 return fperfdata("offset", offset, "s", true, offset_thresholds->warning->end, true, offset_thresholds->critical->end, false, 0, false, 593 return fperfdata("offset", offset, "s", true, offset_thresholds->warning->end, true,
585 0); 594 offset_thresholds->critical->end, false, 0, false, 0);
586} 595}
587 596
588char *perfd_jitter(double jitter, bool do_jitter, thresholds *jitter_thresholds) { 597char *perfd_jitter(double jitter, bool do_jitter, thresholds *jitter_thresholds) {
589 return fperfdata("jitter", jitter, "", do_jitter, jitter_thresholds->warning->end, do_jitter, jitter_thresholds->critical->end, true, 0, 598 return fperfdata("jitter", jitter, "", do_jitter, jitter_thresholds->warning->end, do_jitter,
590 false, 0); 599 jitter_thresholds->critical->end, true, 0, false, 0);
591} 600}
592 601
593char *perfd_stratum(int stratum, bool do_stratum, thresholds *stratum_thresholds) { 602char *perfd_stratum(int stratum, bool do_stratum, thresholds *stratum_thresholds) {
594 return perfdata("stratum", stratum, "", do_stratum, (int)stratum_thresholds->warning->end, do_stratum, 603 return perfdata("stratum", stratum, "", do_stratum, (int)stratum_thresholds->warning->end,
595 (int)stratum_thresholds->critical->end, true, 0, true, 16); 604 do_stratum, (int)stratum_thresholds->critical->end, true, 0, true, 16);
596} 605}
597 606
598char *perfd_truechimers(int num_truechimers, const bool do_truechimers, thresholds *truechimer_thresholds) { 607char *perfd_truechimers(int num_truechimers, const bool do_truechimers,
599 return perfdata("truechimers", num_truechimers, "", do_truechimers, (int)truechimer_thresholds->warning->end, do_truechimers, 608 thresholds *truechimer_thresholds) {
609 return perfdata("truechimers", num_truechimers, "", do_truechimers,
610 (int)truechimer_thresholds->warning->end, do_truechimers,
600 (int)truechimer_thresholds->critical->end, true, 0, false, 0); 611 (int)truechimer_thresholds->critical->end, true, 0, false, 0);
601} 612}
602 613
@@ -686,9 +697,11 @@ int main(int argc, char *argv[]) {
686 xasprintf(&result_line, "%s %s", result_line, _("Offset unknown")); 697 xasprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
687 xasprintf(&perfdata_line, ""); 698 xasprintf(&perfdata_line, "");
688 } else if (oresult == STATE_WARNING) { 699 } else if (oresult == STATE_WARNING) {
689 xasprintf(&result_line, "%s %s %.10g secs (WARNING)", result_line, _("Offset"), ntp_res.offset); 700 xasprintf(&result_line, "%s %s %.10g secs (WARNING)", result_line, _("Offset"),
701 ntp_res.offset);
690 } else if (oresult == STATE_CRITICAL) { 702 } else if (oresult == STATE_CRITICAL) {
691 xasprintf(&result_line, "%s %s %.10g secs (CRITICAL)", result_line, _("Offset"), ntp_res.offset); 703 xasprintf(&result_line, "%s %s %.10g secs (CRITICAL)", result_line, _("Offset"),
704 ntp_res.offset);
692 } else { 705 } else {
693 xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), ntp_res.offset); 706 xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), ntp_res.offset);
694 } 707 }
@@ -702,7 +715,8 @@ int main(int argc, char *argv[]) {
702 } else { 715 } else {
703 xasprintf(&result_line, "%s, jitter=%f", result_line, ntp_res.jitter); 716 xasprintf(&result_line, "%s, jitter=%f", result_line, ntp_res.jitter);
704 } 717 }
705 xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(ntp_res.jitter, config.do_jitter, config.jitter_thresholds)); 718 xasprintf(&perfdata_line, "%s %s", perfdata_line,
719 perfd_jitter(ntp_res.jitter, config.do_jitter, config.jitter_thresholds));
706 } 720 }
707 721
708 if (config.do_stratum) { 722 if (config.do_stratum) {
@@ -713,19 +727,23 @@ int main(int argc, char *argv[]) {
713 } else { 727 } else {
714 xasprintf(&result_line, "%s, stratum=%li", result_line, ntp_res.stratum); 728 xasprintf(&result_line, "%s, stratum=%li", result_line, ntp_res.stratum);
715 } 729 }
716 xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_stratum(ntp_res.stratum, config.do_stratum, config.stratum_thresholds)); 730 xasprintf(&perfdata_line, "%s %s", perfdata_line,
731 perfd_stratum(ntp_res.stratum, config.do_stratum, config.stratum_thresholds));
717 } 732 }
718 733
719 if (config.do_truechimers) { 734 if (config.do_truechimers) {
720 if (tresult == STATE_WARNING) { 735 if (tresult == STATE_WARNING) {
721 xasprintf(&result_line, "%s, truechimers=%i (WARNING)", result_line, ntp_res.num_truechimers); 736 xasprintf(&result_line, "%s, truechimers=%i (WARNING)", result_line,
737 ntp_res.num_truechimers);
722 } else if (tresult == STATE_CRITICAL) { 738 } else if (tresult == STATE_CRITICAL) {
723 xasprintf(&result_line, "%s, truechimers=%i (CRITICAL)", result_line, ntp_res.num_truechimers); 739 xasprintf(&result_line, "%s, truechimers=%i (CRITICAL)", result_line,
740 ntp_res.num_truechimers);
724 } else { 741 } else {
725 xasprintf(&result_line, "%s, truechimers=%i", result_line, ntp_res.num_truechimers); 742 xasprintf(&result_line, "%s, truechimers=%i", result_line, ntp_res.num_truechimers);
726 } 743 }
727 xasprintf(&perfdata_line, "%s %s", perfdata_line, 744 xasprintf(&perfdata_line, "%s %s", perfdata_line,
728 perfd_truechimers(ntp_res.num_truechimers, config.do_truechimers, config.truechimer_thresholds)); 745 perfd_truechimers(ntp_res.num_truechimers, config.do_truechimers,
746 config.truechimer_thresholds));
729 } 747 }
730 748
731 printf("%s|%s\n", result_line, perfdata_line); 749 printf("%s|%s\n", result_line, perfdata_line);
@@ -753,7 +771,8 @@ void print_help(void) {
753 printf(UT_IPv46); 771 printf(UT_IPv46);
754 printf(UT_HOST_PORT, 'p', "123"); 772 printf(UT_HOST_PORT, 'p', "123");
755 printf(" %s\n", "-q, --quiet"); 773 printf(" %s\n", "-q, --quiet");
756 printf(" %s\n", _("Returns UNKNOWN instead of CRITICAL or WARNING if server isn't synchronized")); 774 printf(" %s\n",
775 _("Returns UNKNOWN instead of CRITICAL or WARNING if server isn't synchronized"));
757 printf(" %s\n", "-w, --warning=THRESHOLD"); 776 printf(" %s\n", "-w, --warning=THRESHOLD");
758 printf(" %s\n", _("Offset to result in warning status (seconds)")); 777 printf(" %s\n", _("Offset to result in warning status (seconds)"));
759 printf(" %s\n", "-c, --critical=THRESHOLD"); 778 printf(" %s\n", "-c, --critical=THRESHOLD");
@@ -790,7 +809,8 @@ void print_help(void) {
790 printf(" %s\n", _("Simple NTP server check:")); 809 printf(" %s\n", _("Simple NTP server check:"));
791 printf(" %s\n", ("./check_ntp_peer -H ntpserv -w 0.5 -c 1")); 810 printf(" %s\n", ("./check_ntp_peer -H ntpserv -w 0.5 -c 1"));
792 printf("\n"); 811 printf("\n");
793 printf(" %s\n", _("Check jitter too, avoiding critical notifications if jitter isn't available")); 812 printf(" %s\n",
813 _("Check jitter too, avoiding critical notifications if jitter isn't available"));
794 printf(" %s\n", _("(See Notes above for more details on thresholds formats):")); 814 printf(" %s\n", _("(See Notes above for more details on thresholds formats):"));
795 printf(" %s\n", ("./check_ntp_peer -H ntpserv -w 0.5 -c 1 -j -1:100 -k -1:200")); 815 printf(" %s\n", ("./check_ntp_peer -H ntpserv -w 0.5 -c 1 -j -1:100 -k -1:200"));
796 printf("\n"); 816 printf("\n");
diff --git a/plugins/check_ntp_time.c b/plugins/check_ntp_time.c
index 31162883..ad69b804 100644
--- a/plugins/check_ntp_time.c
+++ b/plugins/check_ntp_time.c
@@ -93,9 +93,9 @@ typedef struct {
93/* bits 1,2 are the leap indicator */ 93/* bits 1,2 are the leap indicator */
94#define LI_MASK 0xc0 94#define LI_MASK 0xc0
95#define LI(x) ((x & LI_MASK) >> 6) 95#define LI(x) ((x & LI_MASK) >> 6)
96#define LI_SET(x, y) \ 96#define LI_SET(x, y) \
97 do { \ 97 do { \
98 x |= ((y << 6) & LI_MASK); \ 98 x |= ((y << 6) & LI_MASK); \
99 } while (0) 99 } while (0)
100/* and these are the values of the leap indicator */ 100/* and these are the values of the leap indicator */
101#define LI_NOWARNING 0x00 101#define LI_NOWARNING 0x00
@@ -105,17 +105,17 @@ typedef struct {
105/* bits 3,4,5 are the ntp version */ 105/* bits 3,4,5 are the ntp version */
106#define VN_MASK 0x38 106#define VN_MASK 0x38
107#define VN(x) ((x & VN_MASK) >> 3) 107#define VN(x) ((x & VN_MASK) >> 3)
108#define VN_SET(x, y) \ 108#define VN_SET(x, y) \
109 do { \ 109 do { \
110 x |= ((y << 3) & VN_MASK); \ 110 x |= ((y << 3) & VN_MASK); \
111 } while (0) 111 } while (0)
112#define VN_RESERVED 0x02 112#define VN_RESERVED 0x02
113/* bits 6,7,8 are the ntp mode */ 113/* bits 6,7,8 are the ntp mode */
114#define MODE_MASK 0x07 114#define MODE_MASK 0x07
115#define MODE(x) (x & MODE_MASK) 115#define MODE(x) (x & MODE_MASK)
116#define MODE_SET(x, y) \ 116#define MODE_SET(x, y) \
117 do { \ 117 do { \
118 x |= (y & MODE_MASK); \ 118 x |= (y & MODE_MASK); \
119 } while (0) 119 } while (0)
120/* here are some values */ 120/* here are some values */
121#define MODE_CLIENT 0x03 121#define MODE_CLIENT 0x03
@@ -127,9 +127,9 @@ typedef struct {
127#define REM_MORE 0x20 127#define REM_MORE 0x20
128/* In control message, bits 11 - 15 are opcode */ 128/* In control message, bits 11 - 15 are opcode */
129#define OP_MASK 0x1f 129#define OP_MASK 0x1f
130#define OP_SET(x, y) \ 130#define OP_SET(x, y) \
131 do { \ 131 do { \
132 x |= (y & OP_MASK); \ 132 x |= (y & OP_MASK); \
133 } while (0) 133 } while (0)
134#define OP_READSTAT 0x01 134#define OP_READSTAT 0x01
135#define OP_READVAR 0x02 135#define OP_READVAR 0x02
@@ -163,32 +163,34 @@ typedef struct {
163#define NTP32asDOUBLE(x) (ntohs(L16(x)) + ((double)ntohs(R16(x)) / 65536.0)) 163#define NTP32asDOUBLE(x) (ntohs(L16(x)) + ((double)ntohs(R16(x)) / 65536.0))
164 164
165/* likewise for a 64-bit ntp fp number */ 165/* likewise for a 64-bit ntp fp number */
166#define NTP64asDOUBLE(n) \ 166#define NTP64asDOUBLE(n) \
167 (double)(((uint64_t)n) ? (ntohl(L32(n)) - EPOCHDIFF) + (.00000001 * (0.5 + (double)(ntohl(R32(n)) / 42.94967296))) : 0) 167 (double)(((uint64_t)n) ? (ntohl(L32(n)) - EPOCHDIFF) + \
168 (.00000001 * (0.5 + (double)(ntohl(R32(n)) / 42.94967296))) \
169 : 0)
168 170
169/* convert a struct timeval to a double */ 171/* convert a struct timeval to a double */
170#define TVasDOUBLE(x) (double)(x.tv_sec + (0.000001 * x.tv_usec)) 172#define TVasDOUBLE(x) (double)(x.tv_sec + (0.000001 * x.tv_usec))
171 173
172/* convert an ntp 64-bit fp number to a struct timeval */ 174/* convert an ntp 64-bit fp number to a struct timeval */
173#define NTP64toTV(n, t) \ 175#define NTP64toTV(n, t) \
174 do { \ 176 do { \
175 if (!n) \ 177 if (!n) \
176 t.tv_sec = t.tv_usec = 0; \ 178 t.tv_sec = t.tv_usec = 0; \
177 else { \ 179 else { \
178 t.tv_sec = ntohl(L32(n)) - EPOCHDIFF; \ 180 t.tv_sec = ntohl(L32(n)) - EPOCHDIFF; \
179 t.tv_usec = (int)(0.5 + (double)(ntohl(R32(n)) / 4294.967296)); \ 181 t.tv_usec = (int)(0.5 + (double)(ntohl(R32(n)) / 4294.967296)); \
180 } \ 182 } \
181 } while (0) 183 } while (0)
182 184
183/* convert a struct timeval to an ntp 64-bit fp number */ 185/* convert a struct timeval to an ntp 64-bit fp number */
184#define TVtoNTP64(t, n) \ 186#define TVtoNTP64(t, n) \
185 do { \ 187 do { \
186 if (!t.tv_usec && !t.tv_sec) \ 188 if (!t.tv_usec && !t.tv_sec) \
187 n = 0x0UL; \ 189 n = 0x0UL; \
188 else { \ 190 else { \
189 L32(n) = htonl(t.tv_sec + EPOCHDIFF); \ 191 L32(n) = htonl(t.tv_sec + EPOCHDIFF); \
190 R32(n) = htonl((uint64_t)((4294.967296 * t.tv_usec) + .5)); \ 192 R32(n) = htonl((uint64_t)((4294.967296 * t.tv_usec) + .5)); \
191 } \ 193 } \
192 } while (0) 194 } while (0)
193 195
194/* NTP control message header is 12 bytes, plus any data in the data 196/* NTP control message header is 12 bytes, plus any data in the data
@@ -197,15 +199,15 @@ typedef struct {
197#define SIZEOF_NTPCM(m) (12 + ntohs(m.count) + ((m.count) ? 4 - (ntohs(m.count) % 4) : 0)) 199#define SIZEOF_NTPCM(m) (12 + ntohs(m.count) + ((m.count) ? 4 - (ntohs(m.count) % 4) : 0))
198 200
199/* finally, a little helper or two for debugging: */ 201/* finally, a little helper or two for debugging: */
200#define DBG(x) \ 202#define DBG(x) \
201 do { \ 203 do { \
202 if (verbose > 1) { \ 204 if (verbose > 1) { \
203 x; \ 205 x; \
204 } \ 206 } \
205 } while (0); 207 } while (0);
206#define PRINTSOCKADDR(x) \ 208#define PRINTSOCKADDR(x) \
207 do { \ 209 do { \
208 printf("%u.%u.%u.%u", (x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff); \ 210 printf("%u.%u.%u.%u", (x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff); \
209 } while (0); 211 } while (0);
210 212
211/* calculate the offset of the local clock */ 213/* calculate the offset of the local clock */
@@ -358,7 +360,8 @@ double offset_request(const char *host, const char *port, mp_state_enum *status,
358 die(STATE_UNKNOWN, "can not allocate socket array"); 360 die(STATE_UNKNOWN, "can not allocate socket array");
359 } 361 }
360 362
361 ntp_server_results *servers = (ntp_server_results *)malloc(sizeof(ntp_server_results) * num_hosts); 363 ntp_server_results *servers =
364 (ntp_server_results *)malloc(sizeof(ntp_server_results) * num_hosts);
362 if (servers == NULL) { 365 if (servers == NULL) {
363 die(STATE_UNKNOWN, "can not allocate server array"); 366 die(STATE_UNKNOWN, "can not allocate server array");
364 } 367 }
@@ -585,8 +588,8 @@ check_ntp_time_config_wrapper process_arguments(int argc, char **argv) {
585} 588}
586 589
587char *perfd_offset(double offset, thresholds *offset_thresholds) { 590char *perfd_offset(double offset, thresholds *offset_thresholds) {
588 return fperfdata("offset", offset, "s", true, offset_thresholds->warning->end, true, offset_thresholds->critical->end, false, 0, false, 591 return fperfdata("offset", offset, "s", true, offset_thresholds->warning->end, true,
589 0); 592 offset_thresholds->critical->end, false, 0, false, 0);
590} 593}
591 594
592int main(int argc, char *argv[]) { 595int main(int argc, char *argv[]) {
@@ -613,7 +616,8 @@ int main(int argc, char *argv[]) {
613 616
614 mp_state_enum offset_result = STATE_OK; 617 mp_state_enum offset_result = STATE_OK;
615 mp_state_enum result = STATE_OK; 618 mp_state_enum result = STATE_OK;
616 double offset = offset_request(config.server_address, config.port, &offset_result, config.time_offset); 619 double offset =
620 offset_request(config.server_address, config.port, &offset_result, config.time_offset);
617 if (offset_result == STATE_UNKNOWN) { 621 if (offset_result == STATE_UNKNOWN) {
618 result = ((!config.quiet) ? STATE_UNKNOWN : STATE_CRITICAL); 622 result = ((!config.quiet) ? STATE_UNKNOWN : STATE_CRITICAL);
619 } else { 623 } else {
@@ -701,5 +705,6 @@ void print_help(void) {
701 705
702void print_usage(void) { 706void print_usage(void) {
703 printf("%s\n", _("Usage:")); 707 printf("%s\n", _("Usage:"));
704 printf(" %s -H <host> [-4|-6] [-w <warn>] [-c <crit>] [-v verbose] [-o <time offset>]\n", progname); 708 printf(" %s -H <host> [-4|-6] [-w <warn>] [-c <crit>] [-v verbose] [-o <time offset>]\n",
709 progname);
705} 710}
diff --git a/plugins/check_pgsql.c b/plugins/check_pgsql.c
index 84305adb..793a686f 100644
--- a/plugins/check_pgsql.c
+++ b/plugins/check_pgsql.c
@@ -46,14 +46,15 @@ const char *email = "devel@monitoring-plugins.org";
46#define DEFAULT_HOST "127.0.0.1" 46#define DEFAULT_HOST "127.0.0.1"
47 47
48/* return the PSQL server version as a 3-tuple */ 48/* return the PSQL server version as a 3-tuple */
49#define PSQL_SERVER_VERSION3(server_version) \ 49#define PSQL_SERVER_VERSION3(server_version) \
50 (server_version) / 10000, (server_version) / 100 - (int)((server_version) / 10000) * 100, \ 50 (server_version) / 10000, (server_version) / 100 - (int)((server_version) / 10000) * 100, \
51 (server_version) - (int)((server_version) / 100) * 100 51 (server_version) - (int)((server_version) / 100) * 100
52/* return true if the given host is a UNIX domain socket */ 52/* return true if the given host is a UNIX domain socket */
53#define PSQL_IS_UNIX_DOMAIN_SOCKET(host) ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host))) 53#define PSQL_IS_UNIX_DOMAIN_SOCKET(host) ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
54/* return a 3-tuple identifying a host/port independent of the socket type */ 54/* return a 3-tuple identifying a host/port independent of the socket type */
55#define PSQL_SOCKET3(host, port) \ 55#define PSQL_SOCKET3(host, port) \
56 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, PSQL_IS_UNIX_DOMAIN_SOCKET(host) ? "/.s.PGSQL." : ":", port 56 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
57 PSQL_IS_UNIX_DOMAIN_SOCKET(host) ? "/.s.PGSQL." : ":", port
57 58
58typedef struct { 59typedef struct {
59 int errorcode; 60 int errorcode;
@@ -63,8 +64,9 @@ static check_pgsql_config_wrapper process_arguments(int /*argc*/, char ** /*argv
63 64
64static void print_help(void); 65static void print_help(void);
65static bool is_pg_logname(char * /*username*/); 66static bool is_pg_logname(char * /*username*/);
66static mp_state_enum do_query(PGconn * /*conn*/, char * /*query*/, const char /*pgqueryname*/[], thresholds * /*qthresholds*/, 67static mp_state_enum do_query(PGconn * /*conn*/, char * /*query*/, const char /*pgqueryname*/[],
67 char * /*query_warning*/, char * /*query_critical*/); 68 thresholds * /*qthresholds*/, char * /*query_warning*/,
69 char * /*query_critical*/);
68void print_usage(void); 70void print_usage(void);
69 71
70static int verbose = 0; 72static int verbose = 0;
@@ -167,7 +169,8 @@ int main(int argc, char **argv) {
167 } 169 }
168 170
169 if (verbose) { /* do not include password (see right below) in output */ 171 if (verbose) { /* do not include password (see right below) in output */
170 printf("Connecting to PostgreSQL using conninfo: %s%s\n", conninfo, config.pgpasswd ? " password = <hidden>" : ""); 172 printf("Connecting to PostgreSQL using conninfo: %s%s\n", conninfo,
173 config.pgpasswd ? " password = <hidden>" : "");
171 } 174 }
172 175
173 if (config.pgpasswd) { 176 if (config.pgpasswd) {
@@ -185,8 +188,8 @@ int main(int argc, char **argv) {
185 --end_timeval.tv_sec; 188 --end_timeval.tv_sec;
186 end_timeval.tv_usec += 1000000; 189 end_timeval.tv_usec += 1000000;
187 } 190 }
188 double elapsed_time = 191 double elapsed_time = (double)(end_timeval.tv_sec - start_timeval.tv_sec) +
189 (double)(end_timeval.tv_sec - start_timeval.tv_sec) + ((double)(end_timeval.tv_usec - start_timeval.tv_usec) / 1000000.0); 192 ((double)(end_timeval.tv_usec - start_timeval.tv_usec) / 1000000.0);
190 193
191 if (verbose) { 194 if (verbose) {
192 printf("Time elapsed: %f\n", elapsed_time); 195 printf("Time elapsed: %f\n", elapsed_time);
@@ -218,16 +221,18 @@ int main(int argc, char **argv) {
218 printf("Successfully connected to database %s (user %s) " 221 printf("Successfully connected to database %s (user %s) "
219 "at server %s%s%s (server version: %d.%d.%d, " 222 "at server %s%s%s (server version: %d.%d.%d, "
220 "protocol version: %d, pid: %d)\n", 223 "protocol version: %d, pid: %d)\n",
221 PQdb(conn), PQuser(conn), PSQL_SOCKET3(server_host, PQport(conn)), PSQL_SERVER_VERSION3(server_version), 224 PQdb(conn), PQuser(conn), PSQL_SOCKET3(server_host, PQport(conn)),
222 PQprotocolVersion(conn), PQbackendPID(conn)); 225 PSQL_SERVER_VERSION3(server_version), PQprotocolVersion(conn), PQbackendPID(conn));
223 } 226 }
224 227
225 printf(_(" %s - database %s (%f sec.)|%s\n"), state_text(status), config.dbName, elapsed_time, 228 printf(_(" %s - database %s (%f sec.)|%s\n"), state_text(status), config.dbName, elapsed_time,
226 fperfdata("time", elapsed_time, "s", (config.twarn > 0.0), config.twarn, (config.tcrit > 0.0), config.tcrit, true, 0, false, 0)); 229 fperfdata("time", elapsed_time, "s", (config.twarn > 0.0), config.twarn,
230 (config.tcrit > 0.0), config.tcrit, true, 0, false, 0));
227 231
228 mp_state_enum query_status = STATE_UNKNOWN; 232 mp_state_enum query_status = STATE_UNKNOWN;
229 if (config.pgquery) { 233 if (config.pgquery) {
230 query_status = do_query(conn, config.pgquery, config.pgqueryname, config.qthresholds, config.query_warning, config.query_critical); 234 query_status = do_query(conn, config.pgquery, config.pgqueryname, config.qthresholds,
235 config.query_warning, config.query_critical);
231 } 236 }
232 237
233 if (verbose) { 238 if (verbose) {
@@ -265,7 +270,8 @@ check_pgsql_config_wrapper process_arguments(int argc, char **argv) {
265 270
266 while (true) { 271 while (true) {
267 int option = 0; 272 int option = 0;
268 int option_char = getopt_long(argc, argv, "hVt:c:w:H:P:d:l:p:a:o:q:C:W:v", longopts, &option); 273 int option_char =
274 getopt_long(argc, argv, "hVt:c:w:H:P:d:l:p:a:o:q:C:W:v", longopts, &option);
269 275
270 if (option_char == EOF) { 276 if (option_char == EOF) {
271 break; 277 break;
@@ -357,7 +363,8 @@ check_pgsql_config_wrapper process_arguments(int argc, char **argv) {
357 } 363 }
358 } 364 }
359 365
360 set_thresholds(&result.config.qthresholds, result.config.query_warning, result.config.query_critical); 366 set_thresholds(&result.config.qthresholds, result.config.query_warning,
367 result.config.query_critical);
361 368
362 return result; 369 return result;
363} 370}
@@ -457,29 +464,39 @@ void print_help(void) {
457 464
458 printf(" %s\n", _("If a query is specified using the -q option, it will be executed after")); 465 printf(" %s\n", _("If a query is specified using the -q option, it will be executed after"));
459 printf(" %s\n", _("connecting to the server. The result from the query has to be numeric.")); 466 printf(" %s\n", _("connecting to the server. The result from the query has to be numeric."));
460 printf(" %s\n", _("Multiple SQL commands, separated by semicolon, are allowed but the result ")); 467 printf(" %s\n",
468 _("Multiple SQL commands, separated by semicolon, are allowed but the result "));
461 printf(" %s\n", _("of the last command is taken into account only. The value of the first")); 469 printf(" %s\n", _("of the last command is taken into account only. The value of the first"));
462 printf(" %s\n", _("column in the first row is used as the check result. If a second column is")); 470 printf(" %s\n",
471 _("column in the first row is used as the check result. If a second column is"));
463 printf(" %s\n", _("present in the result set, this is added to the plugin output with a")); 472 printf(" %s\n", _("present in the result set, this is added to the plugin output with a"));
464 printf(" %s\n", _("prefix of \"Extra Info:\". This information can be displayed in the system")); 473 printf(" %s\n",
474 _("prefix of \"Extra Info:\". This information can be displayed in the system"));
465 printf(" %s\n\n", _("executing the plugin.")); 475 printf(" %s\n\n", _("executing the plugin."));
466 476
467 printf(" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual")); 477 printf(" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual"));
468 printf(" %s\n\n", _("for details about how to access internal statistics of the database server.")); 478 printf(" %s\n\n",
479 _("for details about how to access internal statistics of the database server."));
469 480
470 printf(" %s\n", _("For a list of available connection parameters which may be used with the -o")); 481 printf(" %s\n",
471 printf(" %s\n", _("command line option, see the documentation for PQconnectdb() in the chapter")); 482 _("For a list of available connection parameters which may be used with the -o"));
483 printf(" %s\n",
484 _("command line option, see the documentation for PQconnectdb() in the chapter"));
472 printf(" %s\n", _("\"libpq - C Library\" of the PostgreSQL manual. For example, this may be")); 485 printf(" %s\n", _("\"libpq - C Library\" of the PostgreSQL manual. For example, this may be"));
473 printf(" %s\n", _("used to specify a service name in pg_service.conf to be used for additional")); 486 printf(" %s\n",
487 _("used to specify a service name in pg_service.conf to be used for additional"));
474 printf(" %s\n", _("connection parameters: -o 'service=<name>' or to specify the SSL mode:")); 488 printf(" %s\n", _("connection parameters: -o 'service=<name>' or to specify the SSL mode:"));
475 printf(" %s\n\n", _("-o 'sslmode=require'.")); 489 printf(" %s\n\n", _("-o 'sslmode=require'."));
476 490
477 printf(" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To")); 491 printf(" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
478 printf(" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP")); 492 printf(" %s\n",
493 _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
479 printf(" %s\n\n", _("connections (start the postmaster with the -i option).")); 494 printf(" %s\n\n", _("connections (start the postmaster with the -i option)."));
480 495
481 printf(" %s\n", _("Typically, the monitoring user (unless the --logname option is used) should be")); 496 printf(" %s\n",
482 printf(" %s\n", _("able to connect to the database without a password. The plugin can also send")); 497 _("Typically, the monitoring user (unless the --logname option is used) should be"));
498 printf(" %s\n",
499 _("able to connect to the database without a password. The plugin can also send"));
483 printf(" %s\n", _("a password, but no effort is made to obscure or encrypt the password.")); 500 printf(" %s\n", _("a password, but no effort is made to obscure or encrypt the password."));
484 501
485 printf(UT_SUPPORT); 502 printf(UT_SUPPORT);
@@ -492,15 +509,16 @@ void print_usage(void) {
492 "[-q <query>] [-C <critical query range>] [-W <warning query range>]\n"); 509 "[-q <query>] [-C <critical query range>] [-W <warning query range>]\n");
493} 510}
494 511
495mp_state_enum do_query(PGconn *conn, char *query, const char pgqueryname[], thresholds *qthresholds, char *query_warning, 512mp_state_enum do_query(PGconn *conn, char *query, const char pgqueryname[], thresholds *qthresholds,
496 char *query_critical) { 513 char *query_warning, char *query_critical) {
497 if (verbose) { 514 if (verbose) {
498 printf("Executing SQL query \"%s\".\n", query); 515 printf("Executing SQL query \"%s\".\n", query);
499 } 516 }
500 PGresult *res = PQexec(conn, query); 517 PGresult *res = PQexec(conn, query);
501 518
502 if (PGRES_TUPLES_OK != PQresultStatus(res)) { 519 if (PGRES_TUPLES_OK != PQresultStatus(res)) {
503 printf(_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"), PQerrorMessage(conn)); 520 printf(_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"),
521 PQerrorMessage(conn));
504 return STATE_CRITICAL; 522 return STATE_CRITICAL;
505 } 523 }
506 524
@@ -548,7 +566,8 @@ mp_state_enum do_query(PGconn *conn, char *query, const char pgqueryname[], thre
548 printf(_("'%s' returned %f"), query, value); 566 printf(_("'%s' returned %f"), query, value);
549 } 567 }
550 568
551 printf("|query=%f;%s;%s;;\n", value, query_warning ? query_warning : "", query_critical ? query_critical : ""); 569 printf("|query=%f;%s;%s;;\n", value, query_warning ? query_warning : "",
570 query_critical ? query_critical : "");
552 if (PQnfields(res) > 1) { 571 if (PQnfields(res) > 1) {
553 char *extra_info = PQgetvalue(res, 0, 1); 572 char *extra_info = PQgetvalue(res, 0, 1);
554 if (extra_info != NULL) { 573 if (extra_info != NULL) {
diff --git a/plugins/check_ping.c b/plugins/check_ping.c
index 6bcdeaad..61feb958 100644
--- a/plugins/check_ping.c
+++ b/plugins/check_ping.c
@@ -135,7 +135,8 @@ int main(int argc, char **argv) {
135 die(STATE_UNKNOWN, _("CRITICAL - Could not interpret output from ping command\n")); 135 die(STATE_UNKNOWN, _("CRITICAL - Could not interpret output from ping command\n"));
136 } 136 }
137 137
138 if (pinged.packet_loss >= config.cpl || pinged.round_trip_average >= config.crta || pinged.round_trip_average < 0) { 138 if (pinged.packet_loss >= config.cpl || pinged.round_trip_average >= config.crta ||
139 pinged.round_trip_average < 0) {
139 pinged.state = STATE_CRITICAL; 140 pinged.state = STATE_CRITICAL;
140 } else if (pinged.packet_loss >= config.wpl || pinged.round_trip_average >= config.wrta) { 141 } else if (pinged.packet_loss >= config.wpl || pinged.round_trip_average >= config.wrta) {
141 pinged.state = STATE_WARNING; 142 pinged.state = STATE_WARNING;
@@ -151,10 +152,11 @@ int main(int argc, char **argv) {
151 printf("<A HREF='%s/traceroute.cgi?%s'>", CGIURL, config.addresses[i]); 152 printf("<A HREF='%s/traceroute.cgi?%s'>", CGIURL, config.addresses[i]);
152 } 153 }
153 if (pinged.packet_loss == 100) { 154 if (pinged.packet_loss == 100) {
154 printf(_("PING %s - %sPacket loss = %d%%"), state_text(pinged.state), warn_text, pinged.packet_loss); 155 printf(_("PING %s - %sPacket loss = %d%%"), state_text(pinged.state), warn_text,
156 pinged.packet_loss);
155 } else { 157 } else {
156 printf(_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"), state_text(pinged.state), warn_text, pinged.packet_loss, 158 printf(_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"), state_text(pinged.state),
157 pinged.round_trip_average); 159 warn_text, pinged.packet_loss, pinged.round_trip_average);
158 } 160 }
159 if (config.display_html) { 161 if (config.display_html) {
160 printf("</A>"); 162 printf("</A>");
@@ -162,14 +164,16 @@ int main(int argc, char **argv) {
162 164
163 /* Print performance data */ 165 /* Print performance data */
164 if (pinged.packet_loss != 100) { 166 if (pinged.packet_loss != 100) {
165 printf("|%s", fperfdata("rta", pinged.round_trip_average, "ms", (bool)(config.wrta > 0), config.wrta, (bool)(config.crta > 0), 167 printf("|%s",
166 config.crta, true, 0, false, 0)); 168 fperfdata("rta", pinged.round_trip_average, "ms", (bool)(config.wrta > 0),
169 config.wrta, (bool)(config.crta > 0), config.crta, true, 0, false, 0));
167 } else { 170 } else {
168 printf("| rta=U;%f;%f;;", config.wrta, config.crta); 171 printf("| rta=U;%f;%f;;", config.wrta, config.crta);
169 } 172 }
170 173
171 printf(" %s\n", perfdata("pl", (long)pinged.packet_loss, "%", (bool)(config.wpl > 0), config.wpl, (bool)(config.cpl > 0), 174 printf(" %s\n",
172 config.cpl, true, 0, false, 0)); 175 perfdata("pl", (long)pinged.packet_loss, "%", (bool)(config.wpl > 0), config.wpl,
176 (bool)(config.cpl > 0), config.cpl, true, 0, false, 0));
173 177
174 if (verbose >= 2) { 178 if (verbose >= 2) {
175 printf("%f:%d%% %f:%d%%\n", config.wrta, config.wpl, config.crta, config.cpl); 179 printf("%f:%d%% %f:%d%%\n", config.wrta, config.wpl, config.crta, config.cpl);
@@ -254,7 +258,8 @@ check_ping_config_wrapper process_arguments(int argc, char **argv) {
254 result.config.n_addresses++; 258 result.config.n_addresses++;
255 if (result.config.n_addresses > max_addr) { 259 if (result.config.n_addresses > max_addr) {
256 max_addr *= 2; 260 max_addr *= 2;
257 result.config.addresses = realloc(result.config.addresses, sizeof(char *) * max_addr); 261 result.config.addresses =
262 realloc(result.config.addresses, sizeof(char *) * max_addr);
258 if (result.config.addresses == NULL) { 263 if (result.config.addresses == NULL) {
259 die(STATE_UNKNOWN, _("Could not realloc() addresses\n")); 264 die(STATE_UNKNOWN, _("Could not realloc() addresses\n"));
260 } 265 }
@@ -411,13 +416,15 @@ check_ping_config_wrapper validate_arguments(check_ping_config_wrapper config_wr
411 } 416 }
412 417
413 if (config_wrapper.config.wrta > config_wrapper.config.crta) { 418 if (config_wrapper.config.wrta > config_wrapper.config.crta) {
414 printf(_("<wrta> (%f) cannot be larger than <crta> (%f)\n"), config_wrapper.config.wrta, config_wrapper.config.crta); 419 printf(_("<wrta> (%f) cannot be larger than <crta> (%f)\n"), config_wrapper.config.wrta,
420 config_wrapper.config.crta);
415 config_wrapper.errorcode = ERROR; 421 config_wrapper.errorcode = ERROR;
416 return config_wrapper; 422 return config_wrapper;
417 } 423 }
418 424
419 if (config_wrapper.config.wpl > config_wrapper.config.cpl) { 425 if (config_wrapper.config.wpl > config_wrapper.config.cpl) {
420 printf(_("<wpl> (%d) cannot be larger than <cpl> (%d)\n"), config_wrapper.config.wpl, config_wrapper.config.cpl); 426 printf(_("<wpl> (%d) cannot be larger than <cpl> (%d)\n"), config_wrapper.config.wpl,
427 config_wrapper.config.cpl);
421 config_wrapper.errorcode = ERROR; 428 config_wrapper.errorcode = ERROR;
422 return config_wrapper; 429 return config_wrapper;
423 } 430 }
@@ -426,7 +433,8 @@ check_ping_config_wrapper validate_arguments(check_ping_config_wrapper config_wr
426 config_wrapper.config.max_packets = DEFAULT_MAX_PACKETS; 433 config_wrapper.config.max_packets = DEFAULT_MAX_PACKETS;
427 } 434 }
428 435
429 double max_seconds = (config_wrapper.config.crta / 1000.0 * config_wrapper.config.max_packets) + config_wrapper.config.max_packets; 436 double max_seconds = (config_wrapper.config.crta / 1000.0 * config_wrapper.config.max_packets) +
437 config_wrapper.config.max_packets;
430 if (max_seconds > timeout_interval) { 438 if (max_seconds > timeout_interval) {
431 timeout_interval = (unsigned int)max_seconds; 439 timeout_interval = (unsigned int)max_seconds;
432 } 440 }
@@ -470,37 +478,70 @@ ping_result run_ping(const char *cmd, const char *addr, double crta) {
470 478
471 /* get the percent loss statistics */ 479 /* get the percent loss statistics */
472 int match = 0; 480 int match = 0;
473 if ((sscanf(buf, "%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss%n", &result.packet_loss, &match) == 481 if ((sscanf(
474 1 && 482 buf,
483 "%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss%n",
484 &result.packet_loss, &match) == 1 &&
475 match) || 485 match) ||
476 (sscanf(buf, "%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet loss%n", &result.packet_loss, 486 (sscanf(buf,
477 &match) == 1 && 487 "%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet "
488 "loss%n",
489 &result.packet_loss, &match) == 1 &&
490 match) ||
491 (sscanf(buf,
492 "%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss%n",
493 &result.packet_loss, &match) == 1 &&
494 match) ||
495 (sscanf(buf, "%*d packets transmitted, %*d packets received, %d%% packet loss%n",
496 &result.packet_loss, &match) == 1 &&
497 match) ||
498 (sscanf(buf, "%*d packets transmitted, %*d packets received, %d%% loss, time%n",
499 &result.packet_loss, &match) == 1 &&
478 match) || 500 match) ||
479 (sscanf(buf, "%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss%n", &result.packet_loss, &match) == 1 && 501 (sscanf(buf, "%*d packets transmitted, %*d received, %d%% loss, time%n",
502 &result.packet_loss, &match) == 1 &&
480 match) || 503 match) ||
481 (sscanf(buf, "%*d packets transmitted, %*d packets received, %d%% packet loss%n", &result.packet_loss, &match) == 1 && match) || 504 (sscanf(buf, "%*d packets transmitted, %*d received, %d%% packet loss, time%n",
482 (sscanf(buf, "%*d packets transmitted, %*d packets received, %d%% loss, time%n", &result.packet_loss, &match) == 1 && match) || 505 &result.packet_loss, &match) == 1 &&
483 (sscanf(buf, "%*d packets transmitted, %*d received, %d%% loss, time%n", &result.packet_loss, &match) == 1 && match) || 506 match) == 1 ||
484 (sscanf(buf, "%*d packets transmitted, %*d received, %d%% packet loss, time%n", &result.packet_loss, &match) == 1 && match) == 507 (sscanf(buf, "%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss%n",
485 1 || 508 &result.packet_loss, &match) == 1 &&
486 (sscanf(buf, "%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss%n", &result.packet_loss, &match) == 1 &&
487 match) || 509 match) ||
488 (sscanf(buf, "%*d packets transmitted %*d received, +%*d errors, %d%% packet loss%n", &result.packet_loss, &match) == 1 && 510 (sscanf(buf, "%*d packets transmitted %*d received, +%*d errors, %d%% packet loss%n",
511 &result.packet_loss, &match) == 1 &&
489 match) || 512 match) ||
490 (sscanf(buf, "%*[^(](%d%% %*[^)])%n", &result.packet_loss, &match) == 1 && match)) { 513 (sscanf(buf, "%*[^(](%d%% %*[^)])%n", &result.packet_loss, &match) == 1 && match)) {
491 continue; 514 continue;
492 } 515 }
493 516
494 /* get the round trip average */ 517 /* get the round trip average */
495 if ((sscanf(buf, "round-trip min/avg/max = %*f/%lf/%*f%n", &result.round_trip_average, &match) == 1 && match) || 518 if ((sscanf(buf, "round-trip min/avg/max = %*f/%lf/%*f%n", &result.round_trip_average,
496 (sscanf(buf, "round-trip min/avg/max/mdev = %*f/%lf/%*f/%*f%n", &result.round_trip_average, &match) == 1 && match) || 519 &match) == 1 &&
497 (sscanf(buf, "round-trip min/avg/max/sdev = %*f/%lf/%*f/%*f%n", &result.round_trip_average, &match) == 1 && match) || 520 match) ||
498 (sscanf(buf, "round-trip min/avg/max/stddev = %*f/%lf/%*f/%*f%n", &result.round_trip_average, &match) == 1 && match) || 521 (sscanf(buf, "round-trip min/avg/max/mdev = %*f/%lf/%*f/%*f%n",
499 (sscanf(buf, "round-trip min/avg/max/std-dev = %*f/%lf/%*f/%*f%n", &result.round_trip_average, &match) == 1 && match) || 522 &result.round_trip_average, &match) == 1 &&
500 (sscanf(buf, "round-trip (ms) min/avg/max = %*f/%lf/%*f%n", &result.round_trip_average, &match) == 1 && match) || 523 match) ||
501 (sscanf(buf, "round-trip (ms) min/avg/max/stddev = %*f/%lf/%*f/%*f%n", &result.round_trip_average, &match) == 1 && match) || 524 (sscanf(buf, "round-trip min/avg/max/sdev = %*f/%lf/%*f/%*f%n",
502 (sscanf(buf, "rtt min/avg/max/mdev = %*f/%lf/%*f/%*f ms%n", &result.round_trip_average, &match) == 1 && match) || 525 &result.round_trip_average, &match) == 1 &&
503 (sscanf(buf, "%*[^=] = %*fms, %*[^=] = %*fms, %*[^=] = %lfms%n", &result.round_trip_average, &match) == 1 && match)) { 526 match) ||
527 (sscanf(buf, "round-trip min/avg/max/stddev = %*f/%lf/%*f/%*f%n",
528 &result.round_trip_average, &match) == 1 &&
529 match) ||
530 (sscanf(buf, "round-trip min/avg/max/std-dev = %*f/%lf/%*f/%*f%n",
531 &result.round_trip_average, &match) == 1 &&
532 match) ||
533 (sscanf(buf, "round-trip (ms) min/avg/max = %*f/%lf/%*f%n", &result.round_trip_average,
534 &match) == 1 &&
535 match) ||
536 (sscanf(buf, "round-trip (ms) min/avg/max/stddev = %*f/%lf/%*f/%*f%n",
537 &result.round_trip_average, &match) == 1 &&
538 match) ||
539 (sscanf(buf, "rtt min/avg/max/mdev = %*f/%lf/%*f/%*f ms%n", &result.round_trip_average,
540 &match) == 1 &&
541 match) ||
542 (sscanf(buf, "%*[^=] = %*fms, %*[^=] = %*fms, %*[^=] = %lfms%n",
543 &result.round_trip_average, &match) == 1 &&
544 match)) {
504 continue; 545 continue;
505 } 546 }
506 } 547 }
@@ -513,7 +554,8 @@ ping_result run_ping(const char *cmd, const char *addr, double crta) {
513 /* check stderr, setting at least WARNING if there is output here */ 554 /* check stderr, setting at least WARNING if there is output here */
514 /* Add warning into warn_text */ 555 /* Add warning into warn_text */
515 while (fgets(buf, MAX_INPUT_BUFFER - 1, child_stderr)) { 556 while (fgets(buf, MAX_INPUT_BUFFER - 1, child_stderr)) {
516 if (!strstr(buf, "WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP") && !strstr(buf, "Warning: time of day goes back") 557 if (!strstr(buf, "WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP") &&
558 !strstr(buf, "Warning: time of day goes back")
517 559
518 ) { 560 ) {
519 if (verbose >= 3) { 561 if (verbose >= 3) {
@@ -524,7 +566,8 @@ ping_result run_ping(const char *cmd, const char *addr, double crta) {
524 if (warn_text == NULL) { 566 if (warn_text == NULL) {
525 warn_text = strdup(_("System call sent warnings to stderr ")); 567 warn_text = strdup(_("System call sent warnings to stderr "));
526 } else { 568 } else {
527 xasprintf(&warn_text, "%s %s", warn_text, _("System call sent warnings to stderr ")); 569 xasprintf(&warn_text, "%s %s", warn_text,
570 _("System call sent warnings to stderr "));
528 } 571 }
529 } 572 }
530 } 573 }
@@ -542,7 +585,8 @@ ping_result run_ping(const char *cmd, const char *addr, double crta) {
542} 585}
543 586
544mp_state_enum error_scan(char buf[MAX_INPUT_BUFFER], const char *addr) { 587mp_state_enum error_scan(char buf[MAX_INPUT_BUFFER], const char *addr) {
545 if (strstr(buf, "Network is unreachable") || strstr(buf, "Destination Net Unreachable") || strstr(buf, "No route")) { 588 if (strstr(buf, "Network is unreachable") || strstr(buf, "Destination Net Unreachable") ||
589 strstr(buf, "No route")) {
546 die(STATE_CRITICAL, _("CRITICAL - Network Unreachable (%s)\n"), addr); 590 die(STATE_CRITICAL, _("CRITICAL - Network Unreachable (%s)\n"), addr);
547 } else if (strstr(buf, "Destination Host Unreachable") || strstr(buf, "Address unreachable")) { 591 } else if (strstr(buf, "Destination Host Unreachable") || strstr(buf, "Address unreachable")) {
548 die(STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)\n"), addr); 592 die(STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)\n"), addr);
@@ -567,7 +611,8 @@ mp_state_enum error_scan(char buf[MAX_INPUT_BUFFER], const char *addr) {
567 if (strstr(buf, "(DUP!)") || strstr(buf, "DUPLICATES FOUND")) { 611 if (strstr(buf, "(DUP!)") || strstr(buf, "DUPLICATES FOUND")) {
568 if (warn_text == NULL) { 612 if (warn_text == NULL) {
569 warn_text = strdup(_(WARN_DUPLICATES)); 613 warn_text = strdup(_(WARN_DUPLICATES));
570 } else if (!strstr(warn_text, _(WARN_DUPLICATES)) && xasprintf(&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1) { 614 } else if (!strstr(warn_text, _(WARN_DUPLICATES)) &&
615 xasprintf(&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1) {
571 die(STATE_UNKNOWN, _("Unable to realloc warn_text\n")); 616 die(STATE_UNKNOWN, _("Unable to realloc warn_text\n"));
572 } 617 }
573 return STATE_WARNING; 618 return STATE_WARNING;
@@ -613,8 +658,10 @@ void print_help(void) {
613 printf("%s\n", _("percentage of packet loss to trigger an alarm state.")); 658 printf("%s\n", _("percentage of packet loss to trigger an alarm state."));
614 659
615 printf("\n"); 660 printf("\n");
616 printf("%s\n", _("This plugin uses the ping command to probe the specified host for packet loss")); 661 printf("%s\n",
617 printf("%s\n", _("(percentage) and round trip average (milliseconds). It can produce HTML output.")); 662 _("This plugin uses the ping command to probe the specified host for packet loss"));
663 printf("%s\n",
664 _("(percentage) and round trip average (milliseconds). It can produce HTML output."));
618 665
619 printf(UT_SUPPORT); 666 printf(UT_SUPPORT);
620} 667}
diff --git a/plugins/check_procs.c b/plugins/check_procs.c
index 83e6864e..ae6e9c23 100644
--- a/plugins/check_procs.c
+++ b/plugins/check_procs.c
@@ -77,8 +77,8 @@ void print_usage(void);
77#define EREG_ARGS 1024 77#define EREG_ARGS 1024
78#define EXCLUDE_PROGS 2048 78#define EXCLUDE_PROGS 2048
79 79
80#define KTHREAD_PARENT \ 80#define KTHREAD_PARENT \
81 "kthreadd" /* the parent process of kernel threads: \ 81 "kthreadd" /* the parent process of kernel threads: \
82 ppid of procs are compared to pid of this proc*/ 82 ppid of procs are compared to pid of this proc*/
83 83
84static int verbose = 0; 84static int verbose = 0;
@@ -197,14 +197,17 @@ int main(int argc, char **argv) {
197 procseconds = convert_to_seconds(procetime, config.metric); 197 procseconds = convert_to_seconds(procetime, config.metric);
198 198
199 if (verbose >= 3) { 199 if (verbose >= 3) {
200 printf("proc#=%d uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", procs, procuid, procvsz, 200 printf("proc#=%d uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s "
201 procrss, procpid, procppid, procpcpu, procstat, procetime, procprog, procargs); 201 "prog=%s args=%s\n",
202 procs, procuid, procvsz, procrss, procpid, procppid, procpcpu, procstat,
203 procetime, procprog, procargs);
202 } 204 }
203 205
204 /* Ignore self */ 206 /* Ignore self */
205 int ret = 0; 207 int ret = 0;
206 if ((config.usepid && mypid == procpid) || 208 if ((config.usepid && mypid == procpid) ||
207 (((!config.usepid) && ((ret = stat_exe(procpid, &statbuf) != -1) && statbuf.st_dev == mydev && statbuf.st_ino == myino)) || 209 (((!config.usepid) && ((ret = stat_exe(procpid, &statbuf) != -1) &&
210 statbuf.st_dev == mydev && statbuf.st_ino == myino)) ||
208 (ret == -1 && errno == ENOENT))) { 211 (ret == -1 && errno == ENOENT))) {
209 if (verbose >= 3) { 212 if (verbose >= 3) {
210 printf("not considering - is myself or gone\n"); 213 printf("not considering - is myself or gone\n");
@@ -255,7 +258,8 @@ int main(int argc, char **argv) {
255 258
256 if (kthread_ppid == procppid) { 259 if (kthread_ppid == procppid) {
257 if (verbose >= 2) { 260 if (verbose >= 2) {
258 printf("Ignore kernel thread: pid=%d ppid=%d prog=%s args=%s\n", procpid, procppid, procprog, procargs); 261 printf("Ignore kernel thread: pid=%d ppid=%d prog=%s args=%s\n", procpid,
262 procppid, procprog, procargs);
259 } 263 }
260 continue; 264 continue;
261 } 265 }
@@ -267,7 +271,8 @@ int main(int argc, char **argv) {
267 if ((config.options & ARGS) && procargs && (strstr(procargs, config.args) != NULL)) { 271 if ((config.options & ARGS) && procargs && (strstr(procargs, config.args) != NULL)) {
268 resultsum |= ARGS; 272 resultsum |= ARGS;
269 } 273 }
270 if ((config.options & EREG_ARGS) && procargs && (regexec(&config.re_args, procargs, (size_t)0, NULL, 0) == 0)) { 274 if ((config.options & EREG_ARGS) && procargs &&
275 (regexec(&config.re_args, procargs, (size_t)0, NULL, 0) == 0)) {
271 resultsum |= EREG_ARGS; 276 resultsum |= EREG_ARGS;
272 } 277 }
273 if ((config.options & PROG) && procprog && (strcmp(config.prog, procprog) == 0)) { 278 if ((config.options & PROG) && procprog && (strcmp(config.prog, procprog) == 0)) {
@@ -298,8 +303,10 @@ int main(int argc, char **argv) {
298 303
299 procs++; 304 procs++;
300 if (verbose >= 2) { 305 if (verbose >= 2) {
301 printf("Matched: uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", procuid, procvsz, 306 printf("Matched: uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s "
302 procrss, procpid, procppid, procpcpu, procstat, procetime, procprog, procargs); 307 "prog=%s args=%s\n",
308 procuid, procvsz, procrss, procpid, procppid, procpcpu, procstat, procetime,
309 procprog, procargs);
303 } 310 }
304 311
305 mp_state_enum temporary_result = STATE_OK; 312 mp_state_enum temporary_result = STATE_OK;
@@ -318,12 +325,14 @@ int main(int argc, char **argv) {
318 if (config.metric != METRIC_PROCS) { 325 if (config.metric != METRIC_PROCS) {
319 if (temporary_result == STATE_WARNING) { 326 if (temporary_result == STATE_WARNING) {
320 warn++; 327 warn++;
321 xasprintf(&config.fails, "%s%s%s", config.fails, (strcmp(config.fails, "") ? ", " : ""), procprog); 328 xasprintf(&config.fails, "%s%s%s", config.fails,
329 (strcmp(config.fails, "") ? ", " : ""), procprog);
322 result = max_state(result, temporary_result); 330 result = max_state(result, temporary_result);
323 } 331 }
324 if (temporary_result == STATE_CRITICAL) { 332 if (temporary_result == STATE_CRITICAL) {
325 crit++; 333 crit++;
326 xasprintf(&config.fails, "%s%s%s", config.fails, (strcmp(config.fails, "") ? ", " : ""), procprog); 334 xasprintf(&config.fails, "%s%s%s", config.fails,
335 (strcmp(config.fails, "") ? ", " : ""), procprog);
327 result = max_state(result, temporary_result); 336 result = max_state(result, temporary_result);
328 } 337 }
329 } 338 }
@@ -420,7 +429,8 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
420 429
421 while (true) { 430 while (true) {
422 int option = 0; 431 int option = 0;
423 int option_index = getopt_long(argc, argv, "Vvhkt:c:w:p:s:u:C:a:z:r:m:P:T:X:", longopts, &option); 432 int option_index =
433 getopt_long(argc, argv, "Vvhkt:c:w:p:s:u:C:a:z:r:m:P:T:X:", longopts, &option);
424 434
425 if (option_index == -1 || option_index == EOF) { 435 if (option_index == -1 || option_index == EOF) {
426 break; 436 break;
@@ -451,7 +461,8 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
451 case 'p': { /* process id */ 461 case 'p': { /* process id */
452 static char tmp[MAX_INPUT_BUFFER]; 462 static char tmp[MAX_INPUT_BUFFER];
453 if (sscanf(optarg, "%d%[^0-9]", &result.config.ppid, tmp) == 1) { 463 if (sscanf(optarg, "%d%[^0-9]", &result.config.ppid, tmp) == 1) {
454 xasprintf(&result.config.fmt, "%s%sPPID = %d", (result.config.fmt ? result.config.fmt : ""), 464 xasprintf(&result.config.fmt, "%s%sPPID = %d",
465 (result.config.fmt ? result.config.fmt : ""),
455 (result.config.options ? ", " : ""), result.config.ppid); 466 (result.config.options ? ", " : ""), result.config.ppid);
456 result.config.options |= PPID; 467 result.config.options |= PPID;
457 break; 468 break;
@@ -464,7 +475,8 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
464 } else { 475 } else {
465 result.config.statopts = optarg; 476 result.config.statopts = optarg;
466 } 477 }
467 xasprintf(&result.config.fmt, _("%s%sSTATE = %s"), (result.config.fmt ? result.config.fmt : ""), 478 xasprintf(&result.config.fmt, _("%s%sSTATE = %s"),
479 (result.config.fmt ? result.config.fmt : ""),
468 (result.config.options ? ", " : ""), result.config.statopts); 480 (result.config.options ? ", " : ""), result.config.statopts);
469 result.config.options |= STAT; 481 result.config.options |= STAT;
470 break; 482 break;
@@ -488,7 +500,8 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
488 } 500 }
489 501
490 char *user = pw->pw_name; 502 char *user = pw->pw_name;
491 xasprintf(&result.config.fmt, "%s%sUID = %d (%s)", (result.config.fmt ? result.config.fmt : ""), 503 xasprintf(&result.config.fmt, "%s%sUID = %d (%s)",
504 (result.config.fmt ? result.config.fmt : ""),
492 (result.config.options ? ", " : ""), result.config.uid, user); 505 (result.config.options ? ", " : ""), result.config.uid, user);
493 result.config.options |= USER; 506 result.config.options |= USER;
494 } break; 507 } break;
@@ -499,7 +512,8 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
499 } else { 512 } else {
500 result.config.prog = optarg; 513 result.config.prog = optarg;
501 } 514 }
502 xasprintf(&result.config.fmt, _("%s%scommand name '%s'"), (result.config.fmt ? result.config.fmt : ""), 515 xasprintf(&result.config.fmt, _("%s%scommand name '%s'"),
516 (result.config.fmt ? result.config.fmt : ""),
503 (result.config.options ? ", " : ""), result.config.prog); 517 (result.config.options ? ", " : ""), result.config.prog);
504 result.config.options |= PROG; 518 result.config.options |= PROG;
505 break; 519 break;
@@ -509,14 +523,17 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
509 } else { 523 } else {
510 result.config.exclude_progs = optarg; 524 result.config.exclude_progs = optarg;
511 } 525 }
512 xasprintf(&result.config.fmt, _("%s%sexclude progs '%s'"), (result.config.fmt ? result.config.fmt : ""), 526 xasprintf(&result.config.fmt, _("%s%sexclude progs '%s'"),
527 (result.config.fmt ? result.config.fmt : ""),
513 (result.config.options ? ", " : ""), result.config.exclude_progs); 528 (result.config.options ? ", " : ""), result.config.exclude_progs);
514 char *tmp_pointer = strtok(result.config.exclude_progs, ","); 529 char *tmp_pointer = strtok(result.config.exclude_progs, ",");
515 530
516 while (tmp_pointer) { 531 while (tmp_pointer) {
517 result.config.exclude_progs_arr = 532 result.config.exclude_progs_arr =
518 realloc(result.config.exclude_progs_arr, sizeof(char *) * ++result.config.exclude_progs_counter); 533 realloc(result.config.exclude_progs_arr,
519 result.config.exclude_progs_arr[result.config.exclude_progs_counter - 1] = tmp_pointer; 534 sizeof(char *) * ++result.config.exclude_progs_counter);
535 result.config.exclude_progs_arr[result.config.exclude_progs_counter - 1] =
536 tmp_pointer;
520 tmp_pointer = strtok(NULL, ","); 537 tmp_pointer = strtok(NULL, ",");
521 } 538 }
522 539
@@ -529,7 +546,8 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
529 } else { 546 } else {
530 result.config.args = optarg; 547 result.config.args = optarg;
531 } 548 }
532 xasprintf(&result.config.fmt, "%s%sargs '%s'", (result.config.fmt ? result.config.fmt : ""), 549 xasprintf(&result.config.fmt, "%s%sargs '%s'",
550 (result.config.fmt ? result.config.fmt : ""),
533 (result.config.options ? ", " : ""), result.config.args); 551 (result.config.options ? ", " : ""), result.config.args);
534 result.config.options |= ARGS; 552 result.config.options |= ARGS;
535 break; 553 break;
@@ -539,7 +557,8 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
539 if (err != 0) { 557 if (err != 0) {
540 char errbuf[MAX_INPUT_BUFFER]; 558 char errbuf[MAX_INPUT_BUFFER];
541 regerror(err, &result.config.re_args, errbuf, MAX_INPUT_BUFFER); 559 regerror(err, &result.config.re_args, errbuf, MAX_INPUT_BUFFER);
542 die(STATE_UNKNOWN, "PROCS %s: %s - %s\n", _("UNKNOWN"), _("Could not compile regular expression"), errbuf); 560 die(STATE_UNKNOWN, "PROCS %s: %s - %s\n", _("UNKNOWN"),
561 _("Could not compile regular expression"), errbuf);
543 } 562 }
544 /* Strip off any | within the regex optarg */ 563 /* Strip off any | within the regex optarg */
545 char *temp_string = strdup(optarg); 564 char *temp_string = strdup(optarg);
@@ -550,14 +569,16 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
550 } 569 }
551 index++; 570 index++;
552 } 571 }
553 xasprintf(&result.config.fmt, "%s%sregex args '%s'", (result.config.fmt ? result.config.fmt : ""), 572 xasprintf(&result.config.fmt, "%s%sregex args '%s'",
573 (result.config.fmt ? result.config.fmt : ""),
554 (result.config.options ? ", " : ""), temp_string); 574 (result.config.options ? ", " : ""), temp_string);
555 result.config.options |= EREG_ARGS; 575 result.config.options |= EREG_ARGS;
556 } break; 576 } break;
557 case 'r': { /* RSS */ 577 case 'r': { /* RSS */
558 static char tmp[MAX_INPUT_BUFFER]; 578 static char tmp[MAX_INPUT_BUFFER];
559 if (sscanf(optarg, "%d%[^0-9]", &result.config.rss, tmp) == 1) { 579 if (sscanf(optarg, "%d%[^0-9]", &result.config.rss, tmp) == 1) {
560 xasprintf(&result.config.fmt, "%s%sRSS >= %d", (result.config.fmt ? result.config.fmt : ""), 580 xasprintf(&result.config.fmt, "%s%sRSS >= %d",
581 (result.config.fmt ? result.config.fmt : ""),
561 (result.config.options ? ", " : ""), result.config.rss); 582 (result.config.options ? ", " : ""), result.config.rss);
562 result.config.options |= RSS; 583 result.config.options |= RSS;
563 break; 584 break;
@@ -567,7 +588,8 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
567 case 'z': { /* VSZ */ 588 case 'z': { /* VSZ */
568 static char tmp[MAX_INPUT_BUFFER]; 589 static char tmp[MAX_INPUT_BUFFER];
569 if (sscanf(optarg, "%d%[^0-9]", &result.config.vsz, tmp) == 1) { 590 if (sscanf(optarg, "%d%[^0-9]", &result.config.vsz, tmp) == 1) {
570 xasprintf(&result.config.fmt, "%s%sVSZ >= %d", (result.config.fmt ? result.config.fmt : ""), 591 xasprintf(&result.config.fmt, "%s%sVSZ >= %d",
592 (result.config.fmt ? result.config.fmt : ""),
571 (result.config.options ? ", " : ""), result.config.vsz); 593 (result.config.options ? ", " : ""), result.config.vsz);
572 result.config.options |= VSZ; 594 result.config.options |= VSZ;
573 break; 595 break;
@@ -578,7 +600,8 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
578 /* TODO: -P 1.5.5 is accepted */ 600 /* TODO: -P 1.5.5 is accepted */
579 static char tmp[MAX_INPUT_BUFFER]; 601 static char tmp[MAX_INPUT_BUFFER];
580 if (sscanf(optarg, "%f%[^0-9.]", &result.config.pcpu, tmp) == 1) { 602 if (sscanf(optarg, "%f%[^0-9.]", &result.config.pcpu, tmp) == 1) {
581 xasprintf(&result.config.fmt, "%s%sPCPU >= %.2f", (result.config.fmt ? result.config.fmt : ""), 603 xasprintf(&result.config.fmt, "%s%sPCPU >= %.2f",
604 (result.config.fmt ? result.config.fmt : ""),
582 (result.config.options ? ", " : ""), result.config.pcpu); 605 (result.config.options ? ", " : ""), result.config.pcpu);
583 result.config.options |= PCPU; 606 result.config.options |= PCPU;
584 break; 607 break;
@@ -633,13 +656,15 @@ check_procs_config_wrapper process_arguments(int argc, char **argv) {
633 } 656 }
634 if (result.config.statopts == NULL && argv[index]) { 657 if (result.config.statopts == NULL && argv[index]) {
635 xasprintf(&result.config.statopts, "%s", argv[index++]); 658 xasprintf(&result.config.statopts, "%s", argv[index++]);
636 xasprintf(&result.config.fmt, _("%s%sSTATE = %s"), (result.config.fmt ? result.config.fmt : ""), 659 xasprintf(&result.config.fmt, _("%s%sSTATE = %s"),
637 (result.config.options ? ", " : ""), result.config.statopts); 660 (result.config.fmt ? result.config.fmt : ""), (result.config.options ? ", " : ""),
661 result.config.statopts);
638 result.config.options |= STAT; 662 result.config.options |= STAT;
639 } 663 }
640 664
641 /* this will abort in case of invalid ranges */ 665 /* this will abort in case of invalid ranges */
642 set_thresholds(&result.config.procs_thresholds, result.config.warning_range, result.config.critical_range); 666 set_thresholds(&result.config.procs_thresholds, result.config.warning_range,
667 result.config.critical_range);
643 668
644 return validate_arguments(result); 669 return validate_arguments(result);
645} 670}
@@ -722,13 +747,17 @@ void print_help(void) {
722 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"); 747 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
723 printf(COPYRIGHT, copyright, email); 748 printf(COPYRIGHT, copyright, email);
724 749
725 printf("%s\n", _("Checks all processes and generates WARNING or CRITICAL states if the specified")); 750 printf("%s\n",
726 printf("%s\n", _("metric is outside the required threshold ranges. The metric defaults to number")); 751 _("Checks all processes and generates WARNING or CRITICAL states if the specified"));
727 printf("%s\n", _("of processes. Search filters can be applied to limit the processes to check.")); 752 printf("%s\n",
753 _("metric is outside the required threshold ranges. The metric defaults to number"));
754 printf("%s\n",
755 _("of processes. Search filters can be applied to limit the processes to check."));
728 756
729 printf("\n\n"); 757 printf("\n\n");
730 758
731 printf("%s\n", _("The parent process, check_procs itself and any child process of check_procs (ps)")); 759 printf("%s\n",
760 _("The parent process, check_procs itself and any child process of check_procs (ps)"));
732 printf("%s\n", _("are excluded from any checks to prevent false positives.")); 761 printf("%s\n", _("are excluded from any checks to prevent false positives."));
733 762
734 printf("\n\n"); 763 printf("\n\n");
diff --git a/plugins/check_radius.c b/plugins/check_radius.c
index cc846709..d26f7cf3 100644
--- a/plugins/check_radius.c
+++ b/plugins/check_radius.c
@@ -56,7 +56,8 @@ static check_radius_config_wrapper process_arguments(int /*argc*/, char ** /*arg
56static void print_help(void); 56static void print_help(void);
57void print_usage(void); 57void print_usage(void);
58 58
59#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) || defined(HAVE_LIBRADCLI) 59#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) || \
60 defined(HAVE_LIBRADCLI)
60# define my_rc_conf_str(a) rc_conf_str(rch, a) 61# define my_rc_conf_str(a) rc_conf_str(rch, a)
61# if defined(HAVE_LIBRADCLI) 62# if defined(HAVE_LIBRADCLI)
62# define my_rc_send_server(a, b) rc_send_server(rch, a, b, AUTH) 63# define my_rc_send_server(a, b) rc_send_server(rch, a, b, AUTH)
@@ -157,12 +158,14 @@ int main(int argc, char **argv) {
157 158
158 check_radius_config config = tmp_config.config; 159 check_radius_config config = tmp_config.config;
159 160
160#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) || defined(HAVE_LIBRADCLI) 161#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) || \
162 defined(HAVE_LIBRADCLI)
161 rc_handle *rch = NULL; 163 rc_handle *rch = NULL;
162#endif 164#endif
163 165
164 char *str = strdup("dictionary"); 166 char *str = strdup("dictionary");
165 if ((config.config_file && my_rc_read_config(config.config_file, &rch)) || my_rc_read_dictionary(my_rc_conf_str(str))) { 167 if ((config.config_file && my_rc_read_config(config.config_file, &rch)) ||
168 my_rc_read_dictionary(my_rc_conf_str(str))) {
166 die(STATE_UNKNOWN, _("Config file error\n")); 169 die(STATE_UNKNOWN, _("Config file error\n"));
167 } 170 }
168 171
@@ -200,7 +203,8 @@ int main(int argc, char **argv) {
200 die(STATE_UNKNOWN, _("Invalid NAS-IP-Address\n")); 203 die(STATE_UNKNOWN, _("Invalid NAS-IP-Address\n"));
201 } 204 }
202 205
203 my_rc_buildreq(&data, PW_ACCESS_REQUEST, config.server, config.port, (int)timeout_interval, config.retries); 206 my_rc_buildreq(&data, PW_ACCESS_REQUEST, config.server, config.port, (int)timeout_interval,
207 config.retries);
204 208
205#ifdef RC_BUFFER_LEN 209#ifdef RC_BUFFER_LEN
206 char msg[RC_BUFFER_LEN]; 210 char msg[RC_BUFFER_LEN];
@@ -251,13 +255,14 @@ int main(int argc, char **argv) {
251 255
252/* process command-line arguments */ 256/* process command-line arguments */
253check_radius_config_wrapper process_arguments(int argc, char **argv) { 257check_radius_config_wrapper process_arguments(int argc, char **argv) {
254 static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, {"port", required_argument, 0, 'P'}, 258 static struct option longopts[] = {
255 {"username", required_argument, 0, 'u'}, {"password", required_argument, 0, 'p'}, 259 {"hostname", required_argument, 0, 'H'}, {"port", required_argument, 0, 'P'},
256 {"nas-id", required_argument, 0, 'n'}, {"nas-ip-address", required_argument, 0, 'N'}, 260 {"username", required_argument, 0, 'u'}, {"password", required_argument, 0, 'p'},
257 {"filename", required_argument, 0, 'F'}, {"expect", required_argument, 0, 'e'}, 261 {"nas-id", required_argument, 0, 'n'}, {"nas-ip-address", required_argument, 0, 'N'},
258 {"retries", required_argument, 0, 'r'}, {"timeout", required_argument, 0, 't'}, 262 {"filename", required_argument, 0, 'F'}, {"expect", required_argument, 0, 'e'},
259 {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, 263 {"retries", required_argument, 0, 'r'}, {"timeout", required_argument, 0, 't'},
260 {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; 264 {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'},
265 {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}};
261 266
262 check_radius_config_wrapper result = { 267 check_radius_config_wrapper result = {
263 .errorcode = OK, 268 .errorcode = OK,
@@ -397,9 +402,11 @@ void print_help(void) {
397 printf("%s\n", _("name and password. A configuration file must be present. The format of")); 402 printf("%s\n", _("name and password. A configuration file must be present. The format of"));
398 printf("%s\n", _("the configuration file is described in the radiusclient library sources.")); 403 printf("%s\n", _("the configuration file is described in the radiusclient library sources."));
399 printf("%s\n", _("The password option presents a substantial security issue because the")); 404 printf("%s\n", _("The password option presents a substantial security issue because the"));
400 printf("%s\n", _("password can possibly be determined by careful watching of the command line")); 405 printf("%s\n",
406 _("password can possibly be determined by careful watching of the command line"));
401 printf("%s\n", _("in a process listing. This risk is exacerbated because the plugin will")); 407 printf("%s\n", _("in a process listing. This risk is exacerbated because the plugin will"));
402 printf("%s\n", _("typically be executed at regular predictable intervals. Please be sure that")); 408 printf("%s\n",
409 _("typically be executed at regular predictable intervals. Please be sure that"));
403 printf("%s\n", _("the password used does not allow access to sensitive system resources.")); 410 printf("%s\n", _("the password used does not allow access to sensitive system resources."));
404 411
405 printf(UT_SUPPORT); 412 printf(UT_SUPPORT);
@@ -414,7 +421,8 @@ void print_usage(void) {
414} 421}
415 422
416int my_rc_read_config(char *config_file_name, rc_handle **rch) { 423int my_rc_read_config(char *config_file_name, rc_handle **rch) {
417#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) || defined(HAVE_LIBRADCLI) 424#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) || \
425 defined(HAVE_LIBRADCLI)
418 *rch = rc_read_config(config_file_name); 426 *rch = rc_read_config(config_file_name);
419 return (rch == NULL) ? 1 : 0; 427 return (rch == NULL) ? 1 : 0;
420#else 428#else
diff --git a/plugins/check_real.c b/plugins/check_real.c
index ec0928ed..66d07f8f 100644
--- a/plugins/check_real.c
+++ b/plugins/check_real.c
@@ -78,7 +78,8 @@ int main(int argc, char **argv) {
78 /* try to connect to the host at the given port number */ 78 /* try to connect to the host at the given port number */
79 int socket; 79 int socket;
80 if (my_tcp_connect(config.server_address, config.server_port, &socket) != STATE_OK) { 80 if (my_tcp_connect(config.server_address, config.server_port, &socket) != STATE_OK) {
81 die(STATE_CRITICAL, _("Unable to connect to %s on port %d\n"), config.server_address, config.server_port); 81 die(STATE_CRITICAL, _("Unable to connect to %s on port %d\n"), config.server_address,
82 config.server_port);
82 } 83 }
83 84
84 /* Part I - Server Check */ 85 /* Part I - Server Check */
@@ -166,7 +167,8 @@ int main(int argc, char **argv) {
166 /* Part I - Server Check */ 167 /* Part I - Server Check */
167 168
168 /* send the DESCRIBE request */ 169 /* send the DESCRIBE request */
169 sprintf(buffer, "DESCRIBE rtsp://%s:%d%s RTSP/1.0\r\n", config.host_name, config.server_port, config.server_url); 170 sprintf(buffer, "DESCRIBE rtsp://%s:%d%s RTSP/1.0\r\n", config.host_name,
171 config.server_port, config.server_url);
170 172
171 ssize_t sent_bytes = send(socket, buffer, strlen(buffer), 0); 173 ssize_t sent_bytes = send(socket, buffer, strlen(buffer), 0);
172 if (sent_bytes == -1) { 174 if (sent_bytes == -1) {
@@ -200,7 +202,8 @@ int main(int argc, char **argv) {
200 if (config.server_port == PORT) { 202 if (config.server_port == PORT) {
201 printf("%s\n", _("Invalid REAL response received from host")); 203 printf("%s\n", _("Invalid REAL response received from host"));
202 } else { 204 } else {
203 printf(_("Invalid REAL response received from host on port %d\n"), config.server_port); 205 printf(_("Invalid REAL response received from host on port %d\n"),
206 config.server_port);
204 } 207 }
205 } else { 208 } else {
206 209
@@ -256,7 +259,8 @@ int main(int argc, char **argv) {
256 } 259 }
257 260
258 /* Put some HTML in here to create a dynamic link */ 261 /* Put some HTML in here to create a dynamic link */
259 printf(_("REAL %s - %d second response time\n"), state_text(result), (int)(end_time - start_time)); 262 printf(_("REAL %s - %d second response time\n"), state_text(result),
263 (int)(end_time - start_time));
260 } else { 264 } else {
261 printf("%s\n", status_line); 265 printf("%s\n", status_line);
262 } 266 }
@@ -272,12 +276,13 @@ int main(int argc, char **argv) {
272 276
273/* process command-line arguments */ 277/* process command-line arguments */
274check_real_config_wrapper process_arguments(int argc, char **argv) { 278check_real_config_wrapper process_arguments(int argc, char **argv) {
275 static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, {"IPaddress", required_argument, 0, 'I'}, 279 static struct option longopts[] = {
276 {"expect", required_argument, 0, 'e'}, {"url", required_argument, 0, 'u'}, 280 {"hostname", required_argument, 0, 'H'}, {"IPaddress", required_argument, 0, 'I'},
277 {"port", required_argument, 0, 'p'}, {"critical", required_argument, 0, 'c'}, 281 {"expect", required_argument, 0, 'e'}, {"url", required_argument, 0, 'u'},
278 {"warning", required_argument, 0, 'w'}, {"timeout", required_argument, 0, 't'}, 282 {"port", required_argument, 0, 'p'}, {"critical", required_argument, 0, 'c'},
279 {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, 283 {"warning", required_argument, 0, 'w'}, {"timeout", required_argument, 0, 't'},
280 {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; 284 {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'},
285 {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}};
281 286
282 check_real_config_wrapper result = { 287 check_real_config_wrapper result = {
283 .errorcode = OK, 288 .errorcode = OK,
@@ -427,7 +432,8 @@ void print_help(void) {
427 printf("%s\n", _("This plugin will attempt to open an RTSP connection with the host.")); 432 printf("%s\n", _("This plugin will attempt to open an RTSP connection with the host."));
428 printf("%s\n", _("Successful connects return STATE_OK, refusals and timeouts return")); 433 printf("%s\n", _("Successful connects return STATE_OK, refusals and timeouts return"));
429 printf("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful connects,")); 434 printf("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful connects,"));
430 printf("%s\n", _("but incorrect response messages from the host result in STATE_WARNING return")); 435 printf("%s\n",
436 _("but incorrect response messages from the host result in STATE_WARNING return"));
431 printf("%s\n", _("values.")); 437 printf("%s\n", _("values."));
432 438
433 printf(UT_SUPPORT); 439 printf(UT_SUPPORT);
diff --git a/plugins/check_smtp.c b/plugins/check_smtp.c
index 44b735f9..83ad575c 100644
--- a/plugins/check_smtp.c
+++ b/plugins/check_smtp.c
@@ -58,7 +58,8 @@ typedef struct {
58} check_smtp_config_wrapper; 58} check_smtp_config_wrapper;
59static check_smtp_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/); 59static check_smtp_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
60 60
61int my_recv(check_smtp_config config, void *buf, int num, int socket_descriptor, bool ssl_established) { 61int my_recv(check_smtp_config config, void *buf, int num, int socket_descriptor,
62 bool ssl_established) {
62#ifdef HAVE_SSL 63#ifdef HAVE_SSL
63 if ((config.use_starttls || config.use_ssl) && ssl_established) { 64 if ((config.use_starttls || config.use_ssl) && ssl_established) {
64 return np_net_ssl_read(buf, num); 65 return np_net_ssl_read(buf, num);
@@ -69,7 +70,8 @@ int my_recv(check_smtp_config config, void *buf, int num, int socket_descriptor,
69#endif 70#endif
70} 71}
71 72
72int my_send(check_smtp_config config, void *buf, int num, int socket_descriptor, bool ssl_established) { 73int my_send(check_smtp_config config, void *buf, int num, int socket_descriptor,
74 bool ssl_established) {
73#ifdef HAVE_SSL 75#ifdef HAVE_SSL
74 if ((config.use_starttls || config.use_ssl) && ssl_established) { 76 if ((config.use_starttls || config.use_ssl) && ssl_established) {
75 77
@@ -83,10 +85,12 @@ int my_send(check_smtp_config config, void *buf, int num, int socket_descriptor,
83 85
84static void print_help(void); 86static void print_help(void);
85void print_usage(void); 87void print_usage(void);
86static char *smtp_quit(check_smtp_config /*config*/, char /*buffer*/[MAX_INPUT_BUFFER], int /*socket_descriptor*/, 88static char *smtp_quit(check_smtp_config /*config*/, char /*buffer*/[MAX_INPUT_BUFFER],
87 bool /*ssl_established*/); 89 int /*socket_descriptor*/, bool /*ssl_established*/);
88static int recvline(char * /*buf*/, size_t /*bufsize*/, check_smtp_config /*config*/, int /*socket_descriptor*/, bool /*ssl_established*/); 90static int recvline(char * /*buf*/, size_t /*bufsize*/, check_smtp_config /*config*/,
89static int recvlines(check_smtp_config /*config*/, char * /*buf*/, size_t /*bufsize*/, int /*socket_descriptor*/, bool /*ssl_established*/); 91 int /*socket_descriptor*/, bool /*ssl_established*/);
92static int recvlines(check_smtp_config /*config*/, char * /*buf*/, size_t /*bufsize*/,
93 int /*socket_descriptor*/, bool /*ssl_established*/);
90static int my_close(int /*socket_descriptor*/); 94static int my_close(int /*socket_descriptor*/);
91 95
92static int verbose = 0; 96static int verbose = 0;
@@ -158,7 +162,8 @@ int main(int argc, char **argv) {
158 162
159 int socket_descriptor = 0; 163 int socket_descriptor = 0;
160 /* try to connect to the host at the given port number */ 164 /* try to connect to the host at the given port number */
161 mp_state_enum result = my_tcp_connect(config.server_address, config.server_port, &socket_descriptor); 165 mp_state_enum result =
166 my_tcp_connect(config.server_address, config.server_port, &socket_descriptor);
162 167
163 char *error_msg = ""; 168 char *error_msg = "";
164 char buffer[MAX_INPUT_BUFFER]; 169 char buffer[MAX_INPUT_BUFFER];
@@ -174,7 +179,8 @@ int main(int argc, char **argv) {
174 179
175#ifdef HAVE_SSL 180#ifdef HAVE_SSL
176 if (config.use_ssl) { 181 if (config.use_ssl) {
177 result = np_net_ssl_init_with_hostname(socket_descriptor, (config.use_sni ? config.server_address : NULL)); 182 result = np_net_ssl_init_with_hostname(socket_descriptor,
183 (config.use_sni ? config.server_address : NULL));
178 if (result != STATE_OK) { 184 if (result != STATE_OK) {
179 printf(_("CRITICAL - Cannot create SSL context.\n")); 185 printf(_("CRITICAL - Cannot create SSL context.\n"));
180 close(socket_descriptor); 186 close(socket_descriptor);
@@ -223,14 +229,16 @@ int main(int argc, char **argv) {
223 /* send the STARTTLS command */ 229 /* send the STARTTLS command */
224 send(socket_descriptor, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0); 230 send(socket_descriptor, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
225 231
226 recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established); /* wait for it */ 232 recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
233 ssl_established); /* wait for it */
227 if (!strstr(buffer, SMTP_EXPECT)) { 234 if (!strstr(buffer, SMTP_EXPECT)) {
228 printf(_("Server does not support STARTTLS\n")); 235 printf(_("Server does not support STARTTLS\n"));
229 smtp_quit(config, buffer, socket_descriptor, ssl_established); 236 smtp_quit(config, buffer, socket_descriptor, ssl_established);
230 exit(STATE_UNKNOWN); 237 exit(STATE_UNKNOWN);
231 } 238 }
232 239
233 result = np_net_ssl_init_with_hostname(socket_descriptor, (config.use_sni ? config.server_address : NULL)); 240 result = np_net_ssl_init_with_hostname(socket_descriptor,
241 (config.use_sni ? config.server_address : NULL));
234 if (result != STATE_OK) { 242 if (result != STATE_OK) {
235 printf(_("CRITICAL - Cannot create SSL context.\n")); 243 printf(_("CRITICAL - Cannot create SSL context.\n"));
236 close(socket_descriptor); 244 close(socket_descriptor);
@@ -251,7 +259,8 @@ int main(int argc, char **argv) {
251 * reason, some MTAs will not allow an AUTH LOGIN command before 259 * reason, some MTAs will not allow an AUTH LOGIN command before
252 * we resent EHLO via TLS. 260 * we resent EHLO via TLS.
253 */ 261 */
254 if (my_send(config, helocmd, strlen(helocmd), socket_descriptor, ssl_established) <= 0) { 262 if (my_send(config, helocmd, strlen(helocmd), socket_descriptor, ssl_established) <=
263 0) {
255 printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS.")); 264 printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
256 my_close(socket_descriptor); 265 my_close(socket_descriptor);
257 exit(STATE_UNKNOWN); 266 exit(STATE_UNKNOWN);
@@ -261,7 +270,8 @@ int main(int argc, char **argv) {
261 printf(_("sent %s"), helocmd); 270 printf(_("sent %s"), helocmd);
262 } 271 }
263 272
264 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) <= 0) { 273 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) <=
274 0) {
265 printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS.")); 275 printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
266 my_close(socket_descriptor); 276 my_close(socket_descriptor);
267 exit(STATE_UNKNOWN); 277 exit(STATE_UNKNOWN);
@@ -273,7 +283,8 @@ int main(int argc, char **argv) {
273 283
274# ifdef USE_OPENSSL 284# ifdef USE_OPENSSL
275 if (config.check_cert) { 285 if (config.check_cert) {
276 result = np_net_ssl_check_cert(config.days_till_exp_warn, config.days_till_exp_crit); 286 result =
287 np_net_ssl_check_cert(config.days_till_exp_warn, config.days_till_exp_crit);
277 smtp_quit(config, buffer, socket_descriptor, ssl_established); 288 smtp_quit(config, buffer, socket_descriptor, ssl_established);
278 my_close(socket_descriptor); 289 my_close(socket_descriptor);
279 exit(result); 290 exit(result);
@@ -296,14 +307,17 @@ int main(int argc, char **argv) {
296 if (config.server_port == SMTP_PORT) { 307 if (config.server_port == SMTP_PORT) {
297 printf(_("Invalid SMTP response received from host: %s\n"), server_response); 308 printf(_("Invalid SMTP response received from host: %s\n"), server_response);
298 } else { 309 } else {
299 printf(_("Invalid SMTP response received from host on port %d: %s\n"), config.server_port, server_response); 310 printf(_("Invalid SMTP response received from host on port %d: %s\n"),
311 config.server_port, server_response);
300 } 312 }
301 exit(STATE_WARNING); 313 exit(STATE_WARNING);
302 } 314 }
303 315
304 if (config.send_mail_from) { 316 if (config.send_mail_from) {
305 my_send(config, cmd_str, (int)strlen(cmd_str), socket_descriptor, ssl_established); 317 my_send(config, cmd_str, (int)strlen(cmd_str), socket_descriptor, ssl_established);
306 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) >= 1 && verbose) { 318 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) >=
319 1 &&
320 verbose) {
307 printf("%s", buffer); 321 printf("%s", buffer);
308 } 322 }
309 } 323 }
@@ -312,7 +326,9 @@ int main(int argc, char **argv) {
312 while (counter < config.ncommands) { 326 while (counter < config.ncommands) {
313 xasprintf(&cmd_str, "%s%s", config.commands[counter], "\r\n"); 327 xasprintf(&cmd_str, "%s%s", config.commands[counter], "\r\n");
314 my_send(config, cmd_str, (int)strlen(cmd_str), socket_descriptor, ssl_established); 328 my_send(config, cmd_str, (int)strlen(cmd_str), socket_descriptor, ssl_established);
315 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) >= 1 && verbose) { 329 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) >=
330 1 &&
331 verbose) {
316 printf("%s", buffer); 332 printf("%s", buffer);
317 } 333 }
318 strip(buffer); 334 strip(buffer);
@@ -334,7 +350,8 @@ int main(int argc, char **argv) {
334 result = STATE_OK; 350 result = STATE_OK;
335 } else if (excode == REG_NOMATCH) { 351 } else if (excode == REG_NOMATCH) {
336 result = STATE_WARNING; 352 result = STATE_WARNING;
337 printf(_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text(result), buffer, config.commands[counter]); 353 printf(_("SMTP %s - Invalid response '%s' to command '%s'\n"),
354 state_text(result), buffer, config.commands[counter]);
338 } else { 355 } else {
339 regerror(excode, &preg, errbuf, MAX_INPUT_BUFFER); 356 regerror(excode, &preg, errbuf, MAX_INPUT_BUFFER);
340 printf(_("Execute Error: %s\n"), errbuf); 357 printf(_("Execute Error: %s\n"), errbuf);
@@ -361,12 +378,14 @@ int main(int argc, char **argv) {
361 } 378 }
362 379
363 /* send AUTH LOGIN */ 380 /* send AUTH LOGIN */
364 my_send(config, SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN), socket_descriptor, ssl_established); 381 my_send(config, SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN), socket_descriptor,
382 ssl_established);
365 if (verbose) { 383 if (verbose) {
366 printf(_("sent %s\n"), "AUTH LOGIN"); 384 printf(_("sent %s\n"), "AUTH LOGIN");
367 } 385 }
368 386
369 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established)) <= 0) { 387 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
388 ssl_established)) <= 0) {
370 xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, ")); 389 xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, "));
371 result = STATE_WARNING; 390 result = STATE_WARNING;
372 break; 391 break;
@@ -389,7 +408,8 @@ int main(int argc, char **argv) {
389 printf(_("sent %s\n"), abuf); 408 printf(_("sent %s\n"), abuf);
390 } 409 }
391 410
392 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established)) <= 0) { 411 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
412 ssl_established)) <= 0) {
393 result = STATE_CRITICAL; 413 result = STATE_CRITICAL;
394 xasprintf(&error_msg, _("recv() failed after sending authuser, ")); 414 xasprintf(&error_msg, _("recv() failed after sending authuser, "));
395 break; 415 break;
@@ -409,7 +429,8 @@ int main(int argc, char **argv) {
409 if (verbose) { 429 if (verbose) {
410 printf(_("sent %s\n"), abuf); 430 printf(_("sent %s\n"), abuf);
411 } 431 }
412 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established)) <= 0) { 432 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
433 ssl_established)) <= 0) {
413 result = STATE_CRITICAL; 434 result = STATE_CRITICAL;
414 xasprintf(&error_msg, _("recv() failed after sending authpass, ")); 435 xasprintf(&error_msg, _("recv() failed after sending authpass, "));
415 break; 436 break;
@@ -451,10 +472,10 @@ int main(int argc, char **argv) {
451 } 472 }
452 } 473 }
453 474
454 printf(_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"), state_text(result), error_msg, elapsed_time, verbose ? ", " : "", 475 printf(_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"), state_text(result), error_msg,
455 verbose ? buffer : "", 476 elapsed_time, verbose ? ", " : "", verbose ? buffer : "",
456 fperfdata("time", elapsed_time, "s", config.check_warning_time, config.warning_time, config.check_critical_time, 477 fperfdata("time", elapsed_time, "s", config.check_warning_time, config.warning_time,
457 config.critical_time, true, 0, false, 0)); 478 config.check_critical_time, config.critical_time, true, 0, false, 0));
458 479
459 exit(result); 480 exit(result);
460} 481}
@@ -519,7 +540,8 @@ check_smtp_config_wrapper process_arguments(int argc, char **argv) {
519 bool implicit_tls = false; 540 bool implicit_tls = false;
520 int server_port_option = 0; 541 int server_port_option = 0;
521 while (true) { 542 while (true) {
522 int opt_index = getopt_long(argc, argv, "+hVv46Lrt:p:f:e:c:w:H:C:R:sSD:F:A:U:P:q", longopts, &option); 543 int opt_index =
544 getopt_long(argc, argv, "+hVv46Lrt:p:f:e:c:w:H:C:R:sSD:F:A:U:P:q", longopts, &option);
523 545
524 if (opt_index == -1 || opt_index == EOF) { 546 if (opt_index == -1 || opt_index == EOF) {
525 break; 547 break;
@@ -546,7 +568,8 @@ check_smtp_config_wrapper process_arguments(int argc, char **argv) {
546 break; 568 break;
547 case 'f': /* from argument */ 569 case 'f': /* from argument */
548 result.config.from_arg = optarg + strspn(optarg, "<"); 570 result.config.from_arg = optarg + strspn(optarg, "<");
549 result.config.from_arg = strndup(result.config.from_arg, strcspn(result.config.from_arg, ">")); 571 result.config.from_arg =
572 strndup(result.config.from_arg, strcspn(result.config.from_arg, ">"));
550 result.config.send_mail_from = true; 573 result.config.send_mail_from = true;
551 break; 574 break;
552 case 'A': 575 case 'A':
@@ -565,9 +588,11 @@ check_smtp_config_wrapper process_arguments(int argc, char **argv) {
565 case 'C': /* commands */ 588 case 'C': /* commands */
566 if (result.config.ncommands >= command_size) { 589 if (result.config.ncommands >= command_size) {
567 command_size += 8; 590 command_size += 8;
568 result.config.commands = realloc(result.config.commands, sizeof(char *) * command_size); 591 result.config.commands =
592 realloc(result.config.commands, sizeof(char *) * command_size);
569 if (result.config.commands == NULL) { 593 if (result.config.commands == NULL) {
570 die(STATE_UNKNOWN, _("Could not realloc() units [%d]\n"), result.config.ncommands); 594 die(STATE_UNKNOWN, _("Could not realloc() units [%d]\n"),
595 result.config.ncommands);
571 } 596 }
572 } 597 }
573 result.config.commands[result.config.ncommands] = (char *)malloc(sizeof(char) * 255); 598 result.config.commands[result.config.ncommands] = (char *)malloc(sizeof(char) * 255);
@@ -577,9 +602,11 @@ check_smtp_config_wrapper process_arguments(int argc, char **argv) {
577 case 'R': /* server responses */ 602 case 'R': /* server responses */
578 if (result.config.nresponses >= response_size) { 603 if (result.config.nresponses >= response_size) {
579 response_size += 8; 604 response_size += 8;
580 result.config.responses = realloc(result.config.responses, sizeof(char *) * response_size); 605 result.config.responses =
606 realloc(result.config.responses, sizeof(char *) * response_size);
581 if (result.config.responses == NULL) { 607 if (result.config.responses == NULL) {
582 die(STATE_UNKNOWN, _("Could not realloc() units [%d]\n"), result.config.nresponses); 608 die(STATE_UNKNOWN, _("Could not realloc() units [%d]\n"),
609 result.config.nresponses);
583 } 610 }
584 } 611 }
585 result.config.responses[result.config.nresponses] = (char *)malloc(sizeof(char) * 255); 612 result.config.responses[result.config.nresponses] = (char *)malloc(sizeof(char) * 255);
@@ -718,8 +745,10 @@ check_smtp_config_wrapper process_arguments(int argc, char **argv) {
718 return result; 745 return result;
719} 746}
720 747
721char *smtp_quit(check_smtp_config config, char buffer[MAX_INPUT_BUFFER], int socket_descriptor, bool ssl_established) { 748char *smtp_quit(check_smtp_config config, char buffer[MAX_INPUT_BUFFER], int socket_descriptor,
722 int sent_bytes = my_send(config, SMTP_QUIT, strlen(SMTP_QUIT), socket_descriptor, ssl_established); 749 bool ssl_established) {
750 int sent_bytes =
751 my_send(config, SMTP_QUIT, strlen(SMTP_QUIT), socket_descriptor, ssl_established);
723 if (sent_bytes < 0) { 752 if (sent_bytes < 0) {
724 if (config.ignore_send_quit_failure) { 753 if (config.ignore_send_quit_failure) {
725 if (verbose) { 754 if (verbose) {
@@ -759,7 +788,8 @@ char *smtp_quit(check_smtp_config config, char buffer[MAX_INPUT_BUFFER], int soc
759 * function which buffers the data, move that to netutils.c and change 788 * function which buffers the data, move that to netutils.c and change
760 * check_smtp and other plugins to use that. Also, remove (\r)\n. 789 * check_smtp and other plugins to use that. Also, remove (\r)\n.
761 */ 790 */
762int recvline(char *buf, size_t bufsize, check_smtp_config config, int socket_descriptor, bool ssl_established) { 791int recvline(char *buf, size_t bufsize, check_smtp_config config, int socket_descriptor,
792 bool ssl_established) {
763 int result; 793 int result;
764 int counter; 794 int counter;
765 795
@@ -789,13 +819,16 @@ int recvline(char *buf, size_t bufsize, check_smtp_config config, int socket_des
789 * 819 *
790 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n. 820 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
791 */ 821 */
792int recvlines(check_smtp_config config, char *buf, size_t bufsize, int socket_descriptor, bool ssl_established) { 822int recvlines(check_smtp_config config, char *buf, size_t bufsize, int socket_descriptor,
823 bool ssl_established) {
793 int result; 824 int result;
794 int counter; 825 int counter;
795 826
796 for (counter = 0; /* forever */; counter += result) { 827 for (counter = 0; /* forever */; counter += result) {
797 if (!((result = recvline(buf + counter, bufsize - counter, config, socket_descriptor, ssl_established)) > 3 && 828 if (!((result = recvline(buf + counter, bufsize - counter, config, socket_descriptor,
798 isdigit((int)buf[counter]) && isdigit((int)buf[counter + 1]) && isdigit((int)buf[counter + 2]) && buf[counter + 3] == '-')) { 829 ssl_established)) > 3 &&
830 isdigit((int)buf[counter]) && isdigit((int)buf[counter + 1]) &&
831 isdigit((int)buf[counter + 2]) && buf[counter + 3] == '-')) {
799 break; 832 break;
800 } 833 }
801 } 834 }
@@ -835,13 +868,15 @@ void print_help(void) {
835 printf(UT_IPv46); 868 printf(UT_IPv46);
836 869
837 printf(" %s\n", "-e, --expect=STRING"); 870 printf(" %s\n", "-e, --expect=STRING");
838 printf(_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT); 871 printf(_(" String to expect in first line of server response (default: '%s')\n"),
872 SMTP_EXPECT);
839 printf(" %s\n", "-C, --command=STRING"); 873 printf(" %s\n", "-C, --command=STRING");
840 printf(" %s\n", _("SMTP command (may be used repeatedly)")); 874 printf(" %s\n", _("SMTP command (may be used repeatedly)"));
841 printf(" %s\n", "-R, --response=STRING"); 875 printf(" %s\n", "-R, --response=STRING");
842 printf(" %s\n", _("Expected response to command (may be used repeatedly)")); 876 printf(" %s\n", _("Expected response to command (may be used repeatedly)"));
843 printf(" %s\n", "-f, --from=STRING"); 877 printf(" %s\n", "-f, --from=STRING");
844 printf(" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")), printf(" %s\n", "-F, --fqdn=STRING"); 878 printf(" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
879 printf(" %s\n", "-F, --fqdn=STRING");
845 printf(" %s\n", _("FQDN used for HELO")); 880 printf(" %s\n", _("FQDN used for HELO"));
846 printf(" %s\n", "-r, --proxy"); 881 printf(" %s\n", "-r, --proxy");
847 printf(" %s\n", _("Use PROXY protocol prefix for the connection.")); 882 printf(" %s\n", _("Use PROXY protocol prefix for the connection."));
@@ -885,7 +920,9 @@ void print_help(void) {
885 920
886void print_usage(void) { 921void print_usage(void) {
887 printf("%s\n", _("Usage:")); 922 printf("%s\n", _("Usage:"));
888 printf("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n", progname); 923 printf("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n",
924 progname);
889 printf("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n"); 925 printf("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
890 printf("[-F fqdn] [-S] [-L] [-D warn days cert expire[,crit days cert expire]] [-r] [--sni] [-v] \n"); 926 printf("[-F fqdn] [-S] [-L] [-D warn days cert expire[,crit days cert expire]] [-r] [--sni] "
927 "[-v] \n");
891} 928}
diff --git a/plugins/check_swap.c b/plugins/check_swap.c
index 435a104e..dbf53a00 100644
--- a/plugins/check_swap.c
+++ b/plugins/check_swap.c
@@ -172,7 +172,8 @@ int main(int argc, char **argv) {
172 } 172 }
173 173
174 if (config.warn_is_set) { 174 if (config.warn_is_set) {
175 if ((config.warn.is_percentage && (percent_used >= (100 - (double)config.warn.value))) || config.warn.value >= data.metrics.free) { 175 if ((config.warn.is_percentage && (percent_used >= (100 - (double)config.warn.value))) ||
176 config.warn.value >= data.metrics.free) {
176 sc1 = mp_set_subcheck_state(sc1, STATE_WARNING); 177 sc1 = mp_set_subcheck_state(sc1, STATE_WARNING);
177 } 178 }
178 } 179 }
@@ -182,13 +183,14 @@ int main(int argc, char **argv) {
182 } 183 }
183 184
184 if (config.crit_is_set) { 185 if (config.crit_is_set) {
185 if ((config.crit.is_percentage && (percent_used >= (100 - (double)config.crit.value))) || config.crit.value >= data.metrics.free) { 186 if ((config.crit.is_percentage && (percent_used >= (100 - (double)config.crit.value))) ||
187 config.crit.value >= data.metrics.free) {
186 sc1 = mp_set_subcheck_state(sc1, STATE_CRITICAL); 188 sc1 = mp_set_subcheck_state(sc1, STATE_CRITICAL);
187 } 189 }
188 } 190 }
189 191
190 xasprintf(&sc1.output, _("%g%% free (%lluMiB out of %lluMiB)"), (100 - percent_used), data.metrics.free >> 20, 192 xasprintf(&sc1.output, _("%g%% free (%lluMiB out of %lluMiB)"), (100 - percent_used),
191 data.metrics.total >> 20); 193 data.metrics.free >> 20, data.metrics.total >> 20);
192 194
193 overall.summary = "Swap"; 195 overall.summary = "Swap";
194 mp_add_subcheck_to_check(&overall, sc1); 196 mp_add_subcheck_to_check(&overall, sc1);
@@ -201,7 +203,9 @@ int check_swap(float free_swap_mb, float total_swap_mb, swap_config config) {
201 return config.no_swap_state; 203 return config.no_swap_state;
202 } 204 }
203 205
204 uint64_t free_swap = (uint64_t)(free_swap_mb * (1024 * 1024)); /* Convert back to bytes as warn and crit specified in bytes */ 206 uint64_t free_swap =
207 (uint64_t)(free_swap_mb *
208 (1024 * 1024)); /* Convert back to bytes as warn and crit specified in bytes */
205 209
206 if (!config.crit.is_percentage && config.crit.value >= free_swap) { 210 if (!config.crit.is_percentage && config.crit.value >= free_swap) {
207 return STATE_CRITICAL; 211 return STATE_CRITICAL;
@@ -210,13 +214,16 @@ int check_swap(float free_swap_mb, float total_swap_mb, swap_config config) {
210 return STATE_WARNING; 214 return STATE_WARNING;
211 } 215 }
212 216
213 uint64_t usage_percentage = (uint64_t)((total_swap_mb - free_swap_mb) / total_swap_mb) * HUNDRED_PERCENT; 217 uint64_t usage_percentage =
218 (uint64_t)((total_swap_mb - free_swap_mb) / total_swap_mb) * HUNDRED_PERCENT;
214 219
215 if (config.crit.is_percentage && config.crit.value != 0 && usage_percentage >= (HUNDRED_PERCENT - config.crit.value)) { 220 if (config.crit.is_percentage && config.crit.value != 0 &&
221 usage_percentage >= (HUNDRED_PERCENT - config.crit.value)) {
216 return STATE_CRITICAL; 222 return STATE_CRITICAL;
217 } 223 }
218 224
219 if (config.warn.is_percentage && config.warn.value != 0 && usage_percentage >= (HUNDRED_PERCENT - config.warn.value)) { 225 if (config.warn.is_percentage && config.warn.value != 0 &&
226 usage_percentage >= (HUNDRED_PERCENT - config.warn.value)) {
220 return STATE_WARNING; 227 return STATE_WARNING;
221 } 228 }
222 229
diff --git a/plugins/check_swap.d/check_swap.h b/plugins/check_swap.d/check_swap.h
index da08d65a..8d3c7fcf 100644
--- a/plugins/check_swap.d/check_swap.h
+++ b/plugins/check_swap.d/check_swap.h
@@ -43,6 +43,7 @@ swap_config swap_config_init(void);
43 43
44swap_result get_swap_data(swap_config config); 44swap_result get_swap_data(swap_config config);
45swap_result getSwapFromProcMeminfo(char path_to_proc_meminfo[]); 45swap_result getSwapFromProcMeminfo(char path_to_proc_meminfo[]);
46swap_result getSwapFromSwapCommand(swap_config config, const char swap_command[], const char swap_format[]); 46swap_result getSwapFromSwapCommand(swap_config config, const char swap_command[],
47 const char swap_format[]);
47swap_result getSwapFromSwapctl_BSD(swap_config config); 48swap_result getSwapFromSwapctl_BSD(swap_config config);
48swap_result getSwapFromSwap_SRV4(swap_config config); 49swap_result getSwapFromSwap_SRV4(swap_config config);
diff --git a/plugins/check_swap.d/swap.c b/plugins/check_swap.d/swap.c
index 634f80d9..5b654197 100644
--- a/plugins/check_swap.d/swap.c
+++ b/plugins/check_swap.d/swap.c
@@ -95,12 +95,14 @@ swap_result getSwapFromProcMeminfo(char proc_meminfo[]) {
95 * 123 123" which exists on NetBSD (at least), 95 * 123 123" which exists on NetBSD (at least),
96 * The unit should be Bytes 96 * The unit should be Bytes
97 */ 97 */
98 if (sscanf(input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %lu %lu %lu", &swap_total, &swap_used, &swap_free) == 3) { 98 if (sscanf(input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %lu %lu %lu", &swap_total, &swap_used,
99 &swap_free) == 3) {
99 found_total = true; 100 found_total = true;
100 found_free = true; 101 found_free = true;
101 // Set error 102 // Set error
102 result.errorcode = STATE_OK; 103 result.errorcode = STATE_OK;
103 // Break out of fgets here, since both scanf expressions might match (NetBSD for example) 104 // Break out of fgets here, since both scanf expressions might match (NetBSD for
105 // example)
104 break; 106 break;
105 } 107 }
106 108
@@ -149,7 +151,8 @@ swap_result getSwapFromProcMeminfo(char proc_meminfo[]) {
149 return result; 151 return result;
150} 152}
151 153
152swap_result getSwapFromSwapCommand(swap_config config, const char swap_command[], const char swap_format[]) { 154swap_result getSwapFromSwapCommand(swap_config config, const char swap_command[],
155 const char swap_format[]) {
153 swap_result result = {0}; 156 swap_result result = {0};
154 157
155 char *temp_buffer; 158 char *temp_buffer;
@@ -212,7 +215,8 @@ swap_result getSwapFromSwapCommand(swap_config config, const char swap_command[]
212 used_swap_mb = total_swap_mb - free_swap_mb; 215 used_swap_mb = total_swap_mb - free_swap_mb;
213 216
214 if (verbose >= 3) { 217 if (verbose >= 3) {
215 printf(_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap_mb, used_swap_mb, free_swap_mb); 218 printf(_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap_mb, used_swap_mb,
219 free_swap_mb);
216 } 220 }
217 } else { 221 } else {
218 while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) { 222 while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
@@ -398,7 +402,8 @@ swap_result getSwapFromSwap_SRV4(swap_config config) {
398 } 402 }
399 403
400 /* initialize swap table + entries */ 404 /* initialize swap table + entries */
401 swaptbl_t *tbl = (swaptbl_t *)malloc(sizeof(swaptbl_t) + (sizeof(swapent_t) * (unsigned long)nswaps)); 405 swaptbl_t *tbl =
406 (swaptbl_t *)malloc(sizeof(swaptbl_t) + (sizeof(swapent_t) * (unsigned long)nswaps));
402 407
403 if (tbl == NULL) { 408 if (tbl == NULL) {
404 die(STATE_UNKNOWN, _("malloc() failed!\n")); 409 die(STATE_UNKNOWN, _("malloc() failed!\n"));
@@ -433,7 +438,8 @@ swap_result getSwapFromSwap_SRV4(swap_config config) {
433 dskused_mb = (dsktotal_mb - dskfree_mb); 438 dskused_mb = (dsktotal_mb - dskfree_mb);
434 439
435 if (verbose >= 3) { 440 if (verbose >= 3) {
436 printf("dsktotal_mb=%.0f dskfree_mb=%.0f dskused_mb=%.0f\n", dsktotal_mb, dskfree_mb, dskused_mb); 441 printf("dsktotal_mb=%.0f dskfree_mb=%.0f dskused_mb=%.0f\n", dsktotal_mb, dskfree_mb,
442 dskused_mb);
437 } 443 }
438 444
439 if (config.allswaps && dsktotal_mb > 0) { 445 if (config.allswaps && dsktotal_mb > 0) {
diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c
index 22dcc74e..09806373 100644
--- a/plugins/check_tcp.c
+++ b/plugins/check_tcp.c
@@ -65,7 +65,8 @@ typedef struct {
65 int errorcode; 65 int errorcode;
66 check_tcp_config config; 66 check_tcp_config config;
67} check_tcp_config_wrapper; 67} check_tcp_config_wrapper;
68static check_tcp_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/, check_tcp_config /*config*/); 68static check_tcp_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/,
69 check_tcp_config /*config*/);
69void print_help(const char *service); 70void print_help(const char *service);
70void print_usage(void); 71void print_usage(void);
71 72
@@ -137,7 +138,8 @@ int main(int argc, char **argv) {
137 config.server_expect[0] = "220"; 138 config.server_expect[0] = "220";
138 config.quit = "QUIT\r\n"; 139 config.quit = "QUIT\r\n";
139 config.server_port = DEFAULT_FTP_PORT; 140 config.server_port = DEFAULT_FTP_PORT;
140 } else if (!strncmp(config.service, "POP", strlen("POP")) || !strncmp(config.service, "POP3", strlen("POP3"))) { 141 } else if (!strncmp(config.service, "POP", strlen("POP")) ||
142 !strncmp(config.service, "POP3", strlen("POP3"))) {
141 config.server_expect[0] = "+OK"; 143 config.server_expect[0] = "+OK";
142 config.quit = "QUIT\r\n"; 144 config.quit = "QUIT\r\n";
143 config.server_port = DEFAULT_POP_PORT; 145 config.server_port = DEFAULT_POP_PORT;
@@ -167,7 +169,8 @@ int main(int argc, char **argv) {
167 config.use_tls = true; 169 config.use_tls = true;
168 config.server_port = DEFAULT_SSMTP_PORT; 170 config.server_port = DEFAULT_SSMTP_PORT;
169 } else if (!strncmp(config.service, "JABBER", strlen("JABBER"))) { 171 } else if (!strncmp(config.service, "JABBER", strlen("JABBER"))) {
170 config.send = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n"; 172 config.send = "<stream:stream to=\'host\' xmlns=\'jabber:client\' "
173 "xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
171 config.server_expect[0] = "<?xml version=\'1.0\'"; 174 config.server_expect[0] = "<?xml version=\'1.0\'";
172 config.quit = "</stream:stream>\n"; 175 config.quit = "</stream:stream>\n";
173 config.hide_output = true; 176 config.hide_output = true;
@@ -246,46 +249,58 @@ int main(int argc, char **argv) {
246 mp_subcheck inital_connect_result = mp_subcheck_init(); 249 mp_subcheck inital_connect_result = mp_subcheck_init();
247 250
248 // Try initial connection 251 // Try initial connection
249 if (np_net_connect(config.server_address, config.server_port, &socket_descriptor, config.protocol) == STATE_CRITICAL) { 252 if (np_net_connect(config.server_address, config.server_port, &socket_descriptor,
253 config.protocol) == STATE_CRITICAL) {
250 // Early exit here, we got connection refused 254 // Early exit here, we got connection refused
251 inital_connect_result = mp_set_subcheck_state(inital_connect_result, config.econn_refuse_state); 255 inital_connect_result =
252 xasprintf(&inital_connect_result.output, "Connection to %s on port %i was REFUSED", config.server_address, config.server_port); 256 mp_set_subcheck_state(inital_connect_result, config.econn_refuse_state);
257 xasprintf(&inital_connect_result.output, "Connection to %s on port %i was REFUSED",
258 config.server_address, config.server_port);
253 mp_add_subcheck_to_check(&overall, inital_connect_result); 259 mp_add_subcheck_to_check(&overall, inital_connect_result);
254 mp_exit(overall); 260 mp_exit(overall);
255 } else { 261 } else {
256 inital_connect_result = mp_set_subcheck_state(inital_connect_result, STATE_OK); 262 inital_connect_result = mp_set_subcheck_state(inital_connect_result, STATE_OK);
257 xasprintf(&inital_connect_result.output, "Connection to %s on port %i was a SUCCESS", config.server_address, config.server_port); 263 xasprintf(&inital_connect_result.output, "Connection to %s on port %i was a SUCCESS",
264 config.server_address, config.server_port);
258 mp_add_subcheck_to_check(&overall, inital_connect_result); 265 mp_add_subcheck_to_check(&overall, inital_connect_result);
259 } 266 }
260 267
261#ifdef HAVE_SSL 268#ifdef HAVE_SSL
262 if (config.use_tls) { 269 if (config.use_tls) {
263 mp_subcheck tls_connection_result = mp_subcheck_init(); 270 mp_subcheck tls_connection_result = mp_subcheck_init();
264 mp_state_enum result = np_net_ssl_init_with_hostname(socket_descriptor, (config.sni_specified ? config.sni : NULL)); 271 mp_state_enum result = np_net_ssl_init_with_hostname(
272 socket_descriptor, (config.sni_specified ? config.sni : NULL));
265 tls_connection_result = mp_set_subcheck_default_state(tls_connection_result, result); 273 tls_connection_result = mp_set_subcheck_default_state(tls_connection_result, result);
266 274
267 if (result == STATE_OK) { 275 if (result == STATE_OK) {
268 xasprintf(&tls_connection_result.output, "TLS connection succeeded"); 276 xasprintf(&tls_connection_result.output, "TLS connection succeeded");
269 277
270 if (config.check_cert) { 278 if (config.check_cert) {
271 result = np_net_ssl_check_cert(config.days_till_exp_warn, config.days_till_exp_crit); 279 result =
280 np_net_ssl_check_cert(config.days_till_exp_warn, config.days_till_exp_crit);
272 281
273 mp_subcheck tls_certificate_lifetime_result = mp_subcheck_init(); 282 mp_subcheck tls_certificate_lifetime_result = mp_subcheck_init();
274 tls_certificate_lifetime_result = mp_set_subcheck_state(tls_certificate_lifetime_result, result); 283 tls_certificate_lifetime_result =
284 mp_set_subcheck_state(tls_certificate_lifetime_result, result);
275 285
276 if (result == STATE_OK) { 286 if (result == STATE_OK) {
277 xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is within thresholds"); 287 xasprintf(&tls_certificate_lifetime_result.output,
288 "Certificate lifetime is within thresholds");
278 } else if (result == STATE_WARNING) { 289 } else if (result == STATE_WARNING) {
279 xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is violating warning threshold (%i)", 290 xasprintf(&tls_certificate_lifetime_result.output,
291 "Certificate lifetime is violating warning threshold (%i)",
280 config.days_till_exp_warn); 292 config.days_till_exp_warn);
281 } else if (result == STATE_CRITICAL) { 293 } else if (result == STATE_CRITICAL) {
282 xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is violating critical threshold (%i)", 294 xasprintf(&tls_certificate_lifetime_result.output,
295 "Certificate lifetime is violating critical threshold (%i)",
283 config.days_till_exp_crit); 296 config.days_till_exp_crit);
284 } else { 297 } else {
285 xasprintf(&tls_certificate_lifetime_result.output, "Certificate lifetime is somehow unknown"); 298 xasprintf(&tls_certificate_lifetime_result.output,
299 "Certificate lifetime is somehow unknown");
286 } 300 }
287 301
288 mp_add_subcheck_to_subcheck(&tls_connection_result, tls_certificate_lifetime_result); 302 mp_add_subcheck_to_subcheck(&tls_connection_result,
303 tls_certificate_lifetime_result);
289 } 304 }
290 305
291 mp_add_subcheck_to_check(&overall, tls_connection_result); 306 mp_add_subcheck_to_check(&overall, tls_connection_result);
@@ -336,7 +351,8 @@ int main(int argc, char **argv) {
336 char buffer[MAXBUF]; 351 char buffer[MAXBUF];
337 352
338 /* watch for the expect string */ 353 /* watch for the expect string */
339 while ((received = my_recv(socket_descriptor, buffer, sizeof(buffer), config.use_tls)) > 0) { 354 while ((received = my_recv(socket_descriptor, buffer, sizeof(buffer), config.use_tls)) >
355 0) {
340 received_buffer = realloc(received_buffer, len + received + 1); 356 received_buffer = realloc(received_buffer, len + received + 1);
341 357
342 if (received_buffer == NULL) { 358 if (received_buffer == NULL) {
@@ -352,7 +368,8 @@ int main(int argc, char **argv) {
352 break; 368 break;
353 } 369 }
354 370
355 if ((match = np_expect_match(received_buffer, config.server_expect, config.server_expect_count, config.match_flags)) != 371 if ((match = np_expect_match(received_buffer, config.server_expect,
372 config.server_expect_count, config.match_flags)) !=
356 NP_MATCH_RETRY) { 373 NP_MATCH_RETRY) {
357 break; 374 break;
358 } 375 }
@@ -385,7 +402,8 @@ int main(int argc, char **argv) {
385 402
386 /* print raw output if we're debugging */ 403 /* print raw output if we're debugging */
387 if (verbosity > 0) { 404 if (verbosity > 0) {
388 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len + 1, received_buffer); 405 printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
406 (int)len + 1, received_buffer);
389 } 407 }
390 /* strip whitespace from end of output */ 408 /* strip whitespace from end of output */
391 while (--len > 0 && isspace(received_buffer[len])) { 409 while (--len > 0 && isspace(received_buffer[len])) {
@@ -415,7 +433,9 @@ int main(int argc, char **argv) {
415 time_pd.uom = "s"; 433 time_pd.uom = "s";
416 434
417 if (config.critical_time_set && elapsed_time > config.critical_time) { 435 if (config.critical_time_set && elapsed_time > config.critical_time) {
418 xasprintf(&elapsed_time_result.output, "Connection time %fs exceeded critical threshold (%f)", elapsed_time, config.critical_time); 436 xasprintf(&elapsed_time_result.output,
437 "Connection time %fs exceeded critical threshold (%f)", elapsed_time,
438 config.critical_time);
419 439
420 elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_CRITICAL); 440 elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_CRITICAL);
421 time_pd.crit_present = true; 441 time_pd.crit_present = true;
@@ -426,7 +446,9 @@ int main(int argc, char **argv) {
426 446
427 time_pd.crit = crit_val; 447 time_pd.crit = crit_val;
428 } else if (config.warning_time_set && elapsed_time > config.warning_time) { 448 } else if (config.warning_time_set && elapsed_time > config.warning_time) {
429 xasprintf(&elapsed_time_result.output, "Connection time %fs exceeded warning threshold (%f)", elapsed_time, config.critical_time); 449 xasprintf(&elapsed_time_result.output,
450 "Connection time %fs exceeded warning threshold (%f)", elapsed_time,
451 config.critical_time);
430 452
431 elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_WARNING); 453 elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_WARNING);
432 time_pd.warn_present = true; 454 time_pd.warn_present = true;
@@ -437,7 +459,8 @@ int main(int argc, char **argv) {
437 time_pd.warn = warn_val; 459 time_pd.warn = warn_val;
438 } else { 460 } else {
439 elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_OK); 461 elapsed_time_result = mp_set_subcheck_state(elapsed_time_result, STATE_OK);
440 xasprintf(&elapsed_time_result.output, "Connection time %fs is within thresholds", elapsed_time); 462 xasprintf(&elapsed_time_result.output, "Connection time %fs is within thresholds",
463 elapsed_time);
441 } 464 }
442 465
443 mp_add_perfdata_to_subcheck(&elapsed_time_result, time_pd); 466 mp_add_perfdata_to_subcheck(&elapsed_time_result, time_pd);
@@ -445,7 +468,8 @@ int main(int argc, char **argv) {
445 468
446 /* did we get the response we hoped? */ 469 /* did we get the response we hoped? */
447 if (match == NP_MATCH_FAILURE) { 470 if (match == NP_MATCH_FAILURE) {
448 expected_data_result = mp_set_subcheck_state(expected_data_result, config.expect_mismatch_state); 471 expected_data_result =
472 mp_set_subcheck_state(expected_data_result, config.expect_mismatch_state);
449 xasprintf(&expected_data_result.output, "Answer failed to match expectation"); 473 xasprintf(&expected_data_result.output, "Answer failed to match expectation");
450 mp_add_subcheck_to_check(&overall, expected_data_result); 474 mp_add_subcheck_to_check(&overall, expected_data_result);
451 } else if (match == NP_MATCH_SUCCESS) { 475 } else if (match == NP_MATCH_SUCCESS) {
@@ -467,34 +491,35 @@ static check_tcp_config_wrapper process_arguments(int argc, char **argv, check_t
467 output_format_index, 491 output_format_index,
468 }; 492 };
469 493
470 static struct option longopts[] = {{"hostname", required_argument, 0, 'H'}, 494 static struct option longopts[] = {
471 {"critical", required_argument, 0, 'c'}, 495 {"hostname", required_argument, 0, 'H'},
472 {"warning", required_argument, 0, 'w'}, 496 {"critical", required_argument, 0, 'c'},
473 {"critical-codes", required_argument, 0, 'C'}, 497 {"warning", required_argument, 0, 'w'},
474 {"warning-codes", required_argument, 0, 'W'}, 498 {"critical-codes", required_argument, 0, 'C'},
475 {"timeout", required_argument, 0, 't'}, 499 {"warning-codes", required_argument, 0, 'W'},
476 {"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */ 500 {"timeout", required_argument, 0, 't'},
477 {"port", required_argument, 0, 'p'}, 501 {"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */
478 {"escape", no_argument, 0, 'E'}, 502 {"port", required_argument, 0, 'p'},
479 {"all", no_argument, 0, 'A'}, 503 {"escape", no_argument, 0, 'E'},
480 {"send", required_argument, 0, 's'}, 504 {"all", no_argument, 0, 'A'},
481 {"expect", required_argument, 0, 'e'}, 505 {"send", required_argument, 0, 's'},
482 {"maxbytes", required_argument, 0, 'm'}, 506 {"expect", required_argument, 0, 'e'},
483 {"quit", required_argument, 0, 'q'}, 507 {"maxbytes", required_argument, 0, 'm'},
484 {"jail", no_argument, 0, 'j'}, 508 {"quit", required_argument, 0, 'q'},
485 {"delay", required_argument, 0, 'd'}, 509 {"jail", no_argument, 0, 'j'},
486 {"refuse", required_argument, 0, 'r'}, 510 {"delay", required_argument, 0, 'd'},
487 {"mismatch", required_argument, 0, 'M'}, 511 {"refuse", required_argument, 0, 'r'},
488 {"use-ipv4", no_argument, 0, '4'}, 512 {"mismatch", required_argument, 0, 'M'},
489 {"use-ipv6", no_argument, 0, '6'}, 513 {"use-ipv4", no_argument, 0, '4'},
490 {"verbose", no_argument, 0, 'v'}, 514 {"use-ipv6", no_argument, 0, '6'},
491 {"version", no_argument, 0, 'V'}, 515 {"verbose", no_argument, 0, 'v'},
492 {"help", no_argument, 0, 'h'}, 516 {"version", no_argument, 0, 'V'},
493 {"ssl", no_argument, 0, 'S'}, 517 {"help", no_argument, 0, 'h'},
494 {"sni", required_argument, 0, SNI_OPTION}, 518 {"ssl", no_argument, 0, 'S'},
495 {"certificate", required_argument, 0, 'D'}, 519 {"sni", required_argument, 0, SNI_OPTION},
496 {"output-format", required_argument, 0, output_format_index}, 520 {"certificate", required_argument, 0, 'D'},
497 {0, 0, 0, 0}}; 521 {"output-format", required_argument, 0, output_format_index},
522 {0, 0, 0, 0}};
498 523
499 if (argc < 2) { 524 if (argc < 2) {
500 usage4(_("No arguments found")); 525 usage4(_("No arguments found"));
@@ -522,7 +547,8 @@ static check_tcp_config_wrapper process_arguments(int argc, char **argv, check_t
522 547
523 while (true) { 548 while (true) {
524 int option = 0; 549 int option = 0;
525 int option_index = getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option); 550 int option_index =
551 getopt_long(argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:", longopts, &option);
526 552
527 if (option_index == -1 || option_index == EOF || option_index == 1) { 553 if (option_index == -1 || option_index == EOF || option_index == 1) {
528 break; 554 break;
@@ -595,7 +621,8 @@ static check_tcp_config_wrapper process_arguments(int argc, char **argv, check_t
595 if (config.server_expect_count == 0) { 621 if (config.server_expect_count == 0) {
596 config.server_expect = malloc(sizeof(char *) * (++config.server_expect_count)); 622 config.server_expect = malloc(sizeof(char *) * (++config.server_expect_count));
597 } else { 623 } else {
598 config.server_expect = realloc(config.server_expect, sizeof(char *) * (++config.server_expect_count)); 624 config.server_expect =
625 realloc(config.server_expect, sizeof(char *) * (++config.server_expect_count));
599 } 626 }
600 627
601 if (config.server_expect == NULL) { 628 if (config.server_expect == NULL) {
@@ -718,8 +745,8 @@ static check_tcp_config_wrapper process_arguments(int argc, char **argv, check_t
718 if (config.server_address == NULL) { 745 if (config.server_address == NULL) {
719 usage4(_("You must provide a server address")); 746 usage4(_("You must provide a server address"));
720 } else if (config.server_address[0] != '/' && !is_host(config.server_address)) { 747 } else if (config.server_address[0] != '/' && !is_host(config.server_address)) {
721 die(STATE_CRITICAL, "%s %s - %s: %s\n", config.service, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), 748 die(STATE_CRITICAL, "%s %s - %s: %s\n", config.service, state_text(STATE_CRITICAL),
722 config.server_address); 749 _("Invalid hostname, address or socket"), config.server_address);
723 } 750 }
724 751
725 check_tcp_config_wrapper result = { 752 check_tcp_config_wrapper result = {
@@ -735,7 +762,8 @@ void print_help(const char *service) {
735 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"); 762 printf("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
736 printf(COPYRIGHT, copyright, email); 763 printf(COPYRIGHT, copyright, email);
737 764
738 printf(_("This plugin tests %s connections with the specified host (or unix socket).\n\n"), service); 765 printf(_("This plugin tests %s connections with the specified host (or unix socket).\n\n"),
766 service);
739 767
740 print_usage(); 768 print_usage();
741 769
@@ -747,7 +775,8 @@ void print_help(const char *service) {
747 printf(UT_IPv46); 775 printf(UT_IPv46);
748 776
749 printf(" %s\n", "-E, --escape"); 777 printf(" %s\n", "-E, --escape");
750 printf(" %s\n", _("Can use \\n, \\r, \\t or \\\\ in send or quit string. Must come before send or quit option")); 778 printf(" %s\n", _("Can use \\n, \\r, \\t or \\\\ in send or quit string. Must come before "
779 "send or quit option"));
751 printf(" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit")); 780 printf(" %s\n", _("Default: nothing added to send, \\r\\n added to end of quit"));
752 printf(" %s\n", "-s, --send=STRING"); 781 printf(" %s\n", "-s, --send=STRING");
753 printf(" %s\n", _("String to send to the server")); 782 printf(" %s\n", _("String to send to the server"));
@@ -760,7 +789,8 @@ void print_help(const char *service) {
760 printf(" %s\n", "-r, --refuse=ok|warn|crit"); 789 printf(" %s\n", "-r, --refuse=ok|warn|crit");
761 printf(" %s\n", _("Accept TCP refusals with states ok, warn, crit (default: crit)")); 790 printf(" %s\n", _("Accept TCP refusals with states ok, warn, crit (default: crit)"));
762 printf(" %s\n", "-M, --mismatch=ok|warn|crit"); 791 printf(" %s\n", "-M, --mismatch=ok|warn|crit");
763 printf(" %s\n", _("Accept expected string mismatches with states ok, warn, crit (default: warn)")); 792 printf(" %s\n",
793 _("Accept expected string mismatches with states ok, warn, crit (default: warn)"));
764 printf(" %s\n", "-j, --jail"); 794 printf(" %s\n", "-j, --jail");
765 printf(" %s\n", _("Hide output from TCP socket")); 795 printf(" %s\n", _("Hide output from TCP socket"));
766 printf(" %s\n", "-m, --maxbytes=INTEGER"); 796 printf(" %s\n", "-m, --maxbytes=INTEGER");
@@ -790,7 +820,8 @@ void print_help(const char *service) {
790 820
791void print_usage(void) { 821void print_usage(void) {
792 printf("%s\n", _("Usage:")); 822 printf("%s\n", _("Usage:"));
793 printf("%s -H host -p port [-w <warning time>] [-c <critical time>] [-s <send string>]\n", progname); 823 printf("%s -H host -p port [-w <warning time>] [-c <critical time>] [-s <send string>]\n",
824 progname);
794 printf("[-e <expect string>] [-q <quit string>][-m <maximum bytes>] [-d <delay>]\n"); 825 printf("[-e <expect string>] [-q <quit string>][-m <maximum bytes>] [-d <delay>]\n");
795 printf("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n"); 826 printf("[-t <timeout seconds>] [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n");
796 printf("[-D <warn days cert expire>[,<crit days cert expire>]] [-S <use SSL>] [-E]\n"); 827 printf("[-D <warn days cert expire>[,<crit days cert expire>]] [-S <use SSL>] [-E]\n");
diff --git a/plugins/check_time.c b/plugins/check_time.c
index debf59f3..fc9ba3f9 100644
--- a/plugins/check_time.c
+++ b/plugins/check_time.c
@@ -87,7 +87,8 @@ int main(int argc, char **argv) {
87 } else { 87 } else {
88 result = STATE_UNKNOWN; 88 result = STATE_UNKNOWN;
89 } 89 }
90 die(result, _("TIME UNKNOWN - could not connect to server %s, port %d\n"), config.server_address, config.server_port); 90 die(result, _("TIME UNKNOWN - could not connect to server %s, port %d\n"),
91 config.server_address, config.server_port);
91 } 92 }
92 93
93 if (config.use_udp) { 94 if (config.use_udp) {
@@ -99,7 +100,8 @@ int main(int argc, char **argv) {
99 } else { 100 } else {
100 result = STATE_UNKNOWN; 101 result = STATE_UNKNOWN;
101 } 102 }
102 die(result, _("TIME UNKNOWN - could not send UDP request to server %s, port %d\n"), config.server_address, config.server_port); 103 die(result, _("TIME UNKNOWN - could not send UDP request to server %s, port %d\n"),
104 config.server_address, config.server_port);
103 } 105 }
104 } 106 }
105 107
@@ -123,7 +125,8 @@ int main(int argc, char **argv) {
123 } else { 125 } else {
124 result = STATE_UNKNOWN; 126 result = STATE_UNKNOWN;
125 } 127 }
126 die(result, _("TIME UNKNOWN - no data received from server %s, port %d\n"), config.server_address, config.server_port); 128 die(result, _("TIME UNKNOWN - no data received from server %s, port %d\n"),
129 config.server_address, config.server_port);
127 } 130 }
128 131
129 result = STATE_OK; 132 result = STATE_OK;
@@ -137,7 +140,8 @@ int main(int argc, char **argv) {
137 140
138 if (result != STATE_OK) { 141 if (result != STATE_OK) {
139 die(result, _("TIME %s - %d second response time|%s\n"), state_text(result), (int)conntime, 142 die(result, _("TIME %s - %d second response time|%s\n"), state_text(result), (int)conntime,
140 perfdata("time", (long)conntime, "s", config.check_warning_time, (long)config.warning_time, config.check_critical_time, 143 perfdata("time", (long)conntime, "s", config.check_warning_time,
144 (long)config.warning_time, config.check_critical_time,
141 (long)config.critical_time, true, 0, false, 0)); 145 (long)config.critical_time, true, 0, false, 0));
142 } 146 }
143 147
@@ -157,10 +161,11 @@ int main(int argc, char **argv) {
157 } 161 }
158 162
159 printf(_("TIME %s - %lu second time difference|%s %s\n"), state_text(result), diff_time, 163 printf(_("TIME %s - %lu second time difference|%s %s\n"), state_text(result), diff_time,
160 perfdata("time", (long)conntime, "s", config.check_warning_time, (long)config.warning_time, config.check_critical_time, 164 perfdata("time", (long)conntime, "s", config.check_warning_time,
165 (long)config.warning_time, config.check_critical_time,
161 (long)config.critical_time, true, 0, false, 0), 166 (long)config.critical_time, true, 0, false, 0),
162 perfdata("offset", diff_time, "s", config.check_warning_diff, config.warning_diff, config.check_critical_diff, 167 perfdata("offset", diff_time, "s", config.check_warning_diff, config.warning_diff,
163 config.critical_diff, true, 0, false, 0)); 168 config.check_critical_diff, config.critical_diff, true, 0, false, 0));
164 return result; 169 return result;
165} 170}
166 171
@@ -230,7 +235,8 @@ check_time_config_wrapper process_arguments(int argc, char **argv) {
230 result.config.warning_diff = strtoul(optarg, NULL, 10); 235 result.config.warning_diff = strtoul(optarg, NULL, 10);
231 result.config.check_warning_diff = true; 236 result.config.check_warning_diff = true;
232 } else if (strspn(optarg, "0123456789:,") > 0) { 237 } else if (strspn(optarg, "0123456789:,") > 0) {
233 if (sscanf(optarg, "%lu%*[:,]%d", &result.config.warning_diff, &result.config.warning_time) == 2) { 238 if (sscanf(optarg, "%lu%*[:,]%d", &result.config.warning_diff,
239 &result.config.warning_time) == 2) {
234 result.config.check_warning_diff = true; 240 result.config.check_warning_diff = true;
235 result.config.check_warning_time = true; 241 result.config.check_warning_time = true;
236 } else { 242 } else {
@@ -245,7 +251,8 @@ check_time_config_wrapper process_arguments(int argc, char **argv) {
245 result.config.critical_diff = strtoul(optarg, NULL, 10); 251 result.config.critical_diff = strtoul(optarg, NULL, 10);
246 result.config.check_critical_diff = true; 252 result.config.check_critical_diff = true;
247 } else if (strspn(optarg, "0123456789:,") > 0) { 253 } else if (strspn(optarg, "0123456789:,") > 0) {
248 if (sscanf(optarg, "%lu%*[:,]%d", &result.config.critical_diff, &result.config.critical_time) == 2) { 254 if (sscanf(optarg, "%lu%*[:,]%d", &result.config.critical_diff,
255 &result.config.critical_time) == 2) {
249 result.config.check_critical_diff = true; 256 result.config.check_critical_diff = true;
250 result.config.check_critical_time = true; 257 result.config.check_critical_time = true;
251 } else { 258 } else {
diff --git a/plugins/check_ups.c b/plugins/check_ups.c
index ecc0760f..54decce3 100644
--- a/plugins/check_ups.c
+++ b/plugins/check_ups.c
@@ -106,7 +106,8 @@ int main(int argc, char **argv) {
106 if (ups_status_flags & UPSSTATUS_OFF) { 106 if (ups_status_flags & UPSSTATUS_OFF) {
107 xasprintf(&ups_status, "Off"); 107 xasprintf(&ups_status, "Off");
108 result = STATE_CRITICAL; 108 result = STATE_CRITICAL;
109 } else if ((ups_status_flags & (UPSSTATUS_OB | UPSSTATUS_LB)) == (UPSSTATUS_OB | UPSSTATUS_LB)) { 109 } else if ((ups_status_flags & (UPSSTATUS_OB | UPSSTATUS_LB)) ==
110 (UPSSTATUS_OB | UPSSTATUS_LB)) {
110 xasprintf(&ups_status, _("On Battery, Low Battery")); 111 xasprintf(&ups_status, _("On Battery, Low Battery"));
111 result = STATE_CRITICAL; 112 result = STATE_CRITICAL;
112 } else { 113 } else {
@@ -192,11 +193,14 @@ int main(int argc, char **argv) {
192 result = max_state(result, STATE_WARNING); 193 result = max_state(result, STATE_WARNING);
193 } 194 }
194 xasprintf(&performance_data, "%s", 195 xasprintf(&performance_data, "%s",
195 perfdata("voltage", (long)(1000 * ups_utility_voltage), "mV", config.check_warn, (long)(1000 * config.warning_value), 196 perfdata("voltage", (long)(1000 * ups_utility_voltage), "mV",
196 config.check_crit, (long)(1000 * config.critical_value), true, 0, false, 0)); 197 config.check_warn, (long)(1000 * config.warning_value),
198 config.check_crit, (long)(1000 * config.critical_value), true, 0,
199 false, 0));
197 } else { 200 } else {
198 xasprintf(&performance_data, "%s", 201 xasprintf(&performance_data, "%s",
199 perfdata("voltage", (long)(1000 * ups_utility_voltage), "mV", false, 0, false, 0, true, 0, false, 0)); 202 perfdata("voltage", (long)(1000 * ups_utility_voltage), "mV", false, 0, false,
203 0, true, 0, false, 0));
200 } 204 }
201 } 205 }
202 206
@@ -220,11 +224,13 @@ int main(int argc, char **argv) {
220 result = max_state(result, STATE_WARNING); 224 result = max_state(result, STATE_WARNING);
221 } 225 }
222 xasprintf(&performance_data, "%s %s", performance_data, 226 xasprintf(&performance_data, "%s %s", performance_data,
223 perfdata("battery", (long)ups_battery_percent, "%", config.check_warn, (long)(config.warning_value), 227 perfdata("battery", (long)ups_battery_percent, "%", config.check_warn,
224 config.check_crit, (long)(config.critical_value), true, 0, true, 100)); 228 (long)(config.warning_value), config.check_crit,
229 (long)(config.critical_value), true, 0, true, 100));
225 } else { 230 } else {
226 xasprintf(&performance_data, "%s %s", performance_data, 231 xasprintf(&performance_data, "%s %s", performance_data,
227 perfdata("battery", (long)ups_battery_percent, "%", false, 0, false, 0, true, 0, true, 100)); 232 perfdata("battery", (long)ups_battery_percent, "%", false, 0, false, 0, true,
233 0, true, 100));
228 } 234 }
229 } 235 }
230 236
@@ -248,11 +254,13 @@ int main(int argc, char **argv) {
248 result = max_state(result, STATE_WARNING); 254 result = max_state(result, STATE_WARNING);
249 } 255 }
250 xasprintf(&performance_data, "%s %s", performance_data, 256 xasprintf(&performance_data, "%s %s", performance_data,
251 perfdata("load", (long)ups_load_percent, "%", config.check_warn, (long)(config.warning_value), config.check_crit, 257 perfdata("load", (long)ups_load_percent, "%", config.check_warn,
258 (long)(config.warning_value), config.check_crit,
252 (long)(config.critical_value), true, 0, true, 100)); 259 (long)(config.critical_value), true, 0, true, 100));
253 } else { 260 } else {
254 xasprintf(&performance_data, "%s %s", performance_data, 261 xasprintf(&performance_data, "%s %s", performance_data,
255 perfdata("load", (long)ups_load_percent, "%", false, 0, false, 0, true, 0, true, 100)); 262 perfdata("load", (long)ups_load_percent, "%", false, 0, false, 0, true, 0,
263 true, 100));
256 } 264 }
257 } 265 }
258 266
@@ -285,11 +293,13 @@ int main(int argc, char **argv) {
285 result = max_state(result, STATE_WARNING); 293 result = max_state(result, STATE_WARNING);
286 } 294 }
287 xasprintf(&performance_data, "%s %s", performance_data, 295 xasprintf(&performance_data, "%s %s", performance_data,
288 perfdata("temp", (long)ups_temperature, tunits, config.check_warn, (long)(config.warning_value), config.check_crit, 296 perfdata("temp", (long)ups_temperature, tunits, config.check_warn,
297 (long)(config.warning_value), config.check_crit,
289 (long)(config.critical_value), true, 0, false, 0)); 298 (long)(config.critical_value), true, 0, false, 0));
290 } else { 299 } else {
291 xasprintf(&performance_data, "%s %s", performance_data, 300 xasprintf(&performance_data, "%s %s", performance_data,
292 perfdata("temp", (long)ups_temperature, tunits, false, 0, false, 0, true, 0, false, 0)); 301 perfdata("temp", (long)ups_temperature, tunits, false, 0, false, 0, true, 0,
302 false, 0));
293 } 303 }
294 } 304 }
295 305
@@ -312,11 +322,13 @@ int main(int argc, char **argv) {
312 result = max_state(result, STATE_WARNING); 322 result = max_state(result, STATE_WARNING);
313 } 323 }
314 xasprintf(&performance_data, "%s %s", performance_data, 324 xasprintf(&performance_data, "%s %s", performance_data,
315 perfdata("realpower", (long)ups_realpower, "W", config.check_warn, (long)(config.warning_value), config.check_crit, 325 perfdata("realpower", (long)ups_realpower, "W", config.check_warn,
326 (long)(config.warning_value), config.check_crit,
316 (long)(config.critical_value), true, 0, false, 0)); 327 (long)(config.critical_value), true, 0, false, 0));
317 } else { 328 } else {
318 xasprintf(&performance_data, "%s %s", performance_data, 329 xasprintf(&performance_data, "%s %s", performance_data,
319 perfdata("realpower", (long)ups_realpower, "W", false, 0, false, 0, true, 0, false, 0)); 330 perfdata("realpower", (long)ups_realpower, "W", false, 0, false, 0, true, 0,
331 false, 0));
320 } 332 }
321 } 333 }
322 334
@@ -401,7 +413,8 @@ int get_ups_variable(const char *varname, char *buf, const check_ups_config conf
401 413
402 /* create the command string to send to the UPS daemon */ 414 /* create the command string to send to the UPS daemon */
403 /* Add LOGOUT to avoid read failure logs */ 415 /* Add LOGOUT to avoid read failure logs */
404 int res = snprintf(send_buffer, sizeof(send_buffer), "GET VAR %s %s\nLOGOUT\n", config.ups_name, varname); 416 int res = snprintf(send_buffer, sizeof(send_buffer), "GET VAR %s %s\nLOGOUT\n", config.ups_name,
417 varname);
405 if ((res > 0) && ((size_t)res >= sizeof(send_buffer))) { 418 if ((res > 0) && ((size_t)res >= sizeof(send_buffer))) {
406 printf("%s\n", _("UPS name to long for buffer")); 419 printf("%s\n", _("UPS name to long for buffer"));
407 return ERROR; 420 return ERROR;
@@ -410,7 +423,8 @@ int get_ups_variable(const char *varname, char *buf, const check_ups_config conf
410 char temp_buffer[MAX_INPUT_BUFFER]; 423 char temp_buffer[MAX_INPUT_BUFFER];
411 424
412 /* send the command to the daemon and get a response back */ 425 /* send the command to the daemon and get a response back */
413 if (process_tcp_request(config.server_address, config.server_port, send_buffer, temp_buffer, sizeof(temp_buffer)) != STATE_OK) { 426 if (process_tcp_request(config.server_address, config.server_port, send_buffer, temp_buffer,
427 sizeof(temp_buffer)) != STATE_OK) {
414 printf("%s\n", _("Invalid response received from host")); 428 printf("%s\n", _("Invalid response received from host"));
415 return ERROR; 429 return ERROR;
416 } 430 }
@@ -630,7 +644,8 @@ void print_help(void) {
630 printf(" %s\n", "-T, --temperature"); 644 printf(" %s\n", "-T, --temperature");
631 printf(" %s\n", _("Output of temperatures in Celsius")); 645 printf(" %s\n", _("Output of temperatures in Celsius"));
632 printf(" %s\n", "-v, --variable=STRING"); 646 printf(" %s\n", "-v, --variable=STRING");
633 printf(" %s %s\n", _("Valid values for STRING are"), "LINE, TEMP, BATTPCT, LOADPCT or REALPOWER"); 647 printf(" %s %s\n", _("Valid values for STRING are"),
648 "LINE, TEMP, BATTPCT, LOADPCT or REALPOWER");
634 649
635 printf(UT_WARN_CRIT); 650 printf(UT_WARN_CRIT);
636 651
diff --git a/plugins/check_ups.d/config.h b/plugins/check_ups.d/config.h
index 353104f2..e05edceb 100644
--- a/plugins/check_ups.d/config.h
+++ b/plugins/check_ups.d/config.h
@@ -52,4 +52,3 @@ check_ups_config check_ups_config_init(void) {
52 52
53 return tmp; 53 return tmp;
54} 54}
55
diff --git a/plugins/check_users.c b/plugins/check_users.c
index cd3bd181..2340eae4 100644
--- a/plugins/check_users.c
+++ b/plugins/check_users.c
@@ -128,10 +128,14 @@ int main(int argc, char **argv) {
128 128
129 switch (tmp_status) { 129 switch (tmp_status) {
130 case STATE_WARNING: 130 case STATE_WARNING:
131 xasprintf(&sc_users.output, "%d users currently logged in. This violates the warning threshold", user_wrapper.users); 131 xasprintf(&sc_users.output,
132 "%d users currently logged in. This violates the warning threshold",
133 user_wrapper.users);
132 break; 134 break;
133 case STATE_CRITICAL: 135 case STATE_CRITICAL:
134 xasprintf(&sc_users.output, "%d users currently logged in. This violates the critical threshold", user_wrapper.users); 136 xasprintf(&sc_users.output,
137 "%d users currently logged in. This violates the critical threshold",
138 user_wrapper.users);
135 break; 139 break;
136 default: 140 default:
137 xasprintf(&sc_users.output, "%d users currently logged in", user_wrapper.users); 141 xasprintf(&sc_users.output, "%d users currently logged in", user_wrapper.users);
@@ -218,7 +222,7 @@ check_users_config_wrapper process_arguments(int argc, char **argv) {
218 printf("Warning threshold missing\n"); 222 printf("Warning threshold missing\n");
219 print_usage(); 223 print_usage();
220 exit(STATE_UNKNOWN); 224 exit(STATE_UNKNOWN);
221 } 225 }
222 226
223 if (tmp.error == MP_PARSING_SUCCES) { 227 if (tmp.error == MP_PARSING_SUCCES) {
224 result.config.thresholds.warning = tmp.range; 228 result.config.thresholds.warning = tmp.range;
@@ -254,7 +258,8 @@ void print_help(void) {
254 printf(COPYRIGHT, copyright, email); 258 printf(COPYRIGHT, copyright, email);
255 259
256 printf("%s\n", _("This plugin checks the number of users currently logged in on the local")); 260 printf("%s\n", _("This plugin checks the number of users currently logged in on the local"));
257 printf("%s\n", _("system and generates an error if the number exceeds the thresholds specified.")); 261 printf("%s\n",
262 _("system and generates an error if the number exceeds the thresholds specified."));
258 263
259 printf("\n\n"); 264 printf("\n\n");
260 265
@@ -264,9 +269,11 @@ void print_help(void) {
264 printf(UT_EXTRA_OPTS); 269 printf(UT_EXTRA_OPTS);
265 270
266 printf(" %s\n", "-w, --warning=RANGE_EXPRESSION"); 271 printf(" %s\n", "-w, --warning=RANGE_EXPRESSION");
267 printf(" %s\n", _("Set WARNING status if number of logged in users violates RANGE_EXPRESSION")); 272 printf(" %s\n",
273 _("Set WARNING status if number of logged in users violates RANGE_EXPRESSION"));
268 printf(" %s\n", "-c, --critical=RANGE_EXPRESSION"); 274 printf(" %s\n", "-c, --critical=RANGE_EXPRESSION");
269 printf(" %s\n", _("Set CRITICAL status if number of logged in users violates RANGE_EXPRESSION")); 275 printf(" %s\n",
276 _("Set CRITICAL status if number of logged in users violates RANGE_EXPRESSION"));
270 printf(UT_OUTPUT_FORMAT); 277 printf(UT_OUTPUT_FORMAT);
271 278
272 printf(UT_SUPPORT); 279 printf(UT_SUPPORT);
diff --git a/plugins/check_users.d/users.c b/plugins/check_users.d/users.c
index a8b168a0..f37819b1 100644
--- a/plugins/check_users.d/users.c
+++ b/plugins/check_users.d/users.c
@@ -23,7 +23,8 @@ get_num_of_users_wrapper get_num_of_users_windows() {
23 LPTSTR username; 23 LPTSTR username;
24 DWORD size; 24 DWORD size;
25 25
26 if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, wtsinfo[index].SessionId, WTSUserName, &username, &size)) { 26 if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, wtsinfo[index].SessionId,
27 WTSUserName, &username, &size)) {
27 continue; 28 continue;
28 } 29 }
29 30
@@ -150,7 +151,8 @@ get_num_of_users_wrapper get_num_of_users_who_command() {
150 151
151 /* check STDERR */ 152 /* check STDERR */
152 if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) { 153 if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
153 // if this fails, something broke and the result can not be relied upon or so is the theorie here 154 // if this fails, something broke and the result can not be relied upon or so is the theorie
155 // here
154 result.errorcode = STDERR_COULD_NOT_BE_READ; 156 result.errorcode = STDERR_COULD_NOT_BE_READ;
155 } 157 }
156 (void)fclose(child_stderr); 158 (void)fclose(child_stderr);
diff --git a/plugins/common.h b/plugins/common.h
index 35d1e549..ef888d08 100644
--- a/plugins/common.h
+++ b/plugins/common.h
@@ -1,32 +1,32 @@
1/***************************************************************************** 1/*****************************************************************************
2* 2 *
3* Monitoring Plugins common include file 3 * Monitoring Plugins common include file
4* 4 *
5* License: GPL 5 * License: GPL
6* Copyright (c) 1999 Ethan Galstad (nagios@nagios.org) 6 * Copyright (c) 1999 Ethan Galstad (nagios@nagios.org)
7* Copyright (c) 2003-2007 Monitoring Plugins Development Team 7 * Copyright (c) 2003-2007 Monitoring Plugins Development Team
8* 8 *
9* Description: 9 * Description:
10* 10 *
11* This file contains common include files and defines used in many of 11 * This file contains common include files and defines used in many of
12* the plugins. 12 * the plugins.
13* 13 *
14* 14 *
15* This program is free software: you can redistribute it and/or modify 15 * This program is free software: you can redistribute it and/or modify
16* it under the terms of the GNU General Public License as published by 16 * it under the terms of the GNU General Public License as published by
17* the Free Software Foundation, either version 3 of the License, or 17 * the Free Software Foundation, either version 3 of the License, or
18* (at your option) any later version. 18 * (at your option) any later version.
19* 19 *
20* This program is distributed in the hope that it will be useful, 20 * This program is distributed in the hope that it will be useful,
21* but WITHOUT ANY WARRANTY; without even the implied warranty of 21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23* GNU General Public License for more details. 23 * GNU General Public License for more details.
24* 24 *
25* You should have received a copy of the GNU General Public License 25 * You should have received a copy of the GNU General Public License
26* along with this program. If not, see <http://www.gnu.org/licenses/>. 26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27* 27 *
28* 28 *
29*****************************************************************************/ 29 *****************************************************************************/
30 30
31#ifndef _COMMON_H_ 31#ifndef _COMMON_H_
32#define _COMMON_H_ 32#define _COMMON_H_
@@ -35,77 +35,78 @@
35#include "../lib/monitoringplug.h" 35#include "../lib/monitoringplug.h"
36 36
37#ifdef HAVE_FEATURES_H 37#ifdef HAVE_FEATURES_H
38#include <features.h> 38# include <features.h>
39#endif 39#endif
40 40
41#include <stdio.h> /* obligatory includes */ 41#include <stdio.h> /* obligatory includes */
42#include <stdlib.h> 42#include <stdlib.h>
43#include <errno.h> 43#include <errno.h>
44 44
45/* This block provides uintmax_t - should be reported to coreutils that this should be added to fsuage.h */ 45/* This block provides uintmax_t - should be reported to coreutils that this should be added to
46 * fsuage.h */
46#if HAVE_INTTYPES_H 47#if HAVE_INTTYPES_H
47# include <inttypes.h> 48# include <inttypes.h>
48#endif 49#endif
49#if HAVE_STDINT_H 50#if HAVE_STDINT_H
50# include <stdint.h> 51# include <stdint.h>
51#endif 52#endif
52#include <unistd.h> 53#include <unistd.h>
53#ifndef UINTMAX_MAX 54#ifndef UINTMAX_MAX
54# define UINTMAX_MAX ((uintmax_t) -1) 55# define UINTMAX_MAX ((uintmax_t) - 1)
55#endif 56#endif
56 57
57#include <limits.h> /* This is assumed true, because coreutils assume it too */ 58#include <limits.h> /* This is assumed true, because coreutils assume it too */
58 59
59#ifdef HAVE_MATH_H 60#ifdef HAVE_MATH_H
60#include <math.h> 61# include <math.h>
61#endif 62#endif
62 63
63#ifdef _AIX 64#ifdef _AIX
64#ifdef HAVE_MP_H 65# ifdef HAVE_MP_H
65#include <mp.h> 66# include <mp.h>
66#endif 67# endif
67#endif 68#endif
68 69
69#ifdef HAVE_STRINGS_H 70#ifdef HAVE_STRINGS_H
70#include <strings.h> 71# include <strings.h>
71#endif 72#endif
72#ifdef HAVE_STRING_H 73#ifdef HAVE_STRING_H
73#include <string.h> 74# include <string.h>
74#endif 75#endif
75 76
76#ifdef HAVE_UNISTD_H 77#ifdef HAVE_UNISTD_H
77#include <unistd.h> 78# include <unistd.h>
78#endif 79#endif
79 80
80/* GET_NUMBER_OF_CPUS is a macro to return 81/* GET_NUMBER_OF_CPUS is a macro to return
81 number of CPUs, if we can get that data. 82 number of CPUs, if we can get that data.
82 Use configure.in to test for various OS ways of 83 Use configure.in to test for various OS ways of
83 getting that data 84 getting that data
84 Will return -1 if cannot get data 85 Will return -1 if cannot get data
85*/ 86*/
86#if defined(HAVE_SYSCONF__SC_NPROCESSORS_ONLN) 87#if defined(HAVE_SYSCONF__SC_NPROCESSORS_ONLN)
87# define GET_NUMBER_OF_CPUS() sysconf(_SC_NPROCESSORS_ONLN) 88# define GET_NUMBER_OF_CPUS() sysconf(_SC_NPROCESSORS_ONLN)
88#elif defined (HAVE_SYSCONF__SC_NPROCESSORS_CONF) 89#elif defined(HAVE_SYSCONF__SC_NPROCESSORS_CONF)
89# define GET_NUMBER_OF_CPUS() sysconf(_SC_NPROCESSORS_CONF) 90# define GET_NUMBER_OF_CPUS() sysconf(_SC_NPROCESSORS_CONF)
90#else 91#else
91# define GET_NUMBER_OF_CPUS() -1 92# define GET_NUMBER_OF_CPUS() -1
92#endif 93#endif
93 94
94#ifdef HAVE_SYS_TIME_H 95#ifdef HAVE_SYS_TIME_H
95# include <sys/time.h> 96# include <sys/time.h>
96#endif 97#endif
97#include <time.h> 98#include <time.h>
98 99
99#ifdef HAVE_SYS_TYPES_H 100#ifdef HAVE_SYS_TYPES_H
100#include <sys/types.h> 101# include <sys/types.h>
101#endif 102#endif
102 103
103#ifdef HAVE_SYS_SOCKET_H 104#ifdef HAVE_SYS_SOCKET_H
104#include <sys/socket.h> 105# include <sys/socket.h>
105#endif 106#endif
106 107
107#ifdef HAVE_SIGNAL_H 108#ifdef HAVE_SIGNAL_H
108#include <signal.h> 109# include <signal.h>
109#endif 110#endif
110 111
111/* GNU Libraries */ 112/* GNU Libraries */
@@ -115,7 +116,7 @@
115#include <locale.h> 116#include <locale.h>
116 117
117#ifdef HAVE_SYS_POLL_H 118#ifdef HAVE_SYS_POLL_H
118# include "sys/poll.h" 119# include "sys/poll.h"
119#endif 120#endif
120 121
121/* 122/*
@@ -125,42 +126,42 @@
125 */ 126 */
126 127
127#ifndef HAVE_STRTOL 128#ifndef HAVE_STRTOL
128# define strtol(a,b,c) atol((a)) 129# define strtol(a, b, c) atol((a))
129#endif 130#endif
130 131
131#ifndef HAVE_STRTOUL 132#ifndef HAVE_STRTOUL
132# define strtoul(a,b,c) (unsigned long)atol((a)) 133# define strtoul(a, b, c) (unsigned long)atol((a))
133#endif 134#endif
134 135
135/* SSL implementations */ 136/* SSL implementations */
136#ifdef HAVE_GNUTLS_OPENSSL_H 137#ifdef HAVE_GNUTLS_OPENSSL_H
137# include <gnutls/openssl.h> 138# include <gnutls/openssl.h>
138#else 139#else
139# define OPENSSL_LOAD_CONF /* See the OPENSSL_config(3) man page. */ 140# define OPENSSL_LOAD_CONF /* See the OPENSSL_config(3) man page. */
140# ifdef HAVE_SSL_H 141# ifdef HAVE_SSL_H
141# include <rsa.h> 142# include <rsa.h>
142# include <crypto.h> 143# include <crypto.h>
143# include <x509.h> 144# include <x509.h>
144# include <pem.h> 145# include <pem.h>
145# include <ssl.h> 146# include <ssl.h>
146# include <err.h> 147# include <err.h>
147# else 148# else
148# ifdef HAVE_OPENSSL_SSL_H 149# ifdef HAVE_OPENSSL_SSL_H
149# include <openssl/rsa.h> 150# include <openssl/rsa.h>
150# include <openssl/crypto.h> 151# include <openssl/crypto.h>
151# include <openssl/x509.h> 152# include <openssl/x509.h>
152# include <openssl/pem.h> 153# include <openssl/pem.h>
153# include <openssl/ssl.h> 154# include <openssl/ssl.h>
154# include <openssl/err.h> 155# include <openssl/err.h>
155# endif 156# endif
156# endif 157# endif
157#endif 158#endif
158 159
159/* openssl 1.1 does not set OPENSSL_NO_SSL2 by default but ships without ssl2 */ 160/* openssl 1.1 does not set OPENSSL_NO_SSL2 by default but ships without ssl2 */
160#ifdef OPENSSL_VERSION_NUMBER 161#ifdef OPENSSL_VERSION_NUMBER
161# if OPENSSL_VERSION_NUMBER >= 0x10100000 162# if OPENSSL_VERSION_NUMBER >= 0x10100000
162# define OPENSSL_NO_SSL2 163# define OPENSSL_NO_SSL2
163# endif 164# endif
164#endif 165#endif
165 166
166/* 167/*
@@ -171,7 +172,7 @@
171 172
172/* MariaDB 10.2 client does not set MYSQL_PORT */ 173/* MariaDB 10.2 client does not set MYSQL_PORT */
173#ifndef MYSQL_PORT 174#ifndef MYSQL_PORT
174# define MYSQL_PORT 3306 175# define MYSQL_PORT 3306
175#endif 176#endif
176 177
177enum { 178enum {
@@ -180,9 +181,9 @@ enum {
180}; 181};
181 182
182enum { 183enum {
183 DEFAULT_SOCKET_TIMEOUT = 10, /* timeout after 10 seconds */ 184 DEFAULT_SOCKET_TIMEOUT = 10, /* timeout after 10 seconds */
184 MAX_INPUT_BUFFER = 8192, /* max size of most buffers we use */ 185 MAX_INPUT_BUFFER = 8192, /* max size of most buffers we use */
185 MAX_HOST_ADDRESS_LENGTH = 256 /* max size of a host address */ 186 MAX_HOST_ADDRESS_LENGTH = 256 /* max size of a host address */
186}; 187};
187 188
188/* 189/*
@@ -191,17 +192,17 @@ enum {
191 * 192 *
192 */ 193 */
193#include "../gl/gettext.h" 194#include "../gl/gettext.h"
194#define _(String) gettext (String) 195#define _(String) gettext(String)
195#if ! ENABLE_NLS 196#if !ENABLE_NLS
196# undef textdomain 197# undef textdomain
197# define textdomain(Domainname) /* empty */ 198# define textdomain(Domainname) /* empty */
198# undef bindtextdomain 199# undef bindtextdomain
199# define bindtextdomain(Domainname, Dirname) /* empty */ 200# define bindtextdomain(Domainname, Dirname) /* empty */
200#endif 201#endif
201 202
202/* For non-GNU compilers to ignore __attribute__ */ 203/* For non-GNU compilers to ignore __attribute__ */
203#ifndef __GNUC__ 204#ifndef __GNUC__
204# define __attribute__(x) /* do nothing */ 205# define __attribute__(x) /* do nothing */
205#endif 206#endif
206 207
207#endif /* _COMMON_H_ */ 208#endif /* _COMMON_H_ */
diff --git a/plugins/negate.c b/plugins/negate.c
index 0520d298..a42a6c59 100644
--- a/plugins/negate.c
+++ b/plugins/negate.c
@@ -105,7 +105,8 @@ int main(int argc, char **argv) {
105 *sub = '\0'; 105 *sub = '\0';
106 sub += strlen(state_text(result)); 106 sub += strlen(state_text(result));
107 /* then put everything back together */ 107 /* then put everything back together */
108 xasprintf(&chld_out.line[i], "%s%s%s", chld_out.line[i], state_text(config.state[result]), sub); 108 xasprintf(&chld_out.line[i], "%s%s%s", chld_out.line[i],
109 state_text(config.state[result]), sub);
109 } 110 }
110 } 111 }
111 printf("%s\n", chld_out.line[i]); 112 printf("%s\n", chld_out.line[i]);
@@ -120,11 +121,12 @@ int main(int argc, char **argv) {
120 121
121/* process command-line arguments */ 122/* process command-line arguments */
122static negate_config_wrapper process_arguments(int argc, char **argv) { 123static negate_config_wrapper process_arguments(int argc, char **argv) {
123 static struct option longopts[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, 124 static struct option longopts[] = {
124 {"timeout", required_argument, 0, 't'}, {"timeout-result", required_argument, 0, 'T'}, 125 {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'},
125 {"ok", required_argument, 0, 'o'}, {"warning", required_argument, 0, 'w'}, 126 {"timeout", required_argument, 0, 't'}, {"timeout-result", required_argument, 0, 'T'},
126 {"critical", required_argument, 0, 'c'}, {"unknown", required_argument, 0, 'u'}, 127 {"ok", required_argument, 0, 'o'}, {"warning", required_argument, 0, 'w'},
127 {"substitute", no_argument, 0, 's'}, {0, 0, 0, 0}}; 128 {"critical", required_argument, 0, 'c'}, {"unknown", required_argument, 0, 'u'},
129 {"substitute", no_argument, 0, 's'}, {0, 0, 0, 0}};
128 130
129 negate_config_wrapper result = { 131 negate_config_wrapper result = {
130 .errorcode = OK, 132 .errorcode = OK,
@@ -159,31 +161,36 @@ static negate_config_wrapper process_arguments(int argc, char **argv) {
159 break; 161 break;
160 case 'T': /* Result to return on timeouts */ 162 case 'T': /* Result to return on timeouts */
161 if ((timeout_state = mp_translate_state(optarg)) == ERROR) { 163 if ((timeout_state = mp_translate_state(optarg)) == ERROR) {
162 usage4(_("Timeout result must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); 164 usage4(_("Timeout result must be a valid state name (OK, WARNING, CRITICAL, "
165 "UNKNOWN) or integer (0-3)."));
163 } 166 }
164 break; 167 break;
165 case 'o': /* replacement for OK */ 168 case 'o': /* replacement for OK */
166 if ((result.config.state[STATE_OK] = mp_translate_state(optarg)) == ERROR) { 169 if ((result.config.state[STATE_OK] = mp_translate_state(optarg)) == ERROR) {
167 usage4(_("Ok must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); 170 usage4(_("Ok must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or "
171 "integer (0-3)."));
168 } 172 }
169 permute = false; 173 permute = false;
170 break; 174 break;
171 175
172 case 'w': /* replacement for WARNING */ 176 case 'w': /* replacement for WARNING */
173 if ((result.config.state[STATE_WARNING] = mp_translate_state(optarg)) == ERROR) { 177 if ((result.config.state[STATE_WARNING] = mp_translate_state(optarg)) == ERROR) {
174 usage4(_("Warning must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); 178 usage4(_("Warning must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or "
179 "integer (0-3)."));
175 } 180 }
176 permute = false; 181 permute = false;
177 break; 182 break;
178 case 'c': /* replacement for CRITICAL */ 183 case 'c': /* replacement for CRITICAL */
179 if ((result.config.state[STATE_CRITICAL] = mp_translate_state(optarg)) == ERROR) { 184 if ((result.config.state[STATE_CRITICAL] = mp_translate_state(optarg)) == ERROR) {
180 usage4(_("Critical must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); 185 usage4(_("Critical must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or "
186 "integer (0-3)."));
181 } 187 }
182 permute = false; 188 permute = false;
183 break; 189 break;
184 case 'u': /* replacement for UNKNOWN */ 190 case 'u': /* replacement for UNKNOWN */
185 if ((result.config.state[STATE_UNKNOWN] = mp_translate_state(optarg)) == ERROR) { 191 if ((result.config.state[STATE_UNKNOWN] = mp_translate_state(optarg)) == ERROR) {
186 usage4(_("Unknown must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); 192 usage4(_("Unknown must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or "
193 "integer (0-3)."));
187 } 194 }
188 permute = false; 195 permute = false;
189 break; 196 break;
@@ -208,7 +215,8 @@ negate_config_wrapper validate_arguments(negate_config_wrapper config_wrapper) {
208 usage4(_("Could not parse arguments")); 215 usage4(_("Could not parse arguments"));
209 } 216 }
210 217
211 if (strncmp(config_wrapper.config.command_line[0], "/", 1) != 0 && strncmp(config_wrapper.config.command_line[0], "./", 2) != 0) { 218 if (strncmp(config_wrapper.config.command_line[0], "/", 1) != 0 &&
219 strncmp(config_wrapper.config.command_line[0], "./", 2) != 0) {
212 usage4(_("Require path to command")); 220 usage4(_("Require path to command"));
213 } 221 }
214 222
@@ -220,7 +228,8 @@ void print_help(void) {
220 228
221 printf(COPYRIGHT, copyright, email); 229 printf(COPYRIGHT, copyright, email);
222 230
223 printf("%s\n", _("Negates only the return code of a plugin (returns OK for CRITICAL and vice-versa) by default.")); 231 printf("%s\n", _("Negates only the return code of a plugin (returns OK for CRITICAL and "
232 "vice-versa) by default."));
224 printf("%s\n", _("Additional switches can be used to control:\n")); 233 printf("%s\n", _("Additional switches can be used to control:\n"));
225 printf("\t - which state becomes what\n"); 234 printf("\t - which state becomes what\n");
226 printf("\t - changing the plugin output text to match the return code"); 235 printf("\t - changing the plugin output text to match the return code");
@@ -250,17 +259,20 @@ void print_help(void) {
250 printf("%s\n", _("Examples:")); 259 printf("%s\n", _("Examples:"));
251 printf(" %s\n", "negate /usr/local/nagios/libexec/check_ping -H host"); 260 printf(" %s\n", "negate /usr/local/nagios/libexec/check_ping -H host");
252 printf(" %s\n", _("Run check_ping and invert result. Must use full path to plugin")); 261 printf(" %s\n", _("Run check_ping and invert result. Must use full path to plugin"));
253 printf(" %s\n", "negate -w OK -c UNKNOWN /usr/local/nagios/libexec/check_procs -a 'vi negate.c'"); 262 printf(" %s\n",
263 "negate -w OK -c UNKNOWN /usr/local/nagios/libexec/check_procs -a 'vi negate.c'");
254 printf(" %s\n", _("This will return OK instead of WARNING and UNKNOWN instead of CRITICAL")); 264 printf(" %s\n", _("This will return OK instead of WARNING and UNKNOWN instead of CRITICAL"));
255 printf("\n"); 265 printf("\n");
256 printf("%s\n", _("Notes:")); 266 printf("%s\n", _("Notes:"));
257 printf(" %s\n", _("This plugin is a wrapper to take the output of another plugin and invert it.")); 267 printf(" %s\n",
268 _("This plugin is a wrapper to take the output of another plugin and invert it."));
258 printf(" %s\n", _("The full path of the plugin must be provided.")); 269 printf(" %s\n", _("The full path of the plugin must be provided."));
259 printf(" %s\n", _("If the wrapped plugin returns OK, the wrapper will return CRITICAL.")); 270 printf(" %s\n", _("If the wrapped plugin returns OK, the wrapper will return CRITICAL."));
260 printf(" %s\n", _("If the wrapped plugin returns CRITICAL, the wrapper will return OK.")); 271 printf(" %s\n", _("If the wrapped plugin returns CRITICAL, the wrapper will return OK."));
261 printf(" %s\n", _("Otherwise, the output state of the wrapped plugin is unchanged.")); 272 printf(" %s\n", _("Otherwise, the output state of the wrapped plugin is unchanged."));
262 printf("\n"); 273 printf("\n");
263 printf(" %s\n", _("Using timeout-result, it is possible to override the timeout behaviour or a")); 274 printf(" %s\n",
275 _("Using timeout-result, it is possible to override the timeout behaviour or a"));
264 printf(" %s\n", _("plugin by setting the negate timeout a bit lower.")); 276 printf(" %s\n", _("plugin by setting the negate timeout a bit lower."));
265 277
266 printf(UT_SUPPORT); 278 printf(UT_SUPPORT);
diff --git a/plugins/netutils.c b/plugins/netutils.c
index e2916c65..b4c6ff0a 100644
--- a/plugins/netutils.c
+++ b/plugins/netutils.c
@@ -30,13 +30,14 @@
30#include "common.h" 30#include "common.h"
31#include "output.h" 31#include "output.h"
32#include "states.h" 32#include "states.h"
33#include <sys/types.h>
33#include "netutils.h" 34#include "netutils.h"
34 35
35unsigned int socket_timeout = DEFAULT_SOCKET_TIMEOUT; 36unsigned int socket_timeout = DEFAULT_SOCKET_TIMEOUT;
36unsigned int socket_timeout_state = STATE_CRITICAL; 37mp_state_enum socket_timeout_state = STATE_CRITICAL;
37 38mp_state_enum econn_refuse_state = STATE_CRITICAL;
38int econn_refuse_state = STATE_CRITICAL;
39bool was_refused = false; 39bool was_refused = false;
40
40#if USE_IPV6 41#if USE_IPV6
41int address_family = AF_UNSPEC; 42int address_family = AF_UNSPEC;
42#else 43#else
@@ -63,38 +64,40 @@ void socket_timeout_alarm_handler(int sig) {
63/* connects to a host on a specified tcp port, sends a string, and gets a 64/* connects to a host on a specified tcp port, sends a string, and gets a
64 response. loops on select-recv until timeout or eof to get all of a 65 response. loops on select-recv until timeout or eof to get all of a
65 multi-packet answer */ 66 multi-packet answer */
66int process_tcp_request2(const char *server_address, int server_port, const char *send_buffer, char *recv_buffer, int recv_size) { 67mp_state_enum process_tcp_request2(const char *server_address, const int server_port,
68 const char *send_buffer, char *recv_buffer,
69 const int recv_size) {
67 70
68 int result; 71 int socket;
69 int send_result;
70 int recv_result;
71 int sd;
72 struct timeval tv;
73 fd_set readfds;
74 int recv_length = 0;
75 72
76 result = np_net_connect(server_address, server_port, &sd, IPPROTO_TCP); 73 mp_state_enum connect_result =
77 if (result != STATE_OK) { 74 np_net_connect(server_address, server_port, &socket, IPPROTO_TCP);
75 if (connect_result != STATE_OK) {
78 return STATE_CRITICAL; 76 return STATE_CRITICAL;
79 } 77 }
80 78
81 send_result = send(sd, send_buffer, strlen(send_buffer), 0); 79 mp_state_enum result;
80 ssize_t send_result = send(socket, send_buffer, strlen(send_buffer), 0);
82 if (send_result < 0 || (size_t)send_result != strlen(send_buffer)) { 81 if (send_result < 0 || (size_t)send_result != strlen(send_buffer)) {
83 // printf("%s\n", _("Send failed")); 82 // printf("%s\n", _("Send failed"));
84 result = STATE_WARNING; 83 result = STATE_WARNING;
85 } 84 }
86 85
87 while (1) { 86 fd_set readfds;
87 ssize_t recv_length = 0;
88 while (true) {
88 /* wait up to the number of seconds for socket timeout 89 /* wait up to the number of seconds for socket timeout
89 minus one for data from the host */ 90 minus one for data from the host */
90 tv.tv_sec = socket_timeout - 1; 91 struct timeval timeout = {
91 tv.tv_usec = 0; 92 .tv_sec = socket_timeout - 1,
93 .tv_usec = 0,
94 };
92 FD_ZERO(&readfds); 95 FD_ZERO(&readfds);
93 FD_SET(sd, &readfds); 96 FD_SET(socket, &readfds);
94 select(sd + 1, &readfds, NULL, NULL, &tv); 97 select(socket + 1, &readfds, NULL, NULL, &timeout);
95 98
96 /* make sure some data has arrived */ 99 /* make sure some data has arrived */
97 if (!FD_ISSET(sd, &readfds)) { /* it hasn't */ 100 if (!FD_ISSET(socket, &readfds)) { /* it hasn't */
98 if (!recv_length) { 101 if (!recv_length) {
99 strcpy(recv_buffer, ""); 102 strcpy(recv_buffer, "");
100 // printf("%s\n", _("No data was received from host!")); 103 // printf("%s\n", _("No data was received from host!"));
@@ -103,70 +106,69 @@ int process_tcp_request2(const char *server_address, int server_port, const char
103 recv_buffer[recv_length] = 0; 106 recv_buffer[recv_length] = 0;
104 } 107 }
105 break; 108 break;
106 } else { /* it has */ 109 } /* it has */
107 recv_result = recv(sd, recv_buffer + recv_length, (size_t)recv_size - recv_length - 1, 0); 110
108 if (recv_result == -1) { 111 ssize_t recv_result =
109 /* recv failed, bail out */ 112 recv(socket, recv_buffer + recv_length, (size_t)(recv_size - recv_length - 1), 0);
110 strcpy(recv_buffer + recv_length, ""); 113 if (recv_result == -1) {
111 result = STATE_WARNING; 114 /* recv failed, bail out */
112 break; 115 strcpy(recv_buffer + recv_length, "");
113 } else if (recv_result == 0) { 116 result = STATE_WARNING;
114 /* end of file ? */ 117 break;
115 recv_buffer[recv_length] = 0; 118 }
116 break; 119
117 } else { /* we got data! */ 120 if (recv_result == 0) {
118 recv_length += recv_result; 121 /* end of file ? */
119 if (recv_length >= recv_size - 1) { 122 recv_buffer[recv_length] = 0;
120 /* buffer full, we're done */ 123 break;
121 recv_buffer[recv_size - 1] = 0; 124 }
122 break; 125
123 } 126 /* we got data! */
124 } 127 recv_length += recv_result;
128 if (recv_length >= recv_size - 1) {
129 /* buffer full, we're done */
130 recv_buffer[recv_size - 1] = 0;
131 break;
125 } 132 }
126 /* end if(!FD_ISSET(sd,&readfds)) */ 133 /* end if(!FD_ISSET(sd,&readfds)) */
127 } 134 }
128 /* end while(1) */
129 135
130 close(sd); 136 close(socket);
131 return result; 137 return result;
132} 138}
133 139
134/* connects to a host on a specified port, sends a string, and gets a 140/* connects to a host on a specified port, sends a string, and gets a
135 response */ 141 response */
136int process_request(const char *server_address, int server_port, int proto, const char *send_buffer, char *recv_buffer, int recv_size) { 142mp_state_enum process_request(const char *server_address, const int server_port, const int proto,
137 int result; 143 const char *send_buffer, char *recv_buffer, const int recv_size) {
138 int sd;
139 144
140 result = STATE_OK; 145 mp_state_enum result = STATE_OK;
141 146 int socket;
142 result = np_net_connect(server_address, server_port, &sd, proto); 147 result = np_net_connect(server_address, server_port, &socket, proto);
143 if (result != STATE_OK) { 148 if (result != STATE_OK) {
144 return STATE_CRITICAL; 149 return STATE_CRITICAL;
145 } 150 }
146 151
147 result = send_request(sd, proto, send_buffer, recv_buffer, recv_size); 152 result = send_request(socket, proto, send_buffer, recv_buffer, recv_size);
148 153
149 close(sd); 154 close(socket);
150 155
151 return result; 156 return result;
152} 157}
153 158
154/* opens a tcp or udp connection to a remote host or local socket */ 159/* opens a tcp or udp connection to a remote host or local socket */
155int np_net_connect(const char *host_name, int port, int *sd, int proto) { 160mp_state_enum np_net_connect(const char *host_name, int port, int *socketDescriptor,
161 const int proto) {
156 /* send back STATE_UNKOWN if there's an error 162 /* send back STATE_UNKOWN if there's an error
157 send back STATE_OK if we connect 163 send back STATE_OK if we connect
158 send back STATE_CRITICAL if we can't connect. 164 send back STATE_CRITICAL if we can't connect.
159 Let upstream figure out what to send to the user. */ 165 Let upstream figure out what to send to the user. */
160 struct addrinfo hints; 166 bool is_socket = (host_name[0] == '/');
161 struct addrinfo *r, *res; 167 int socktype = (proto == IPPROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM;
162 struct sockaddr_un su;
163 char port_str[6], host[MAX_HOST_ADDRESS_LENGTH];
164 size_t len;
165 int socktype, result;
166 short is_socket = (host_name[0] == '/');
167
168 socktype = (proto == IPPROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM;
169 168
169 struct addrinfo hints = {};
170 struct addrinfo *res = NULL;
171 int result;
170 /* as long as it doesn't start with a '/', it's assumed a host or ip */ 172 /* as long as it doesn't start with a '/', it's assumed a host or ip */
171 if (!is_socket) { 173 if (!is_socket) {
172 memset(&hints, 0, sizeof(hints)); 174 memset(&hints, 0, sizeof(hints));
@@ -174,38 +176,46 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) {
174 hints.ai_protocol = proto; 176 hints.ai_protocol = proto;
175 hints.ai_socktype = socktype; 177 hints.ai_socktype = socktype;
176 178
177 len = strlen(host_name); 179 size_t len = strlen(host_name);
178 /* check for an [IPv6] address (and strip the brackets) */ 180 /* check for an [IPv6] address (and strip the brackets) */
179 if (len >= 2 && host_name[0] == '[' && host_name[len - 1] == ']') { 181 if (len >= 2 && host_name[0] == '[' && host_name[len - 1] == ']') {
180 host_name++; 182 host_name++;
181 len -= 2; 183 len -= 2;
182 } 184 }
185
186 char host[MAX_HOST_ADDRESS_LENGTH];
187
183 if (len >= sizeof(host)) { 188 if (len >= sizeof(host)) {
184 return STATE_UNKNOWN; 189 return STATE_UNKNOWN;
185 } 190 }
191
186 memcpy(host, host_name, len); 192 memcpy(host, host_name, len);
187 host[len] = '\0'; 193 host[len] = '\0';
194
195 char port_str[6];
188 snprintf(port_str, sizeof(port_str), "%d", port); 196 snprintf(port_str, sizeof(port_str), "%d", port);
189 result = getaddrinfo(host, port_str, &hints, &res); 197 int getaddrinfo_err = getaddrinfo(host, port_str, &hints, &res);
190 198
191 if (result != 0) { 199 if (getaddrinfo_err != 0) {
192 // printf("%s\n", gai_strerror(result)); 200 // printf("%s\n", gai_strerror(result));
193 return STATE_UNKNOWN; 201 return STATE_UNKNOWN;
194 } 202 }
195 203
196 r = res; 204 struct addrinfo *addressPointer = res;
197 while (r) { 205 while (addressPointer) {
198 /* attempt to create a socket */ 206 /* attempt to create a socket */
199 *sd = socket(r->ai_family, socktype, r->ai_protocol); 207 *socketDescriptor =
208 socket(addressPointer->ai_family, socktype, addressPointer->ai_protocol);
200 209
201 if (*sd < 0) { 210 if (*socketDescriptor < 0) {
202 // printf("%s\n", _("Socket creation failed")); 211 // printf("%s\n", _("Socket creation failed"));
203 freeaddrinfo(r); 212 freeaddrinfo(addressPointer);
204 return STATE_UNKNOWN; 213 return STATE_UNKNOWN;
205 } 214 }
206 215
207 /* attempt to open a connection */ 216 /* attempt to open a connection */
208 result = connect(*sd, r->ai_addr, r->ai_addrlen); 217 result =
218 connect(*socketDescriptor, addressPointer->ai_addr, addressPointer->ai_addrlen);
209 219
210 if (result == 0) { 220 if (result == 0) {
211 was_refused = false; 221 was_refused = false;
@@ -220,24 +230,28 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) {
220 } 230 }
221 } 231 }
222 232
223 close(*sd); 233 close(*socketDescriptor);
224 r = r->ai_next; 234 addressPointer = addressPointer->ai_next;
225 } 235 }
236
226 freeaddrinfo(res); 237 freeaddrinfo(res);
227 } 238
228 /* else the hostname is interpreted as a path to a unix socket */ 239 } else {
229 else { 240 /* else the hostname is interpreted as a path to a unix socket */
230 if (strlen(host_name) >= UNIX_PATH_MAX) { 241 if (strlen(host_name) >= UNIX_PATH_MAX) {
231 die(STATE_UNKNOWN, _("Supplied path too long unix domain socket")); 242 die(STATE_UNKNOWN, _("Supplied path too long unix domain socket"));
232 } 243 }
233 memset(&su, 0, sizeof(su)); 244
245 struct sockaddr_un su = {};
234 su.sun_family = AF_UNIX; 246 su.sun_family = AF_UNIX;
235 strncpy(su.sun_path, host_name, UNIX_PATH_MAX); 247 strncpy(su.sun_path, host_name, UNIX_PATH_MAX);
236 *sd = socket(PF_UNIX, SOCK_STREAM, 0); 248 *socketDescriptor = socket(PF_UNIX, SOCK_STREAM, 0);
237 if (*sd < 0) { 249
250 if (*socketDescriptor < 0) {
238 die(STATE_UNKNOWN, _("Socket creation failed")); 251 die(STATE_UNKNOWN, _("Socket creation failed"));
239 } 252 }
240 result = connect(*sd, (struct sockaddr *)&su, sizeof(su)); 253
254 result = connect(*socketDescriptor, (struct sockaddr *)&su, sizeof(su));
241 if (result < 0 && errno == ECONNREFUSED) { 255 if (result < 0 && errno == ECONNREFUSED) {
242 was_refused = true; 256 was_refused = true;
243 } 257 }
@@ -245,7 +259,9 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) {
245 259
246 if (result == 0) { 260 if (result == 0) {
247 return STATE_OK; 261 return STATE_OK;
248 } else if (was_refused) { 262 }
263
264 if (was_refused) {
249 switch (econn_refuse_state) { /* a user-defined expected outcome */ 265 switch (econn_refuse_state) { /* a user-defined expected outcome */
250 case STATE_OK: 266 case STATE_OK:
251 case STATE_WARNING: /* user wants WARN or OK on refusal, or... */ 267 case STATE_WARNING: /* user wants WARN or OK on refusal, or... */
@@ -253,7 +269,8 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) {
253 if (is_socket) { 269 if (is_socket) {
254 // printf("connect to file socket %s: %s\n", host_name, strerror(errno)); 270 // printf("connect to file socket %s: %s\n", host_name, strerror(errno));
255 } else { 271 } else {
256 // printf("connect to address %s and port %d: %s\n", host_name, port, strerror(errno)); 272 // printf("connect to address %s and port %d: %s\n", host_name, port,
273 // strerror(errno));
257 } 274 }
258 return STATE_CRITICAL; 275 return STATE_CRITICAL;
259 break; 276 break;
@@ -271,14 +288,11 @@ int np_net_connect(const char *host_name, int port, int *sd, int proto) {
271 } 288 }
272} 289}
273 290
274int send_request(int sd, int proto, const char *send_buffer, char *recv_buffer, int recv_size) { 291mp_state_enum send_request(const int socket, const int proto, const char *send_buffer,
275 int result = STATE_OK; 292 char *recv_buffer, const int recv_size) {
276 int send_result; 293 mp_state_enum result = STATE_OK;
277 int recv_result;
278 struct timeval tv;
279 fd_set readfds;
280 294
281 send_result = send(sd, send_buffer, strlen(send_buffer), 0); 295 ssize_t send_result = send(socket, send_buffer, strlen(send_buffer), 0);
282 if (send_result < 0 || (size_t)send_result != strlen(send_buffer)) { 296 if (send_result < 0 || (size_t)send_result != strlen(send_buffer)) {
283 // printf("%s\n", _("Send failed")); 297 // printf("%s\n", _("Send failed"));
284 result = STATE_WARNING; 298 result = STATE_WARNING;
@@ -286,21 +300,22 @@ int send_request(int sd, int proto, const char *send_buffer, char *recv_buffer,
286 300
287 /* wait up to the number of seconds for socket timeout minus one 301 /* wait up to the number of seconds for socket timeout minus one
288 for data from the host */ 302 for data from the host */
289 tv.tv_sec = socket_timeout - 1; 303 struct timeval timestamp = {
290 tv.tv_usec = 0; 304 .tv_sec = socket_timeout - 1,
305 .tv_usec = 0,
306 };
307 fd_set readfds;
291 FD_ZERO(&readfds); 308 FD_ZERO(&readfds);
292 FD_SET(sd, &readfds); 309 FD_SET(socket, &readfds);
293 select(sd + 1, &readfds, NULL, NULL, &tv); 310 select(socket + 1, &readfds, NULL, NULL, &timestamp);
294 311
295 /* make sure some data has arrived */ 312 /* make sure some data has arrived */
296 if (!FD_ISSET(sd, &readfds)) { 313 if (!FD_ISSET(socket, &readfds)) {
297 strcpy(recv_buffer, ""); 314 strcpy(recv_buffer, "");
298 // printf("%s\n", _("No data was received from host!")); 315 // printf("%s\n", _("No data was received from host!"));
299 result = STATE_WARNING; 316 result = STATE_WARNING;
300 } 317 } else {
301 318 ssize_t recv_result = recv(socket, recv_buffer, (size_t)(recv_size - 1), 0);
302 else {
303 recv_result = recv(sd, recv_buffer, (size_t)recv_size - 1, 0);
304 if (recv_result == -1) { 319 if (recv_result == -1) {
305 strcpy(recv_buffer, ""); 320 strcpy(recv_buffer, "");
306 if (proto != IPPROTO_TCP) { 321 if (proto != IPPROTO_TCP) {
@@ -314,6 +329,7 @@ int send_request(int sd, int proto, const char *send_buffer, char *recv_buffer,
314 /* die returned string */ 329 /* die returned string */
315 recv_buffer[recv_size - 1] = 0; 330 recv_buffer[recv_size - 1] = 0;
316 } 331 }
332
317 return result; 333 return result;
318} 334}
319 335
@@ -335,27 +351,27 @@ bool is_addr(const char *address) {
335#ifdef USE_IPV6 351#ifdef USE_IPV6
336 if (address_family == AF_INET && is_inet_addr(address)) { 352 if (address_family == AF_INET && is_inet_addr(address)) {
337 return true; 353 return true;
338 } else if (address_family == AF_INET6 && is_inet6_addr(address)) { 354 }
355
356 if (address_family == AF_INET6 && is_inet6_addr(address)) {
339 return true; 357 return true;
340 } 358 }
341#else 359#else
342 if (is_inet_addr(address)) { 360 if (is_inet_addr(address)) {
343 return (true); 361 return true;
344 } 362 }
345#endif 363#endif
346 364
347 return (false); 365 return false;
348} 366}
349 367
350int dns_lookup(const char *in, struct sockaddr_storage *ss, int family) { 368bool dns_lookup(const char *node_string, struct sockaddr_storage *ss, const int family) {
351 struct addrinfo hints; 369 struct addrinfo hints;
352 struct addrinfo *res;
353 int retval;
354
355 memset(&hints, 0, sizeof(struct addrinfo)); 370 memset(&hints, 0, sizeof(struct addrinfo));
356 hints.ai_family = family; 371 hints.ai_family = family;
357 372
358 retval = getaddrinfo(in, NULL, &hints, &res); 373 struct addrinfo *res;
374 int retval = getaddrinfo(node_string, NULL, &hints, &res);
359 if (retval != 0) { 375 if (retval != 0) {
360 return false; 376 return false;
361 } 377 }
@@ -363,6 +379,8 @@ int dns_lookup(const char *in, struct sockaddr_storage *ss, int family) {
363 if (ss != NULL) { 379 if (ss != NULL) {
364 memcpy(ss, res->ai_addr, res->ai_addrlen); 380 memcpy(ss, res->ai_addr, res->ai_addrlen);
365 } 381 }
382
366 freeaddrinfo(res); 383 freeaddrinfo(res);
384
367 return true; 385 return true;
368} 386}
diff --git a/plugins/netutils.h b/plugins/netutils.h
index 6adb8e01..c4461113 100644
--- a/plugins/netutils.h
+++ b/plugins/netutils.h
@@ -31,7 +31,6 @@
31#ifndef _NETUTILS_H_ 31#ifndef _NETUTILS_H_
32#define _NETUTILS_H_ 32#define _NETUTILS_H_
33 33
34#include "common.h"
35#include "output.h" 34#include "output.h"
36#include "states.h" 35#include "states.h"
37#include "utils.h" 36#include "utils.h"
@@ -56,25 +55,26 @@
56 process_request(addr, port, IPPROTO_TCP, sbuf, rbuf, rsize) 55 process_request(addr, port, IPPROTO_TCP, sbuf, rbuf, rsize)
57#define process_udp_request(addr, port, sbuf, rbuf, rsize) \ 56#define process_udp_request(addr, port, sbuf, rbuf, rsize) \
58 process_request(addr, port, IPPROTO_UDP, sbuf, rbuf, rsize) 57 process_request(addr, port, IPPROTO_UDP, sbuf, rbuf, rsize)
59int process_tcp_request2(const char *address, int port, const char *sbuffer, char *rbuffer, 58mp_state_enum process_tcp_request2(const char *server_address, int server_port,
60 int rsize); 59 const char *send_buffer, char *recv_buffer, int recv_size);
61int process_request(const char *address, int port, int proto, const char *sbuffer, char *rbuffer, 60mp_state_enum process_request(const char *server_address, int server_port, int proto,
62 int rsize); 61 const char *send_buffer, char *recv_buffer, int recv_size);
63 62
64/* my_connect and wrapper macros */ 63/* my_connect and wrapper macros */
65#define my_tcp_connect(addr, port, s) np_net_connect(addr, port, s, IPPROTO_TCP) 64#define my_tcp_connect(addr, port, s) np_net_connect(addr, port, s, IPPROTO_TCP)
66#define my_udp_connect(addr, port, s) np_net_connect(addr, port, s, IPPROTO_UDP) 65#define my_udp_connect(addr, port, s) np_net_connect(addr, port, s, IPPROTO_UDP)
67int np_net_connect(const char *address, int port, int *sd, int proto); 66mp_state_enum np_net_connect(const char *host_name, int port, int *socketDescriptor, int proto);
68 67
69/* send_request and wrapper macros */ 68/* send_request and wrapper macros */
70#define send_tcp_request(s, sbuf, rbuf, rsize) send_request(s, IPPROTO_TCP, sbuf, rbuf, rsize) 69#define send_tcp_request(s, sbuf, rbuf, rsize) send_request(s, IPPROTO_TCP, sbuf, rbuf, rsize)
71#define send_udp_request(s, sbuf, rbuf, rsize) send_request(s, IPPROTO_UDP, sbuf, rbuf, rsize) 70#define send_udp_request(s, sbuf, rbuf, rsize) send_request(s, IPPROTO_UDP, sbuf, rbuf, rsize)
72int send_request(int sd, int proto, const char *send_buffer, char *recv_buffer, int recv_size); 71mp_state_enum send_request(int socket, int proto, const char *send_buffer, char *recv_buffer,
72 int recv_size);
73 73
74/* "is_*" wrapper macros and functions */ 74/* "is_*" wrapper macros and functions */
75bool is_host(const char *); 75bool is_host(const char *);
76bool is_addr(const char *); 76bool is_addr(const char *);
77int dns_lookup(const char *, struct sockaddr_storage *, int); 77bool dns_lookup(const char *, struct sockaddr_storage *, int);
78void host_or_die(const char *str); 78void host_or_die(const char *str);
79#define resolve_host_or_addr(addr, family) dns_lookup(addr, NULL, family) 79#define resolve_host_or_addr(addr, family) dns_lookup(addr, NULL, family)
80#define is_inet_addr(addr) resolve_host_or_addr(addr, AF_INET) 80#define is_inet_addr(addr) resolve_host_or_addr(addr, AF_INET)
@@ -86,8 +86,8 @@ void host_or_die(const char *str);
86#endif 86#endif
87 87
88extern unsigned int socket_timeout; 88extern unsigned int socket_timeout;
89extern unsigned int socket_timeout_state; 89extern mp_state_enum socket_timeout_state;
90extern int econn_refuse_state; 90extern mp_state_enum econn_refuse_state;
91extern bool was_refused; 91extern bool was_refused;
92extern int address_family; 92extern int address_family;
93 93
@@ -106,12 +106,12 @@ void socket_timeout_alarm_handler(int) __attribute__((noreturn));
106# define MP_TLSv1_1_OR_NEWER 9 106# define MP_TLSv1_1_OR_NEWER 9
107# define MP_TLSv1_2_OR_NEWER 10 107# define MP_TLSv1_2_OR_NEWER 10
108/* maybe this could be merged with the above np_net_connect, via some flags */ 108/* maybe this could be merged with the above np_net_connect, via some flags */
109int np_net_ssl_init(int sd); 109int np_net_ssl_init(int socket);
110int np_net_ssl_init_with_hostname(int sd, char *host_name); 110int np_net_ssl_init_with_hostname(int socket, char *host_name);
111int np_net_ssl_init_with_hostname_and_version(int sd, char *host_name, int version); 111int np_net_ssl_init_with_hostname_and_version(int socket, char *host_name, int version);
112int np_net_ssl_init_with_hostname_version_and_cert(int sd, char *host_name, int version, char *cert, 112int np_net_ssl_init_with_hostname_version_and_cert(int socket, char *host_name, int version,
113 char *privkey); 113 char *cert, char *privkey);
114void np_net_ssl_cleanup(); 114void np_net_ssl_cleanup(void);
115int np_net_ssl_write(const void *buf, int num); 115int np_net_ssl_write(const void *buf, int num);
116int np_net_ssl_read(void *buf, int num); 116int np_net_ssl_read(void *buf, int num);
117mp_state_enum np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit); 117mp_state_enum np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit);
diff --git a/plugins/picohttpparser/picohttpparser.c b/plugins/picohttpparser/picohttpparser.c
index 2ae92d66..e87388b0 100644
--- a/plugins/picohttpparser/picohttpparser.c
+++ b/plugins/picohttpparser/picohttpparser.c
@@ -50,59 +50,61 @@
50# define ALIGNED(n) __attribute__((aligned(n))) 50# define ALIGNED(n) __attribute__((aligned(n)))
51#endif 51#endif
52 52
53#define IS_PRINTABLE_ASCII(c) ((unsigned char)(c)-040u < 0137u) 53#define IS_PRINTABLE_ASCII(c) ((unsigned char)(c) - 040u < 0137u)
54 54
55#define CHECK_EOF() \ 55#define CHECK_EOF() \
56 if (buf == buf_end) { \ 56 if (buf == buf_end) { \
57 *ret = -2; \ 57 *ret = -2; \
58 return NULL; \ 58 return NULL; \
59 } 59 }
60 60
61#define EXPECT_CHAR_NO_CHECK(ch) \ 61#define EXPECT_CHAR_NO_CHECK(ch) \
62 if (*buf++ != ch) { \ 62 if (*buf++ != ch) { \
63 *ret = -1; \ 63 *ret = -1; \
64 return NULL; \ 64 return NULL; \
65 } 65 }
66 66
67#define EXPECT_CHAR(ch) \ 67#define EXPECT_CHAR(ch) \
68 CHECK_EOF(); \ 68 CHECK_EOF(); \
69 EXPECT_CHAR_NO_CHECK(ch); 69 EXPECT_CHAR_NO_CHECK(ch);
70 70
71#define ADVANCE_TOKEN(tok, toklen) \ 71#define ADVANCE_TOKEN(tok, toklen) \
72 do { \ 72 do { \
73 const char *tok_start = buf; \ 73 const char *tok_start = buf; \
74 static const char ALIGNED(16) ranges2[16] = "\000\040\177\177"; \ 74 static const char ALIGNED(16) ranges2[16] = "\000\040\177\177"; \
75 int found2; \ 75 int found2; \
76 buf = findchar_fast(buf, buf_end, ranges2, 4, &found2); \ 76 buf = findchar_fast(buf, buf_end, ranges2, 4, &found2); \
77 if (!found2) { \ 77 if (!found2) { \
78 CHECK_EOF(); \ 78 CHECK_EOF(); \
79 } \ 79 } \
80 while (1) { \ 80 while (1) { \
81 if (*buf == ' ') { \ 81 if (*buf == ' ') { \
82 break; \ 82 break; \
83 } else if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { \ 83 } else if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { \
84 if ((unsigned char)*buf < '\040' || *buf == '\177') { \ 84 if ((unsigned char)*buf < '\040' || *buf == '\177') { \
85 *ret = -1; \ 85 *ret = -1; \
86 return NULL; \ 86 return NULL; \
87 } \ 87 } \
88 } \ 88 } \
89 ++buf; \ 89 ++buf; \
90 CHECK_EOF(); \ 90 CHECK_EOF(); \
91 } \ 91 } \
92 tok = tok_start; \ 92 tok = tok_start; \
93 toklen = buf - tok_start; \ 93 toklen = buf - tok_start; \
94 } while (0) 94 } while (0)
95 95
96static const char *token_char_map = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" 96static const char *token_char_map =
97 "\0\1\0\1\1\1\1\1\0\0\1\1\0\1\1\0\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0" 97 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
98 "\0\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\1\1" 98 "\0\1\0\1\1\1\1\1\0\0\1\1\0\1\1\0\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0"
99 "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\1\0\1\0" 99 "\0\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\1\1"
100 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" 100 "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\1\0\1\0"
101 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" 101 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
102 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" 102 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
103 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; 103 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
104 104 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
105static const char *findchar_fast(const char *buf, const char *buf_end, const char *ranges, size_t ranges_size, int *found) { 105
106static const char *findchar_fast(const char *buf, const char *buf_end, const char *ranges,
107 size_t ranges_size, int *found) {
106 *found = 0; 108 *found = 0;
107#if __SSE4_2__ 109#if __SSE4_2__
108 if (likely(buf_end - buf >= 16)) { 110 if (likely(buf_end - buf >= 16)) {
@@ -111,7 +113,8 @@ static const char *findchar_fast(const char *buf, const char *buf_end, const cha
111 size_t left = (buf_end - buf) & ~15; 113 size_t left = (buf_end - buf) & ~15;
112 do { 114 do {
113 __m128i b16 = _mm_loadu_si128((const __m128i *)buf); 115 __m128i b16 = _mm_loadu_si128((const __m128i *)buf);
114 int r = _mm_cmpestri(ranges16, ranges_size, b16, 16, _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_RANGES | _SIDD_UBYTE_OPS); 116 int r = _mm_cmpestri(ranges16, ranges_size, b16, 16,
117 _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_RANGES | _SIDD_UBYTE_OPS);
115 if (unlikely(r != 16)) { 118 if (unlikely(r != 16)) {
116 buf += r; 119 buf += r;
117 *found = 1; 120 *found = 1;
@@ -130,25 +133,29 @@ static const char *findchar_fast(const char *buf, const char *buf_end, const cha
130 return buf; 133 return buf;
131} 134}
132 135
133static const char *get_token_to_eol(const char *buf, const char *buf_end, const char **token, size_t *token_len, int *ret) { 136static const char *get_token_to_eol(const char *buf, const char *buf_end, const char **token,
137 size_t *token_len, int *ret) {
134 const char *token_start = buf; 138 const char *token_start = buf;
135 139
136#ifdef __SSE4_2__ 140#ifdef __SSE4_2__
137 static const char ALIGNED(16) ranges1[16] = "\0\010" /* allow HT */ 141 static const char ALIGNED(16) ranges1[16] =
138 "\012\037" /* allow SP and up to but not including DEL */ 142 "\0\010" /* allow HT */
139 "\177\177"; /* allow chars w. MSB set */ 143 "\012\037" /* allow SP and up to but not including DEL */
144 "\177\177"; /* allow chars w. MSB set */
140 int found; 145 int found;
141 buf = findchar_fast(buf, buf_end, ranges1, 6, &found); 146 buf = findchar_fast(buf, buf_end, ranges1, 6, &found);
142 if (found) 147 if (found) {
143 goto FOUND_CTL; 148 goto FOUND_CTL;
149 }
144#else 150#else
145 /* find non-printable char within the next 8 bytes, this is the hottest code; manually inlined */ 151 /* find non-printable char within the next 8 bytes, this is the hottest code; manually inlined
152 */
146 while (likely(buf_end - buf >= 8)) { 153 while (likely(buf_end - buf >= 8)) {
147# define DOIT() \ 154# define DOIT() \
148 do { \ 155 do { \
149 if (unlikely(!IS_PRINTABLE_ASCII(*buf))) \ 156 if (unlikely(!IS_PRINTABLE_ASCII(*buf))) \
150 goto NonPrintable; \ 157 goto NonPrintable; \
151 ++buf; \ 158 ++buf; \
152 } while (0) 159 } while (0)
153 DOIT(); 160 DOIT();
154 DOIT(); 161 DOIT();
@@ -161,7 +168,8 @@ static const char *get_token_to_eol(const char *buf, const char *buf_end, const
161# undef DOIT 168# undef DOIT
162 continue; 169 continue;
163 NonPrintable: 170 NonPrintable:
164 if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { 171 if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) ||
172 unlikely(*buf == '\177')) {
165 goto FOUND_CTL; 173 goto FOUND_CTL;
166 } 174 }
167 ++buf; 175 ++buf;
@@ -170,7 +178,8 @@ static const char *get_token_to_eol(const char *buf, const char *buf_end, const
170 for (;; ++buf) { 178 for (;; ++buf) {
171 CHECK_EOF(); 179 CHECK_EOF();
172 if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { 180 if (unlikely(!IS_PRINTABLE_ASCII(*buf))) {
173 if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { 181 if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) ||
182 unlikely(*buf == '\177')) {
174 goto FOUND_CTL; 183 goto FOUND_CTL;
175 } 184 }
176 } 185 }
@@ -219,27 +228,28 @@ static const char *is_complete(const char *buf, const char *buf_end, size_t last
219 return NULL; 228 return NULL;
220} 229}
221 230
222#define PARSE_INT(valp_, mul_) \ 231#define PARSE_INT(valp_, mul_) \
223 if (*buf < '0' || '9' < *buf) { \ 232 if (*buf < '0' || '9' < *buf) { \
224 buf++; \ 233 buf++; \
225 *ret = -1; \ 234 *ret = -1; \
226 return NULL; \ 235 return NULL; \
227 } \ 236 } \
228 *(valp_) = (mul_) * (*buf++ - '0'); 237 *(valp_) = (mul_) * (*buf++ - '0');
229 238
230#define PARSE_INT_3(valp_) \ 239#define PARSE_INT_3(valp_) \
231 do { \ 240 do { \
232 int res_ = 0; \ 241 int res_ = 0; \
233 PARSE_INT(&res_, 100) \ 242 PARSE_INT(&res_, 100) \
234 *valp_ = res_; \ 243 *valp_ = res_; \
235 PARSE_INT(&res_, 10) \ 244 PARSE_INT(&res_, 10) \
236 *valp_ += res_; \ 245 *valp_ += res_; \
237 PARSE_INT(&res_, 1) \ 246 PARSE_INT(&res_, 1) \
238 *valp_ += res_; \ 247 *valp_ += res_; \
239 } while (0) 248 } while (0)
240 249
241/* returned pointer is always within [buf, buf_end), or null */ 250/* returned pointer is always within [buf, buf_end), or null */
242static const char *parse_http_version(const char *buf, const char *buf_end, int *major_version, int *minor_version, int *ret) { 251static const char *parse_http_version(const char *buf, const char *buf_end, int *major_version,
252 int *minor_version, int *ret) {
243 /* we want at least [HTTP/1.<two chars>] to try to parse */ 253 /* we want at least [HTTP/1.<two chars>] to try to parse */
244 if (buf_end - buf < 9) { 254 if (buf_end - buf < 9) {
245 *ret = -2; 255 *ret = -2;
@@ -260,8 +270,8 @@ static const char *parse_http_version(const char *buf, const char *buf_end, int
260 return buf; 270 return buf;
261} 271}
262 272
263static const char *parse_headers(const char *buf, const char *buf_end, struct phr_header *headers, size_t *num_headers, size_t max_headers, 273static const char *parse_headers(const char *buf, const char *buf_end, struct phr_header *headers,
264 int *ret) { 274 size_t *num_headers, size_t max_headers, int *ret) {
265 for (;; ++*num_headers) { 275 for (;; ++*num_headers) {
266 CHECK_EOF(); 276 CHECK_EOF();
267 if (*buf == '\015') { 277 if (*buf == '\015') {
@@ -337,9 +347,10 @@ static const char *parse_headers(const char *buf, const char *buf_end, struct ph
337 return buf; 347 return buf;
338} 348}
339 349
340static const char *parse_request(const char *buf, const char *buf_end, const char **method, size_t *method_len, const char **path, 350static const char *parse_request(const char *buf, const char *buf_end, const char **method,
341 size_t *path_len, int *major_version, int *minor_version, struct phr_header *headers, size_t *num_headers, 351 size_t *method_len, const char **path, size_t *path_len,
342 size_t max_headers, int *ret) { 352 int *major_version, int *minor_version, struct phr_header *headers,
353 size_t *num_headers, size_t max_headers, int *ret) {
343 /* skip first empty line (some clients add CRLF after POST content) */ 354 /* skip first empty line (some clients add CRLF after POST content) */
344 CHECK_EOF(); 355 CHECK_EOF();
345 if (*buf == '\015') { 356 if (*buf == '\015') {
@@ -378,8 +389,9 @@ static const char *parse_request(const char *buf, const char *buf_end, const cha
378 return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); 389 return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret);
379} 390}
380 391
381int phr_parse_request(const char *buf_start, size_t len, const char **method, size_t *method_len, const char **path, size_t *path_len, 392int phr_parse_request(const char *buf_start, size_t len, const char **method, size_t *method_len,
382 int *major_version, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len) { 393 const char **path, size_t *path_len, int *major_version, int *minor_version,
394 struct phr_header *headers, size_t *num_headers, size_t last_len) {
383 const char *buf = buf_start, *buf_end = buf_start + len; 395 const char *buf = buf_start, *buf_end = buf_start + len;
384 size_t max_headers = *num_headers; 396 size_t max_headers = *num_headers;
385 int r; 397 int r;
@@ -398,17 +410,18 @@ int phr_parse_request(const char *buf_start, size_t len, const char **method, si
398 return r; 410 return r;
399 } 411 }
400 412
401 if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, major_version, minor_version, headers, num_headers, 413 if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, major_version,
402 max_headers, &r)) == NULL) { 414 minor_version, headers, num_headers, max_headers, &r)) == NULL) {
403 return r; 415 return r;
404 } 416 }
405 417
406 return (int)(buf - buf_start); 418 return (int)(buf - buf_start);
407} 419}
408 420
409static const char *parse_response(const char *buf, const char *buf_end, int *major_version, int *minor_version, int *status, 421static const char *parse_response(const char *buf, const char *buf_end, int *major_version,
410 const char **msg, size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t max_headers, 422 int *minor_version, int *status, const char **msg,
411 int *ret) { 423 size_t *msg_len, struct phr_header *headers, size_t *num_headers,
424 size_t max_headers, int *ret) {
412 /* parse "HTTP/1.x" */ 425 /* parse "HTTP/1.x" */
413 if ((buf = parse_http_version(buf, buf_end, major_version, minor_version, ret)) == NULL) { 426 if ((buf = parse_http_version(buf, buf_end, major_version, minor_version, ret)) == NULL) {
414 return NULL; 427 return NULL;
@@ -421,7 +434,8 @@ static const char *parse_response(const char *buf, const char *buf_end, int *maj
421 do { 434 do {
422 ++buf; 435 ++buf;
423 } while (*buf == ' '); 436 } while (*buf == ' ');
424 /* parse status code, we want at least [:digit:][:digit:][:digit:]<other char> to try to parse */ 437 /* parse status code, we want at least [:digit:][:digit:][:digit:]<other char> to try to parse
438 */
425 if (buf_end - buf < 4) { 439 if (buf_end - buf < 4) {
426 *ret = -2; 440 *ret = -2;
427 return NULL; 441 return NULL;
@@ -449,8 +463,9 @@ static const char *parse_response(const char *buf, const char *buf_end, int *maj
449 return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); 463 return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret);
450} 464}
451 465
452int phr_parse_response(const char *buf_start, size_t len, int *major_version, int *minor_version, int *status, const char **msg, 466int phr_parse_response(const char *buf_start, size_t len, int *major_version, int *minor_version,
453 size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t last_len) { 467 int *status, const char **msg, size_t *msg_len, struct phr_header *headers,
468 size_t *num_headers, size_t last_len) {
454 const char *buf = buf_start, *buf_end = buf + len; 469 const char *buf = buf_start, *buf_end = buf + len;
455 size_t max_headers = *num_headers; 470 size_t max_headers = *num_headers;
456 int r; 471 int r;
@@ -468,15 +483,16 @@ int phr_parse_response(const char *buf_start, size_t len, int *major_version, in
468 return r; 483 return r;
469 } 484 }
470 485
471 if ((buf = parse_response(buf, buf_end, major_version, minor_version, status, msg, msg_len, headers, num_headers, max_headers, &r)) == 486 if ((buf = parse_response(buf, buf_end, major_version, minor_version, status, msg, msg_len,
472 NULL) { 487 headers, num_headers, max_headers, &r)) == NULL) {
473 return r; 488 return r;
474 } 489 }
475 490
476 return (int)(buf - buf_start); 491 return (int)(buf - buf_start);
477} 492}
478 493
479int phr_parse_headers(const char *buf_start, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len) { 494int phr_parse_headers(const char *buf_start, size_t len, struct phr_header *headers,
495 size_t *num_headers, size_t last_len) {
480 const char *buf = buf_start, *buf_end = buf + len; 496 const char *buf = buf_start, *buf_end = buf + len;
481 size_t max_headers = *num_headers; 497 size_t max_headers = *num_headers;
482 int r; 498 int r;
@@ -526,8 +542,9 @@ ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_
526 case CHUNKED_IN_CHUNK_SIZE: 542 case CHUNKED_IN_CHUNK_SIZE:
527 for (;; ++src) { 543 for (;; ++src) {
528 int v; 544 int v;
529 if (src == bufsz) 545 if (src == bufsz) {
530 goto Exit; 546 goto Exit;
547 }
531 if ((v = decode_hex(buf[src])) == -1) { 548 if ((v = decode_hex(buf[src])) == -1) {
532 if (decoder->_hex_count == 0) { 549 if (decoder->_hex_count == 0) {
533 ret = -1; 550 ret = -1;
@@ -548,10 +565,12 @@ ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_
548 case CHUNKED_IN_CHUNK_EXT: 565 case CHUNKED_IN_CHUNK_EXT:
549 /* RFC 7230 A.2 "Line folding in chunk extensions is disallowed" */ 566 /* RFC 7230 A.2 "Line folding in chunk extensions is disallowed" */
550 for (;; ++src) { 567 for (;; ++src) {
551 if (src == bufsz) 568 if (src == bufsz) {
552 goto Exit; 569 goto Exit;
553 if (buf[src] == '\012') 570 }
571 if (buf[src] == '\012') {
554 break; 572 break;
573 }
555 } 574 }
556 ++src; 575 ++src;
557 if (decoder->bytes_left_in_chunk == 0) { 576 if (decoder->bytes_left_in_chunk == 0) {
@@ -567,15 +586,17 @@ ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_
567 case CHUNKED_IN_CHUNK_DATA: { 586 case CHUNKED_IN_CHUNK_DATA: {
568 size_t avail = bufsz - src; 587 size_t avail = bufsz - src;
569 if (avail < decoder->bytes_left_in_chunk) { 588 if (avail < decoder->bytes_left_in_chunk) {
570 if (dst != src) 589 if (dst != src) {
571 memmove(buf + dst, buf + src, avail); 590 memmove(buf + dst, buf + src, avail);
591 }
572 src += avail; 592 src += avail;
573 dst += avail; 593 dst += avail;
574 decoder->bytes_left_in_chunk -= avail; 594 decoder->bytes_left_in_chunk -= avail;
575 goto Exit; 595 goto Exit;
576 } 596 }
577 if (dst != src) 597 if (dst != src) {
578 memmove(buf + dst, buf + src, decoder->bytes_left_in_chunk); 598 memmove(buf + dst, buf + src, decoder->bytes_left_in_chunk);
599 }
579 src += decoder->bytes_left_in_chunk; 600 src += decoder->bytes_left_in_chunk;
580 dst += decoder->bytes_left_in_chunk; 601 dst += decoder->bytes_left_in_chunk;
581 decoder->bytes_left_in_chunk = 0; 602 decoder->bytes_left_in_chunk = 0;
@@ -584,10 +605,12 @@ ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_
584 /* fallthru */ 605 /* fallthru */
585 case CHUNKED_IN_CHUNK_CRLF: 606 case CHUNKED_IN_CHUNK_CRLF:
586 for (;; ++src) { 607 for (;; ++src) {
587 if (src == bufsz) 608 if (src == bufsz) {
588 goto Exit; 609 goto Exit;
589 if (buf[src] != '\015') 610 }
611 if (buf[src] != '\015') {
590 break; 612 break;
613 }
591 } 614 }
592 if (buf[src] != '\012') { 615 if (buf[src] != '\012') {
593 ret = -1; 616 ret = -1;
@@ -598,21 +621,26 @@ ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_
598 break; 621 break;
599 case CHUNKED_IN_TRAILERS_LINE_HEAD: 622 case CHUNKED_IN_TRAILERS_LINE_HEAD:
600 for (;; ++src) { 623 for (;; ++src) {
601 if (src == bufsz) 624 if (src == bufsz) {
602 goto Exit; 625 goto Exit;
603 if (buf[src] != '\015') 626 }
627 if (buf[src] != '\015') {
604 break; 628 break;
629 }
605 } 630 }
606 if (buf[src++] == '\012') 631 if (buf[src++] == '\012') {
607 goto Complete; 632 goto Complete;
633 }
608 decoder->_state = CHUNKED_IN_TRAILERS_LINE_MIDDLE; 634 decoder->_state = CHUNKED_IN_TRAILERS_LINE_MIDDLE;
609 /* fallthru */ 635 /* fallthru */
610 case CHUNKED_IN_TRAILERS_LINE_MIDDLE: 636 case CHUNKED_IN_TRAILERS_LINE_MIDDLE:
611 for (;; ++src) { 637 for (;; ++src) {
612 if (src == bufsz) 638 if (src == bufsz) {
613 goto Exit; 639 goto Exit;
614 if (buf[src] == '\012') 640 }
641 if (buf[src] == '\012') {
615 break; 642 break;
643 }
616 } 644 }
617 ++src; 645 ++src;
618 decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; 646 decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD;
@@ -625,13 +653,16 @@ ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_
625Complete: 653Complete:
626 ret = bufsz - src; 654 ret = bufsz - src;
627Exit: 655Exit:
628 if (dst != src) 656 if (dst != src) {
629 memmove(buf + dst, buf + src, bufsz - src); 657 memmove(buf + dst, buf + src, bufsz - src);
658 }
630 *_bufsz = dst; 659 *_bufsz = dst;
631 return ret; 660 return ret;
632} 661}
633 662
634int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder) { return decoder->_state == CHUNKED_IN_CHUNK_DATA; } 663int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder) {
664 return decoder->_state == CHUNKED_IN_CHUNK_DATA;
665}
635 666
636#undef CHECK_EOF 667#undef CHECK_EOF
637#undef EXPECT_CHAR 668#undef EXPECT_CHAR
diff --git a/plugins/picohttpparser/picohttpparser.h b/plugins/picohttpparser/picohttpparser.h
index 8f13b36f..054c2812 100644
--- a/plugins/picohttpparser/picohttpparser.h
+++ b/plugins/picohttpparser/picohttpparser.h
@@ -30,7 +30,7 @@
30#include <sys/types.h> 30#include <sys/types.h>
31 31
32#ifdef _MSC_VER 32#ifdef _MSC_VER
33#define ssize_t intptr_t 33# define ssize_t intptr_t
34#endif 34#endif
35 35
36#ifdef __cplusplus 36#ifdef __cplusplus
@@ -40,30 +40,33 @@ extern "C" {
40/* contains name and value of a header (name == NULL if is a continuing line 40/* contains name and value of a header (name == NULL if is a continuing line
41 * of a multiline header */ 41 * of a multiline header */
42struct phr_header { 42struct phr_header {
43 const char *name; 43 const char *name;
44 size_t name_len; 44 size_t name_len;
45 const char *value; 45 const char *value;
46 size_t value_len; 46 size_t value_len;
47}; 47};
48 48
49/* returns number of bytes consumed if successful, -2 if request is partial, 49/* returns number of bytes consumed if successful, -2 if request is partial,
50 * -1 if failed */ 50 * -1 if failed */
51int phr_parse_request(const char *buf, size_t len, const char **method, size_t *method_len, const char **path, size_t *path_len, 51int phr_parse_request(const char *buf, size_t len, const char **method, size_t *method_len,
52 int *major_version, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len); 52 const char **path, size_t *path_len, int *major_version, int *minor_version,
53 struct phr_header *headers, size_t *num_headers, size_t last_len);
53 54
54/* ditto */ 55/* ditto */
55int phr_parse_response(const char *_buf, size_t len, int *major_version, int *minor_version, int *status, const char **msg, size_t *msg_len, 56int phr_parse_response(const char *_buf, size_t len, int *major_version, int *minor_version,
56 struct phr_header *headers, size_t *num_headers, size_t last_len); 57 int *status, const char **msg, size_t *msg_len, struct phr_header *headers,
58 size_t *num_headers, size_t last_len);
57 59
58/* ditto */ 60/* ditto */
59int phr_parse_headers(const char *buf, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len); 61int phr_parse_headers(const char *buf, size_t len, struct phr_header *headers, size_t *num_headers,
62 size_t last_len);
60 63
61/* should be zero-filled before start */ 64/* should be zero-filled before start */
62struct phr_chunked_decoder { 65struct phr_chunked_decoder {
63 size_t bytes_left_in_chunk; /* number of bytes left in current chunk */ 66 size_t bytes_left_in_chunk; /* number of bytes left in current chunk */
64 char consume_trailer; /* if trailing headers should be consumed */ 67 char consume_trailer; /* if trailing headers should be consumed */
65 char _hex_count; 68 char _hex_count;
66 char _state; 69 char _state;
67}; 70};
68 71
69/* the function rewrites the buffer given as (buf, bufsz) removing the chunked- 72/* the function rewrites the buffer given as (buf, bufsz) removing the chunked-
diff --git a/plugins/popen.c b/plugins/popen.c
index cfe930b6..c596d1e0 100644
--- a/plugins/popen.c
+++ b/plugins/popen.c
@@ -68,7 +68,7 @@ void popen_timeout_alarm_handler(int /*signo*/);
68#endif 68#endif
69 69
70#ifndef WIFEXITED 70#ifndef WIFEXITED
71# define WIFEXITED(stat_val) (((stat_val)&255) == 0) 71# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
72#endif 72#endif
73 73
74/* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */ 74/* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
@@ -96,24 +96,28 @@ FILE *spopen(const char *cmdstring) {
96 env[1] = NULL; 96 env[1] = NULL;
97 97
98 /* if no command was passed, return with no error */ 98 /* if no command was passed, return with no error */
99 if (cmdstring == NULL) 99 if (cmdstring == NULL) {
100 return (NULL); 100 return (NULL);
101 }
101 102
102 char *cmd = NULL; 103 char *cmd = NULL;
103 /* make copy of command string so strtok() doesn't silently modify it */ 104 /* make copy of command string so strtok() doesn't silently modify it */
104 /* (the calling program may want to access it later) */ 105 /* (the calling program may want to access it later) */
105 cmd = malloc(strlen(cmdstring) + 1); 106 cmd = malloc(strlen(cmdstring) + 1);
106 if (cmd == NULL) 107 if (cmd == NULL) {
107 return NULL; 108 return NULL;
109 }
108 strcpy(cmd, cmdstring); 110 strcpy(cmd, cmdstring);
109 111
110 /* This is not a shell, so we don't handle "???" */ 112 /* This is not a shell, so we don't handle "???" */
111 if (strstr(cmdstring, "\"")) 113 if (strstr(cmdstring, "\"")) {
112 return NULL; 114 return NULL;
115 }
113 116
114 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */ 117 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
115 if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) 118 if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) {
116 return NULL; 119 return NULL;
120 }
117 121
118 int argc; 122 int argc;
119 char **argv = NULL; 123 char **argv = NULL;
@@ -140,15 +144,17 @@ FILE *spopen(const char *cmdstring) {
140 144
141 if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */ 145 if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */
142 str++; 146 str++;
143 if (!strstr(str, "'")) 147 if (!strstr(str, "'")) {
144 return NULL; /* balanced? */ 148 return NULL; /* balanced? */
149 }
145 cmd = 1 + strstr(str, "'"); 150 cmd = 1 + strstr(str, "'");
146 str[strcspn(str, "'")] = 0; 151 str[strcspn(str, "'")] = 0;
147 } else if (strcspn(str, "'") < strcspn(str, " \t\r\n")) { 152 } else if (strcspn(str, "'") < strcspn(str, " \t\r\n")) {
148 /* handle --option='foo bar' strings */ 153 /* handle --option='foo bar' strings */
149 char *tmp = str + strcspn(str, "'") + 1; 154 char *tmp = str + strcspn(str, "'") + 1;
150 if (!strstr(tmp, "'")) 155 if (!strstr(tmp, "'")) {
151 return NULL; /* balanced? */ 156 return NULL; /* balanced? */
157 }
152 tmp += strcspn(tmp, "'") + 1; 158 tmp += strcspn(tmp, "'") + 1;
153 *tmp = 0; 159 *tmp = 0;
154 cmd = tmp + 1; 160 cmd = tmp + 1;
@@ -161,8 +167,9 @@ FILE *spopen(const char *cmdstring) {
161 } 167 }
162 } 168 }
163 169
164 if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) 170 if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) {
165 cmd = NULL; 171 cmd = NULL;
172 }
166 173
167 argv[i++] = str; 174 argv[i++] = str;
168 } 175 }
@@ -171,22 +178,26 @@ FILE *spopen(const char *cmdstring) {
171 long maxfd = mp_open_max(); 178 long maxfd = mp_open_max();
172 179
173 if (childpid == NULL) { /* first time through */ 180 if (childpid == NULL) { /* first time through */
174 if ((childpid = calloc((size_t)maxfd, sizeof(pid_t))) == NULL) 181 if ((childpid = calloc((size_t)maxfd, sizeof(pid_t))) == NULL) {
175 return (NULL); 182 return (NULL);
183 }
176 } 184 }
177 185
178 if (child_stderr_array == NULL) { /* first time through */ 186 if (child_stderr_array == NULL) { /* first time through */
179 if ((child_stderr_array = calloc((size_t)maxfd, sizeof(int))) == NULL) 187 if ((child_stderr_array = calloc((size_t)maxfd, sizeof(int))) == NULL) {
180 return (NULL); 188 return (NULL);
189 }
181 } 190 }
182 191
183 int pfd[2]; 192 int pfd[2];
184 if (pipe(pfd) < 0) 193 if (pipe(pfd) < 0) {
185 return (NULL); /* errno set by pipe() */ 194 return (NULL); /* errno set by pipe() */
195 }
186 196
187 int pfderr[2]; 197 int pfderr[2];
188 if (pipe(pfderr) < 0) 198 if (pipe(pfderr) < 0) {
189 return (NULL); /* errno set by pipe() */ 199 return (NULL); /* errno set by pipe() */
200 }
190 201
191#ifdef REDHAT_SPOPEN_ERROR 202#ifdef REDHAT_SPOPEN_ERROR
192 if (signal(SIGCHLD, popen_sigchld_handler) == SIG_ERR) { 203 if (signal(SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
@@ -195,8 +206,9 @@ FILE *spopen(const char *cmdstring) {
195#endif 206#endif
196 207
197 pid_t pid; 208 pid_t pid;
198 if ((pid = fork()) < 0) 209 if ((pid = fork()) < 0) {
199 return (NULL); /* errno set by fork() */ 210 return (NULL); /* errno set by fork() */
211 }
200 212
201 if (pid == 0) { /* child */ 213 if (pid == 0) { /* child */
202 close(pfd[0]); 214 close(pfd[0]);
@@ -210,17 +222,20 @@ FILE *spopen(const char *cmdstring) {
210 close(pfderr[1]); 222 close(pfderr[1]);
211 } 223 }
212 /* close all descriptors in childpid[] */ 224 /* close all descriptors in childpid[] */
213 for (i = 0; i < maxfd; i++) 225 for (i = 0; i < maxfd; i++) {
214 if (childpid[i] > 0) 226 if (childpid[i] > 0) {
215 close(i); 227 close(i);
228 }
229 }
216 230
217 execve(argv[0], argv, env); 231 execve(argv[0], argv, env);
218 _exit(0); 232 _exit(0);
219 } 233 }
220 234
221 close(pfd[1]); /* parent */ 235 close(pfd[1]); /* parent */
222 if ((child_process = fdopen(pfd[0], "r")) == NULL) 236 if ((child_process = fdopen(pfd[0], "r")) == NULL) {
223 return (NULL); 237 return (NULL);
238 }
224 close(pfderr[1]); 239 close(pfderr[1]);
225 240
226 childpid[fileno(child_process)] = pid; /* remember child pid for this fd */ 241 childpid[fileno(child_process)] = pid; /* remember child pid for this fd */
@@ -229,17 +244,20 @@ FILE *spopen(const char *cmdstring) {
229} 244}
230 245
231int spclose(FILE *fp) { 246int spclose(FILE *fp) {
232 if (childpid == NULL) 247 if (childpid == NULL) {
233 return (1); /* popen() has never been called */ 248 return (1); /* popen() has never been called */
249 }
234 250
235 pid_t pid; 251 pid_t pid;
236 int fd = fileno(fp); 252 int fd = fileno(fp);
237 if ((pid = childpid[fd]) == 0) 253 if ((pid = childpid[fd]) == 0) {
238 return (1); /* fp wasn't opened by popen() */ 254 return (1); /* fp wasn't opened by popen() */
255 }
239 256
240 childpid[fd] = 0; 257 childpid[fd] = 0;
241 if (fclose(fp) == EOF) 258 if (fclose(fp) == EOF) {
242 return (1); 259 return (1);
260 }
243 261
244#ifdef REDHAT_SPOPEN_ERROR 262#ifdef REDHAT_SPOPEN_ERROR
245 while (!childtermd) 263 while (!childtermd)
@@ -247,20 +265,24 @@ int spclose(FILE *fp) {
247#endif 265#endif
248 266
249 int status; 267 int status;
250 while (waitpid(pid, &status, 0) < 0) 268 while (waitpid(pid, &status, 0) < 0) {
251 if (errno != EINTR) 269 if (errno != EINTR) {
252 return (1); /* error other than EINTR from waitpid() */ 270 return (1); /* error other than EINTR from waitpid() */
271 }
272 }
253 273
254 if (WIFEXITED(status)) 274 if (WIFEXITED(status)) {
255 return (WEXITSTATUS(status)); /* return child's termination status */ 275 return (WEXITSTATUS(status)); /* return child's termination status */
276 }
256 277
257 return (1); 278 return (1);
258} 279}
259 280
260#ifdef REDHAT_SPOPEN_ERROR 281#ifdef REDHAT_SPOPEN_ERROR
261void popen_sigchld_handler(int signo) { 282void popen_sigchld_handler(int signo) {
262 if (signo == SIGCHLD) 283 if (signo == SIGCHLD) {
263 childtermd = 1; 284 childtermd = 1;
285 }
264} 286}
265#endif 287#endif
266 288
diff --git a/plugins/popen.h b/plugins/popen.h
index 1ea69632..e318ce25 100644
--- a/plugins/popen.h
+++ b/plugins/popen.h
@@ -1,13 +1,13 @@
1/****************************************************************************** 1/******************************************************************************
2* 2 *
3* 3 *
4*****************************************************************************/ 4 *****************************************************************************/
5 5
6FILE *spopen (const char *); 6FILE *spopen(const char *);
7int spclose (FILE *); 7int spclose(FILE *);
8void popen_timeout_alarm_handler (int); 8void popen_timeout_alarm_handler(int);
9 9
10pid_t *childpid=NULL; 10pid_t *childpid = NULL;
11int *child_stderr_array=NULL; 11int *child_stderr_array = NULL;
12FILE *child_process=NULL; 12FILE *child_process = NULL;
13FILE *child_stderr=NULL; 13FILE *child_stderr = NULL;
diff --git a/plugins/runcmd.c b/plugins/runcmd.c
index 4429ceb0..7c583b85 100644
--- a/plugins/runcmd.c
+++ b/plugins/runcmd.c
@@ -53,7 +53,7 @@
53#endif 53#endif
54 54
55#ifndef WIFEXITED 55#ifndef WIFEXITED
56# define WIFEXITED(stat_val) (((stat_val)&255) == 0) 56# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
57#endif 57#endif
58 58
59/* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */ 59/* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
@@ -87,8 +87,9 @@ extern void die(int, const char *, ...) __attribute__((__noreturn__, __format__(
87 * through this api and thus achieve async-safeness throughout the api */ 87 * through this api and thus achieve async-safeness throughout the api */
88void np_runcmd_init(void) { 88void np_runcmd_init(void) {
89 long maxfd = mp_open_max(); 89 long maxfd = mp_open_max();
90 if (!np_pids) 90 if (!np_pids) {
91 np_pids = calloc(maxfd, sizeof(pid_t)); 91 np_pids = calloc(maxfd, sizeof(pid_t));
92 }
92} 93}
93 94
94/* Start running a command */ 95/* Start running a command */
@@ -106,8 +107,9 @@ static int np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) {
106 107
107 int i = 0; 108 int i = 0;
108 109
109 if (!np_pids) 110 if (!np_pids) {
110 NP_RUNCMD_INIT; 111 NP_RUNCMD_INIT;
112 }
111 113
112 env[0] = strdup("LC_ALL=C"); 114 env[0] = strdup("LC_ALL=C");
113 env[1] = NULL; 115 env[1] = NULL;
@@ -115,18 +117,21 @@ static int np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) {
115 /* make copy of command string so strtok() doesn't silently modify it */ 117 /* make copy of command string so strtok() doesn't silently modify it */
116 /* (the calling program may want to access it later) */ 118 /* (the calling program may want to access it later) */
117 cmdlen = strlen(cmdstring); 119 cmdlen = strlen(cmdstring);
118 if ((cmd = malloc(cmdlen + 1)) == NULL) 120 if ((cmd = malloc(cmdlen + 1)) == NULL) {
119 return -1; 121 return -1;
122 }
120 memcpy(cmd, cmdstring, cmdlen); 123 memcpy(cmd, cmdstring, cmdlen);
121 cmd[cmdlen] = '\0'; 124 cmd[cmdlen] = '\0';
122 125
123 /* This is not a shell, so we don't handle "???" */ 126 /* This is not a shell, so we don't handle "???" */
124 if (strstr(cmdstring, "\"")) 127 if (strstr(cmdstring, "\"")) {
125 return -1; 128 return -1;
129 }
126 130
127 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */ 131 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
128 if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) 132 if (strstr(cmdstring, " ' ") || strstr(cmdstring, "'''")) {
129 return -1; 133 return -1;
134 }
130 135
131 /* each arg must be whitespace-separated, so args can be a maximum 136 /* each arg must be whitespace-separated, so args can be a maximum
132 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */ 137 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
@@ -145,8 +150,9 @@ static int np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) {
145 150
146 if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */ 151 if (strstr(str, "'") == str) { /* handle SIMPLE quoted strings */
147 str++; 152 str++;
148 if (!strstr(str, "'")) 153 if (!strstr(str, "'")) {
149 return -1; /* balanced? */ 154 return -1; /* balanced? */
155 }
150 cmd = 1 + strstr(str, "'"); 156 cmd = 1 + strstr(str, "'");
151 str[strcspn(str, "'")] = 0; 157 str[strcspn(str, "'")] = 0;
152 } else { 158 } else {
@@ -158,14 +164,16 @@ static int np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) {
158 } 164 }
159 } 165 }
160 166
161 if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) 167 if (cmd && strlen(cmd) == strspn(cmd, " \t\r\n")) {
162 cmd = NULL; 168 cmd = NULL;
169 }
163 170
164 argv[i++] = str; 171 argv[i++] = str;
165 } 172 }
166 173
167 if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0) 174 if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0) {
168 return -1; /* errno set by the failing function */ 175 return -1; /* errno set by the failing function */
176 }
169 177
170 /* child runs exceve() and _exit. */ 178 /* child runs exceve() and _exit. */
171 if (pid == 0) { 179 if (pid == 0) {
@@ -190,9 +198,11 @@ static int np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) {
190 * This is executed in a separate address space (pure child), 198 * This is executed in a separate address space (pure child),
191 * so we don't have to worry about async safety */ 199 * so we don't have to worry about async safety */
192 long maxfd = mp_open_max(); 200 long maxfd = mp_open_max();
193 for (i = 0; i < maxfd; i++) 201 for (i = 0; i < maxfd; i++) {
194 if (np_pids[i] > 0) 202 if (np_pids[i] > 0) {
195 close(i); 203 close(i);
204 }
205 }
196 206
197 execve(argv[0], argv, env); 207 execve(argv[0], argv, env);
198 _exit(STATE_UNKNOWN); 208 _exit(STATE_UNKNOWN);
@@ -215,17 +225,21 @@ static int np_runcmd_close(int fd) {
215 225
216 /* make sure this fd was opened by popen() */ 226 /* make sure this fd was opened by popen() */
217 long maxfd = mp_open_max(); 227 long maxfd = mp_open_max();
218 if (fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0) 228 if (fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0) {
219 return -1; 229 return -1;
230 }
220 231
221 np_pids[fd] = 0; 232 np_pids[fd] = 0;
222 if (close(fd) == -1) 233 if (close(fd) == -1) {
223 return -1; 234 return -1;
235 }
224 236
225 /* EINTR is ok (sort of), everything else is bad */ 237 /* EINTR is ok (sort of), everything else is bad */
226 while (waitpid(pid, &status, 0) < 0) 238 while (waitpid(pid, &status, 0) < 0) {
227 if (errno != EINTR) 239 if (errno != EINTR) {
228 return -1; 240 return -1;
241 }
242 }
229 243
230 /* return child's termination status */ 244 /* return child's termination status */
231 return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1; 245 return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
@@ -233,15 +247,18 @@ static int np_runcmd_close(int fd) {
233 247
234void runcmd_timeout_alarm_handler(int signo) { 248void runcmd_timeout_alarm_handler(int signo) {
235 249
236 if (signo == SIGALRM) 250 if (signo == SIGALRM) {
237 puts(_("CRITICAL - Plugin timed out while executing system call")); 251 puts(_("CRITICAL - Plugin timed out while executing system call"));
252 }
238 253
239 long maxfd = mp_open_max(); 254 long maxfd = mp_open_max();
240 if (np_pids) 255 if (np_pids) {
241 for (long int i = 0; i < maxfd; i++) { 256 for (long int i = 0; i < maxfd; i++) {
242 if (np_pids[i] != 0) 257 if (np_pids[i] != 0) {
243 kill(np_pids[i], SIGKILL); 258 kill(np_pids[i], SIGKILL);
259 }
244 } 260 }
261 }
245 262
246 exit(STATE_CRITICAL); 263 exit(STATE_CRITICAL);
247} 264}
@@ -270,15 +287,17 @@ static int np_fetch_output(int fd, output *op, int flags) {
270 287
271 /* some plugins may want to keep output unbroken, and some commands 288 /* some plugins may want to keep output unbroken, and some commands
272 * will yield no output, so return here for those */ 289 * will yield no output, so return here for those */
273 if (flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen) 290 if (flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen) {
274 return op->buflen; 291 return op->buflen;
292 }
275 293
276 /* and some may want both */ 294 /* and some may want both */
277 if (flags & RUNCMD_NO_ASSOC) { 295 if (flags & RUNCMD_NO_ASSOC) {
278 buf = malloc(op->buflen); 296 buf = malloc(op->buflen);
279 memcpy(buf, op->buf, op->buflen); 297 memcpy(buf, op->buf, op->buflen);
280 } else 298 } else {
281 buf = op->buf; 299 buf = op->buf;
300 }
282 301
283 op->line = NULL; 302 op->line = NULL;
284 op->lens = NULL; 303 op->lens = NULL;
@@ -299,8 +318,9 @@ static int np_fetch_output(int fd, output *op, int flags) {
299 op->line[lineno] = &buf[i]; 318 op->line[lineno] = &buf[i];
300 319
301 /* hop to next newline or end of buffer */ 320 /* hop to next newline or end of buffer */
302 while (buf[i] != '\n' && i < op->buflen) 321 while (buf[i] != '\n' && i < op->buflen) {
303 i++; 322 i++;
323 }
304 buf[i] = '\0'; 324 buf[i] = '\0';
305 325
306 /* calculate the string length using pointer difference */ 326 /* calculate the string length using pointer difference */
@@ -317,18 +337,23 @@ int np_runcmd(const char *cmd, output *out, output *err, int flags) {
317 int fd, pfd_out[2], pfd_err[2]; 337 int fd, pfd_out[2], pfd_err[2];
318 338
319 /* initialize the structs */ 339 /* initialize the structs */
320 if (out) 340 if (out) {
321 memset(out, 0, sizeof(output)); 341 memset(out, 0, sizeof(output));
322 if (err) 342 }
343 if (err) {
323 memset(err, 0, sizeof(output)); 344 memset(err, 0, sizeof(output));
345 }
324 346
325 if ((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1) 347 if ((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1) {
326 die(STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd); 348 die(STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
349 }
327 350
328 if (out) 351 if (out) {
329 out->lines = np_fetch_output(pfd_out[0], out, flags); 352 out->lines = np_fetch_output(pfd_out[0], out, flags);
330 if (err) 353 }
354 if (err) {
331 err->lines = np_fetch_output(pfd_err[0], err, flags); 355 err->lines = np_fetch_output(pfd_err[0], err, flags);
356 }
332 357
333 return np_runcmd_close(fd); 358 return np_runcmd_close(fd);
334} 359}
diff --git a/plugins/runcmd.h b/plugins/runcmd.h
index 2dcdadf0..63ce7b12 100644
--- a/plugins/runcmd.h
+++ b/plugins/runcmd.h
@@ -1,25 +1,25 @@
1/**************************************************************************** 1/****************************************************************************
2* 2 *
3* License: GPL 3 * License: GPL
4* Copyright (c) 2005 Monitoring Plugins Development Team 4 * Copyright (c) 2005 Monitoring Plugins Development Team
5* Author: Andreas Ericsson <ae@op5.se> 5 * Author: Andreas Ericsson <ae@op5.se>
6* 6 *
7* 7 *
8* This program is free software: you can redistribute it and/or modify 8 * This program is free software: you can redistribute it and/or modify
9* it under the terms of the GNU General Public License as published by 9 * it under the terms of the GNU General Public License as published by
10* the Free Software Foundation, either version 3 of the License, or 10 * the Free Software Foundation, either version 3 of the License, or
11* (at your option) any later version. 11 * (at your option) any later version.
12* 12 *
13* This program is distributed in the hope that it will be useful, 13 * This program is distributed in the hope that it will be useful,
14* but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16* GNU General Public License for more details. 16 * GNU General Public License for more details.
17* 17 *
18* You should have received a copy of the GNU General Public License 18 * You should have received a copy of the GNU General Public License
19* along with this program. If not, see <http://www.gnu.org/licenses/>. 19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20* 20 *
21* 21 *
22*****************************************************************************/ 22 *****************************************************************************/
23 23
24#ifndef NAGIOSPLUG_RUNCMD_H 24#ifndef NAGIOSPLUG_RUNCMD_H
25#define NAGIOSPLUG_RUNCMD_H 25#define NAGIOSPLUG_RUNCMD_H
@@ -29,8 +29,7 @@
29 29
30/** prototypes **/ 30/** prototypes **/
31int np_runcmd(const char *, output *, output *, int); 31int np_runcmd(const char *, output *, output *, int);
32void runcmd_timeout_alarm_handler(int) 32void runcmd_timeout_alarm_handler(int) __attribute__((__noreturn__));
33 __attribute__((__noreturn__));
34 33
35/* only multi-threaded plugins need to bother with this */ 34/* only multi-threaded plugins need to bother with this */
36void np_runcmd_init(void); 35void np_runcmd_init(void);
@@ -38,6 +37,6 @@ void np_runcmd_init(void);
38 37
39/* possible flags for np_runcmd()'s fourth argument */ 38/* possible flags for np_runcmd()'s fourth argument */
40#define RUNCMD_NO_ARRAYS 0x01 /* don't populate arrays at all */ 39#define RUNCMD_NO_ARRAYS 0x01 /* don't populate arrays at all */
41#define RUNCMD_NO_ASSOC 0x02 /* output.line won't point to buf */ 40#define RUNCMD_NO_ASSOC 0x02 /* output.line won't point to buf */
42 41
43#endif /* NAGIOSPLUG_RUNCMD_H */ 42#endif /* NAGIOSPLUG_RUNCMD_H */
diff --git a/plugins/sslutils.c b/plugins/sslutils.c
index 3ce6afed..0e6d7525 100644
--- a/plugins/sslutils.c
+++ b/plugins/sslutils.c
@@ -437,16 +437,14 @@ mp_subcheck mp_net_ssl_check_certificate(X509 *certificate, int days_till_exp_wa
437 xasprintf(&sc_cert.output, _("Certificate '%s' expired on %s"), commonName, timestamp); 437 xasprintf(&sc_cert.output, _("Certificate '%s' expired on %s"), commonName, timestamp);
438 sc_cert = mp_set_subcheck_state(sc_cert, STATE_CRITICAL); 438 sc_cert = mp_set_subcheck_state(sc_cert, STATE_CRITICAL);
439 } else if (days_left == 0) { 439 } else if (days_left == 0) {
440 xasprintf(&sc_cert.output, _("Certificate '%s' just expired (%s)"), commonName, 440 xasprintf(&sc_cert.output, _("Certificate '%s' just expired (%s)"), commonName, timestamp);
441 timestamp);
442 if (days_left > days_till_exp_crit) { 441 if (days_left > days_till_exp_crit) {
443 sc_cert = mp_set_subcheck_state(sc_cert, STATE_WARNING); 442 sc_cert = mp_set_subcheck_state(sc_cert, STATE_WARNING);
444 } else { 443 } else {
445 sc_cert = mp_set_subcheck_state(sc_cert, STATE_CRITICAL); 444 sc_cert = mp_set_subcheck_state(sc_cert, STATE_CRITICAL);
446 } 445 }
447 } else { 446 } else {
448 xasprintf(&sc_cert.output, _("Certificate '%s' will expire on %s"), commonName, 447 xasprintf(&sc_cert.output, _("Certificate '%s' will expire on %s"), commonName, timestamp);
449 timestamp);
450 sc_cert = mp_set_subcheck_state(sc_cert, STATE_OK); 448 sc_cert = mp_set_subcheck_state(sc_cert, STATE_OK);
451 } 449 }
452 X509_free(certificate); 450 X509_free(certificate);
diff --git a/plugins/tests/test_check_disk.c b/plugins/tests/test_check_disk.c
index 35c57bce..32b46c2d 100644
--- a/plugins/tests/test_check_disk.c
+++ b/plugins/tests/test_check_disk.c
@@ -21,7 +21,8 @@
21#include "../../tap/tap.h" 21#include "../../tap/tap.h"
22#include "regex.h" 22#include "regex.h"
23 23
24void np_test_mount_entry_regex(struct mount_entry *dummy_mount_list, char *regstr, int cflags, int expect, char *desc); 24void np_test_mount_entry_regex(struct mount_entry *dummy_mount_list, char *regstr, int cflags,
25 int expect, char *desc);
25 26
26int main(int argc, char **argv) { 27int main(int argc, char **argv) {
27 plan_tests(35); 28 plan_tests(35);
@@ -70,16 +71,26 @@ int main(int argc, char **argv) {
70 71
71 int cflags = REG_NOSUB | REG_EXTENDED; 72 int cflags = REG_NOSUB | REG_EXTENDED;
72 np_test_mount_entry_regex(dummy_mount_list, strdup("/"), cflags, 3, strdup("a")); 73 np_test_mount_entry_regex(dummy_mount_list, strdup("/"), cflags, 3, strdup("a"));
73 np_test_mount_entry_regex(dummy_mount_list, strdup("/dev"), cflags, 3, strdup("regex on dev names:")); 74 np_test_mount_entry_regex(dummy_mount_list, strdup("/dev"), cflags, 3,
74 np_test_mount_entry_regex(dummy_mount_list, strdup("/foo"), cflags, 0, strdup("regex on non existent dev/path:")); 75 strdup("regex on dev names:"));
75 np_test_mount_entry_regex(dummy_mount_list, strdup("/Foo"), cflags | REG_ICASE, 0, strdup("regi on non existent dev/path:")); 76 np_test_mount_entry_regex(dummy_mount_list, strdup("/foo"), cflags, 0,
76 np_test_mount_entry_regex(dummy_mount_list, strdup("/c.t0"), cflags, 3, strdup("partial devname regex match:")); 77 strdup("regex on non existent dev/path:"));
77 np_test_mount_entry_regex(dummy_mount_list, strdup("c0t0"), cflags, 1, strdup("partial devname regex match:")); 78 np_test_mount_entry_regex(dummy_mount_list, strdup("/Foo"), cflags | REG_ICASE, 0,
78 np_test_mount_entry_regex(dummy_mount_list, strdup("C0t0"), cflags | REG_ICASE, 1, strdup("partial devname regi match:")); 79 strdup("regi on non existent dev/path:"));
79 np_test_mount_entry_regex(dummy_mount_list, strdup("home"), cflags, 1, strdup("partial pathname regex match:")); 80 np_test_mount_entry_regex(dummy_mount_list, strdup("/c.t0"), cflags, 3,
80 np_test_mount_entry_regex(dummy_mount_list, strdup("hOme"), cflags | REG_ICASE, 1, strdup("partial pathname regi match:")); 81 strdup("partial devname regex match:"));
81 np_test_mount_entry_regex(dummy_mount_list, strdup("(/home)|(/var)"), cflags, 2, strdup("grouped regex pathname match:")); 82 np_test_mount_entry_regex(dummy_mount_list, strdup("c0t0"), cflags, 1,
82 np_test_mount_entry_regex(dummy_mount_list, strdup("(/homE)|(/Var)"), cflags | REG_ICASE, 2, strdup("grouped regi pathname match:")); 83 strdup("partial devname regex match:"));
84 np_test_mount_entry_regex(dummy_mount_list, strdup("C0t0"), cflags | REG_ICASE, 1,
85 strdup("partial devname regi match:"));
86 np_test_mount_entry_regex(dummy_mount_list, strdup("home"), cflags, 1,
87 strdup("partial pathname regex match:"));
88 np_test_mount_entry_regex(dummy_mount_list, strdup("hOme"), cflags | REG_ICASE, 1,
89 strdup("partial pathname regi match:"));
90 np_test_mount_entry_regex(dummy_mount_list, strdup("(/home)|(/var)"), cflags, 2,
91 strdup("grouped regex pathname match:"));
92 np_test_mount_entry_regex(dummy_mount_list, strdup("(/homE)|(/Var)"), cflags | REG_ICASE, 2,
93 strdup("grouped regi pathname match:"));
83 94
84 filesystem_list test_paths = filesystem_list_init(); 95 filesystem_list test_paths = filesystem_list_init();
85 mp_int_fs_list_append(&test_paths, "/home/groups"); 96 mp_int_fs_list_append(&test_paths, "/home/groups");
@@ -94,15 +105,18 @@ int main(int argc, char **argv) {
94 struct mount_entry *temp_me; 105 struct mount_entry *temp_me;
95 temp_me = p->best_match; 106 temp_me = p->best_match;
96 if (!strcmp(p->name, "/home/groups")) { 107 if (!strcmp(p->name, "/home/groups")) {
97 ok(temp_me && !strcmp(temp_me->me_mountdir, "/home"), "/home/groups got right best match: /home"); 108 ok(temp_me && !strcmp(temp_me->me_mountdir, "/home"),
109 "/home/groups got right best match: /home");
98 } else if (!strcmp(p->name, "/var")) { 110 } else if (!strcmp(p->name, "/var")) {
99 ok(temp_me && !strcmp(temp_me->me_mountdir, "/var"), "/var got right best match: /var"); 111 ok(temp_me && !strcmp(temp_me->me_mountdir, "/var"), "/var got right best match: /var");
100 } else if (!strcmp(p->name, "/tmp")) { 112 } else if (!strcmp(p->name, "/tmp")) {
101 ok(temp_me && !strcmp(temp_me->me_mountdir, "/"), "/tmp got right best match: /"); 113 ok(temp_me && !strcmp(temp_me->me_mountdir, "/"), "/tmp got right best match: /");
102 } else if (!strcmp(p->name, "/home/tonvoon")) { 114 } else if (!strcmp(p->name, "/home/tonvoon")) {
103 ok(temp_me && !strcmp(temp_me->me_mountdir, "/home"), "/home/tonvoon got right best match: /home"); 115 ok(temp_me && !strcmp(temp_me->me_mountdir, "/home"),
116 "/home/tonvoon got right best match: /home");
104 } else if (!strcmp(p->name, "/dev/c2t0d0s0")) { 117 } else if (!strcmp(p->name, "/dev/c2t0d0s0")) {
105 ok(temp_me && !strcmp(temp_me->me_devname, "/dev/c2t0d0s0"), "/dev/c2t0d0s0 got right best match: /dev/c2t0d0s0"); 118 ok(temp_me && !strcmp(temp_me->me_devname, "/dev/c2t0d0s0"),
119 "/dev/c2t0d0s0 got right best match: /dev/c2t0d0s0");
106 } 120 }
107 } 121 }
108 122
@@ -180,7 +194,8 @@ int main(int argc, char **argv) {
180 return exit_status(); 194 return exit_status();
181} 195}
182 196
183void np_test_mount_entry_regex(struct mount_entry *dummy_mount_list, char *regstr, int cflags, int expect, char *desc) { 197void np_test_mount_entry_regex(struct mount_entry *dummy_mount_list, char *regstr, int cflags,
198 int expect, char *desc) {
184 regex_t regex; 199 regex_t regex;
185 if (regcomp(&regex, regstr, cflags) == 0) { 200 if (regcomp(&regex, regstr, cflags) == 0) {
186 int matches = 0; 201 int matches = 0;
@@ -189,7 +204,8 @@ void np_test_mount_entry_regex(struct mount_entry *dummy_mount_list, char *regst
189 matches++; 204 matches++;
190 } 205 }
191 } 206 }
192 ok(matches == expect, "%s '%s' matched %i/3 entries. ok: %i/3", desc, regstr, expect, matches); 207 ok(matches == expect, "%s '%s' matched %i/3 entries. ok: %i/3", desc, regstr, expect,
208 matches);
193 209
194 } else { 210 } else {
195 ok(false, "regex '%s' not compilable", regstr); 211 ok(false, "regex '%s' not compilable", regstr);
diff --git a/plugins/tests/test_check_swap.c b/plugins/tests/test_check_swap.c
index b85fb4ad..94d56ce7 100644
--- a/plugins/tests/test_check_swap.c
+++ b/plugins/tests/test_check_swap.c
@@ -5,9 +5,7 @@
5int verbose = 0; 5int verbose = 0;
6 6
7void print_usage(void) {} 7void print_usage(void) {}
8void print_help(swap_config config) { 8void print_help(swap_config config) { (void)config; }
9 (void) config;
10}
11 9
12const char *progname = "test_check_swap"; 10const char *progname = "test_check_swap";
13 11
diff --git a/plugins/urlize.c b/plugins/urlize.c
index 1aa4e425..a8590fae 100644
--- a/plugins/urlize.c
+++ b/plugins/urlize.c
@@ -53,8 +53,10 @@ int main(int argc, char **argv) {
53 53
54 int c; 54 int c;
55 int option = 0; 55 int option = 0;
56 static struct option longopts[] = { 56 static struct option longopts[] = {{"help", no_argument, 0, 'h'},
57 {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"url", required_argument, 0, 'u'}, {0, 0, 0, 0}}; 57 {"version", no_argument, 0, 'V'},
58 {"url", required_argument, 0, 'u'},
59 {0, 0, 0, 0}};
58 60
59 setlocale(LC_ALL, ""); 61 setlocale(LC_ALL, "");
60 bindtextdomain(PACKAGE, LOCALEDIR); 62 bindtextdomain(PACKAGE, LOCALEDIR);
@@ -69,8 +71,9 @@ int main(int argc, char **argv) {
69 while (1) { 71 while (1) {
70 c = getopt_long(argc, argv, "+hVu:", longopts, &option); 72 c = getopt_long(argc, argv, "+hVu:", longopts, &option);
71 73
72 if (c == -1 || c == EOF) 74 if (c == -1 || c == EOF) {
73 break; 75 break;
76 }
74 77
75 switch (c) { 78 switch (c) {
76 case 'h': /* help */ 79 case 'h': /* help */
@@ -90,8 +93,9 @@ int main(int argc, char **argv) {
90 } 93 }
91 } 94 }
92 95
93 if (url == NULL) 96 if (url == NULL) {
94 url = strdup(argv[optind++]); 97 url = strdup(argv[optind++]);
98 }
95 99
96 cmd = strdup(argv[optind++]); 100 cmd = strdup(argv[optind++]);
97 for (c = optind; c < argc; c++) { 101 for (c = optind; c < argc; c++) {
@@ -118,27 +122,32 @@ int main(int argc, char **argv) {
118 strcat(tstr, buf); 122 strcat(tstr, buf);
119 } 123 }
120 124
121 if (!found) 125 if (!found) {
122 die(STATE_UNKNOWN, _("%s UNKNOWN - No data received from host\nCMD: %s</A>\n"), argv[0], cmd); 126 die(STATE_UNKNOWN, _("%s UNKNOWN - No data received from host\nCMD: %s</A>\n"), argv[0],
127 cmd);
128 }
123 129
124 /* chop the newline character */ 130 /* chop the newline character */
125 if ((nstr = strchr(tstr, NEWLINE_CHARACTER)) != NULL) 131 if ((nstr = strchr(tstr, NEWLINE_CHARACTER)) != NULL) {
126 *nstr = '\0'; 132 *nstr = '\0';
133 }
127 134
128 /* tokenize the string for Perfdata if there is some */ 135 /* tokenize the string for Perfdata if there is some */
129 nstr = strtok(tstr, PERF_CHARACTER); 136 nstr = strtok(tstr, PERF_CHARACTER);
130 printf("%s", nstr); 137 printf("%s", nstr);
131 printf("</A>"); 138 printf("</A>");
132 nstr = strtok(NULL, PERF_CHARACTER); 139 nstr = strtok(NULL, PERF_CHARACTER);
133 if (nstr != NULL) 140 if (nstr != NULL) {
134 printf(" | %s", nstr); 141 printf(" | %s", nstr);
142 }
135 143
136 /* close the pipe */ 144 /* close the pipe */
137 result = spclose(child_process); 145 result = spclose(child_process);
138 146
139 /* WARNING if output found on stderr */ 147 /* WARNING if output found on stderr */
140 if (fgets(buf, MAX_INPUT_BUFFER - 1, child_stderr)) 148 if (fgets(buf, MAX_INPUT_BUFFER - 1, child_stderr)) {
141 result = max_state(result, STATE_WARNING); 149 result = max_state(result, STATE_WARNING);
150 }
142 151
143 /* close stderr */ 152 /* close stderr */
144 (void)fclose(child_stderr); 153 (void)fclose(child_stderr);
@@ -153,8 +162,10 @@ void print_help(void) {
153 printf(COPYRIGHT, copyright, email); 162 printf(COPYRIGHT, copyright, email);
154 163
155 printf("%s\n", _("This plugin wraps the text output of another command (plugin) in HTML <A>")); 164 printf("%s\n", _("This plugin wraps the text output of another command (plugin) in HTML <A>"));
156 printf("%s\n", _("tags, thus displaying the child plugin's output as a clickable link in compatible")); 165 printf("%s\n",
157 printf("%s\n", _("monitoring status screen. This plugin returns the status of the invoked plugin.")); 166 _("tags, thus displaying the child plugin's output as a clickable link in compatible"));
167 printf("%s\n",
168 _("monitoring status screen. This plugin returns the status of the invoked plugin."));
158 169
159 printf("\n\n"); 170 printf("\n\n");
160 171
@@ -164,7 +175,8 @@ void print_help(void) {
164 175
165 printf("\n"); 176 printf("\n");
166 printf("%s\n", _("Examples:")); 177 printf("%s\n", _("Examples:"));
167 printf("%s\n", _("Pay close attention to quoting to ensure that the shell passes the expected")); 178 printf("%s\n",
179 _("Pay close attention to quoting to ensure that the shell passes the expected"));
168 printf("%s\n\n", _("data to the plugin. For example, in:")); 180 printf("%s\n\n", _("data to the plugin. For example, in:"));
169 printf(" %s\n\n", _("urlize http://example.com/ check_http -H example.com -r 'two words'")); 181 printf(" %s\n\n", _("urlize http://example.com/ check_http -H example.com -r 'two words'"));
170 printf(" %s\n", _("the shell will remove the single quotes and urlize will see:")); 182 printf(" %s\n", _("the shell will remove the single quotes and urlize will see:"));
diff --git a/plugins/utils.c b/plugins/utils.c
index 34335c89..41fe5fcf 100644
--- a/plugins/utils.c
+++ b/plugins/utils.c
@@ -285,7 +285,8 @@ double delta_time(struct timeval tv) {
285 struct timeval now; 285 struct timeval now;
286 286
287 gettimeofday(&now, NULL); 287 gettimeofday(&now, NULL);
288 return ((double)(now.tv_sec - tv.tv_sec) + (double)(now.tv_usec - tv.tv_usec) / (double)1000000); 288 return ((double)(now.tv_sec - tv.tv_sec) +
289 (double)(now.tv_usec - tv.tv_usec) / (double)1000000);
289} 290}
290 291
291long deltime(struct timeval tv) { 292long deltime(struct timeval tv) {
@@ -507,8 +508,8 @@ int xasprintf(char **strp, const char *fmt, ...) {
507 * 508 *
508 ******************************************************************************/ 509 ******************************************************************************/
509 510
510char *perfdata(const char *label, long int val, const char *uom, bool warnp, long int warn, bool critp, long int crit, bool minp, 511char *perfdata(const char *label, long int val, const char *uom, bool warnp, long int warn,
511 long int minv, bool maxp, long int maxv) { 512 bool critp, long int crit, bool minp, long int minv, bool maxp, long int maxv) {
512 char *data = NULL; 513 char *data = NULL;
513 514
514 if (strpbrk(label, "'= ")) { 515 if (strpbrk(label, "'= ")) {
@@ -542,10 +543,11 @@ char *perfdata(const char *label, long int val, const char *uom, bool warnp, lon
542 return data; 543 return data;
543} 544}
544 545
545char *perfdata_uint64(const char *label, uint64_t val, const char *uom, bool warnp, /* Warning present */ 546char *perfdata_uint64(const char *label, uint64_t val, const char *uom,
546 uint64_t warn, bool critp, /* Critical present */ 547 bool warnp, /* Warning present */
547 uint64_t crit, bool minp, /* Minimum present */ 548 uint64_t warn, bool critp, /* Critical present */
548 uint64_t minv, bool maxp, /* Maximum present */ 549 uint64_t crit, bool minp, /* Minimum present */
550 uint64_t minv, bool maxp, /* Maximum present */
549 uint64_t maxv) { 551 uint64_t maxv) {
550 char *data = NULL; 552 char *data = NULL;
551 553
@@ -580,10 +582,11 @@ char *perfdata_uint64(const char *label, uint64_t val, const char *uom, bool war
580 return data; 582 return data;
581} 583}
582 584
583char *perfdata_int64(const char *label, int64_t val, const char *uom, bool warnp, /* Warning present */ 585char *perfdata_int64(const char *label, int64_t val, const char *uom,
584 int64_t warn, bool critp, /* Critical present */ 586 bool warnp, /* Warning present */
585 int64_t crit, bool minp, /* Minimum present */ 587 int64_t warn, bool critp, /* Critical present */
586 int64_t minv, bool maxp, /* Maximum present */ 588 int64_t crit, bool minp, /* Minimum present */
589 int64_t minv, bool maxp, /* Maximum present */
587 int64_t maxv) { 590 int64_t maxv) {
588 char *data = NULL; 591 char *data = NULL;
589 592
@@ -618,8 +621,8 @@ char *perfdata_int64(const char *label, int64_t val, const char *uom, bool warnp
618 return data; 621 return data;
619} 622}
620 623
621char *fperfdata(const char *label, double val, const char *uom, bool warnp, double warn, bool critp, double crit, bool minp, double minv, 624char *fperfdata(const char *label, double val, const char *uom, bool warnp, double warn, bool critp,
622 bool maxp, double maxv) { 625 double crit, bool minp, double minv, bool maxp, double maxv) {
623 char *data = NULL; 626 char *data = NULL;
624 627
625 if (strpbrk(label, "'= ")) { 628 if (strpbrk(label, "'= ")) {
@@ -655,7 +658,8 @@ char *fperfdata(const char *label, double val, const char *uom, bool warnp, doub
655 return data; 658 return data;
656} 659}
657 660
658char *sperfdata(const char *label, double val, const char *uom, char *warn, char *crit, bool minp, double minv, bool maxp, double maxv) { 661char *sperfdata(const char *label, double val, const char *uom, char *warn, char *crit, bool minp,
662 double minv, bool maxp, double maxv) {
659 char *data = NULL; 663 char *data = NULL;
660 if (strpbrk(label, "'= ")) { 664 if (strpbrk(label, "'= ")) {
661 xasprintf(&data, "'%s'=", label); 665 xasprintf(&data, "'%s'=", label);
@@ -690,7 +694,8 @@ char *sperfdata(const char *label, double val, const char *uom, char *warn, char
690 return data; 694 return data;
691} 695}
692 696
693char *sperfdata_int(const char *label, int val, const char *uom, char *warn, char *crit, bool minp, int minv, bool maxp, int maxv) { 697char *sperfdata_int(const char *label, int val, const char *uom, char *warn, char *crit, bool minp,
698 int minv, bool maxp, int maxv) {
694 char *data = NULL; 699 char *data = NULL;
695 if (strpbrk(label, "'= ")) { 700 if (strpbrk(label, "'= ")) {
696 xasprintf(&data, "'%s'=", label); 701 xasprintf(&data, "'%s'=", label);
diff --git a/plugins/utils.h b/plugins/utils.h
index 1d3c153c..1f0e021b 100644
--- a/plugins/utils.h
+++ b/plugins/utils.h
@@ -76,7 +76,7 @@ char *strnl(char *);
76char *strpcpy(char *, const char *, const char *); 76char *strpcpy(char *, const char *, const char *);
77char *strpcat(char *, const char *, const char *); 77char *strpcat(char *, const char *, const char *);
78int xvasprintf(char **strp, const char *fmt, va_list ap); 78int xvasprintf(char **strp, const char *fmt, va_list ap);
79int xasprintf(char **strp, const char *fmt, ...)__attribute__ ((format (printf, 2, 3))); 79int xasprintf(char **strp, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
80 80
81void usage(const char *) __attribute__((noreturn)); 81void usage(const char *) __attribute__((noreturn));
82void usage2(const char *, const char *) __attribute__((noreturn)); 82void usage2(const char *, const char *) __attribute__((noreturn));
@@ -88,13 +88,17 @@ void usage_va(const char *fmt, ...) __attribute__((noreturn));
88#define max(a, b) (((a) > (b)) ? (a) : (b)) 88#define max(a, b) (((a) > (b)) ? (a) : (b))
89#define min(a, b) (((a) < (b)) ? (a) : (b)) 89#define min(a, b) (((a) < (b)) ? (a) : (b))
90 90
91char *perfdata(const char *, long int, const char *, bool, long int, bool, long int, bool, long int, bool, long int); 91char *perfdata(const char *, long int, const char *, bool, long int, bool, long int, bool, long int,
92 bool, long int);
92 93
93char *perfdata_uint64(const char *, uint64_t, const char *, bool, uint64_t, bool, uint64_t, bool, uint64_t, bool, uint64_t); 94char *perfdata_uint64(const char *, uint64_t, const char *, bool, uint64_t, bool, uint64_t, bool,
95 uint64_t, bool, uint64_t);
94 96
95char *perfdata_int64(const char *, int64_t, const char *, bool, int64_t, bool, int64_t, bool, int64_t, bool, int64_t); 97char *perfdata_int64(const char *, int64_t, const char *, bool, int64_t, bool, int64_t, bool,
98 int64_t, bool, int64_t);
96 99
97char *fperfdata(const char *, double, const char *, bool, double, bool, double, bool, double, bool, double); 100char *fperfdata(const char *, double, const char *, bool, double, bool, double, bool, double, bool,
101 double);
98 102
99char *sperfdata(const char *, double, const char *, char *, char *, bool, double, bool, double); 103char *sperfdata(const char *, double, const char *, char *, char *, bool, double, bool, double);
100 104
@@ -104,21 +108,22 @@ char *sperfdata_int(const char *, int, const char *, char *, char *, bool, int,
104 most will or should. Therefore, for consistency, these very common 108 most will or should. Therefore, for consistency, these very common
105 options should have only these meanings throughout the overall suite */ 109 options should have only these meanings throughout the overall suite */
106 110
107#define STD_LONG_OPTS \ 111#define STD_LONG_OPTS \
108 {"version", no_argument, 0, 'V'}, {"verbose", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, \ 112 {"version", no_argument, 0, 'V'}, {"verbose", no_argument, 0, 'v'}, \
109 {"timeout", required_argument, 0, 't'}, {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, \ 113 {"help", no_argument, 0, 'h'}, {"timeout", required_argument, 0, 't'}, \
114 {"critical", required_argument, 0, 'c'}, {"warning", required_argument, 0, 'w'}, \
110 {"hostname", required_argument, 0, 'H'} 115 {"hostname", required_argument, 0, 'H'}
111 116
112#define COPYRIGHT \ 117#define COPYRIGHT \
113 "Copyright (c) %s Monitoring Plugins Development Team\n\ 118 "Copyright (c) %s Monitoring Plugins Development Team\n\
114\t<%s>\n\n" 119\t<%s>\n\n"
115 120
116#define UT_HLP_VRS \ 121#define UT_HLP_VRS \
117 _("\ 122 _("\
118 %s (-h | --help) for detailed help\n\ 123 %s (-h | --help) for detailed help\n\
119 %s (-V | --version) for version information\n") 124 %s (-V | --version) for version information\n")
120 125
121#define UT_HELP_VRSN \ 126#define UT_HELP_VRSN \
122 _("\ 127 _("\
123\nOptions:\n\ 128\nOptions:\n\
124 -h, --help\n\ 129 -h, --help\n\
@@ -126,52 +131,52 @@ char *sperfdata_int(const char *, int, const char *, char *, char *, bool, int,
126 -V, --version\n\ 131 -V, --version\n\
127 Print version information\n") 132 Print version information\n")
128 133
129#define UT_HOST_PORT \ 134#define UT_HOST_PORT \
130 _("\ 135 _("\
131 -H, --hostname=ADDRESS\n\ 136 -H, --hostname=ADDRESS\n\
132 Host name, IP Address, or unix socket (must be an absolute path)\n\ 137 Host name, IP Address, or unix socket (must be an absolute path)\n\
133 -%c, --port=INTEGER\n\ 138 -%c, --port=INTEGER\n\
134 Port number (default: %s)\n") 139 Port number (default: %s)\n")
135 140
136#define UT_IPv46 \ 141#define UT_IPv46 \
137 _("\ 142 _("\
138 -4, --use-ipv4\n\ 143 -4, --use-ipv4\n\
139 Use IPv4 connection\n\ 144 Use IPv4 connection\n\
140 -6, --use-ipv6\n\ 145 -6, --use-ipv6\n\
141 Use IPv6 connection\n") 146 Use IPv6 connection\n")
142 147
143#define UT_VERBOSE \ 148#define UT_VERBOSE \
144 _("\ 149 _("\
145 -v, --verbose\n\ 150 -v, --verbose\n\
146 Show details for command-line debugging (output may be truncated by\n\ 151 Show details for command-line debugging (output may be truncated by\n\
147 the monitoring system)\n") 152 the monitoring system)\n")
148 153
149#define UT_WARN_CRIT \ 154#define UT_WARN_CRIT \
150 _("\ 155 _("\
151 -w, --warning=DOUBLE\n\ 156 -w, --warning=DOUBLE\n\
152 Response time to result in warning status (seconds)\n\ 157 Response time to result in warning status (seconds)\n\
153 -c, --critical=DOUBLE\n\ 158 -c, --critical=DOUBLE\n\
154 Response time to result in critical status (seconds)\n") 159 Response time to result in critical status (seconds)\n")
155 160
156#define UT_WARN_CRIT_RANGE \ 161#define UT_WARN_CRIT_RANGE \
157 _("\ 162 _("\
158 -w, --warning=RANGE\n\ 163 -w, --warning=RANGE\n\
159 Warning range (format: start:end). Alert if outside this range\n\ 164 Warning range (format: start:end). Alert if outside this range\n\
160 -c, --critical=RANGE\n\ 165 -c, --critical=RANGE\n\
161 Critical range\n") 166 Critical range\n")
162 167
163#define UT_CONN_TIMEOUT \ 168#define UT_CONN_TIMEOUT \
164 _("\ 169 _("\
165 -t, --timeout=INTEGER\n\ 170 -t, --timeout=INTEGER\n\
166 Seconds before connection times out (default: %d)\n") 171 Seconds before connection times out (default: %d)\n")
167 172
168#define UT_PLUG_TIMEOUT \ 173#define UT_PLUG_TIMEOUT \
169 _("\ 174 _("\
170 -t, --timeout=INTEGER\n\ 175 -t, --timeout=INTEGER\n\
171 Seconds before plugin times out (default: %d)\n") 176 Seconds before plugin times out (default: %d)\n")
172 177
173#ifdef NP_EXTRA_OPTS 178#ifdef NP_EXTRA_OPTS
174# define UT_EXTRA_OPTS \ 179# define UT_EXTRA_OPTS \
175 _("\ 180 _("\
176 --extra-opts=[section][@file]\n\ 181 --extra-opts=[section][@file]\n\
177 Read options from an ini file. See\n\ 182 Read options from an ini file. See\n\
@@ -181,25 +186,25 @@ char *sperfdata_int(const char *, int, const char *, char *, char *, bool, int,
181# define UT_EXTRA_OPTS " \b" 186# define UT_EXTRA_OPTS " \b"
182#endif 187#endif
183 188
184#define UT_THRESHOLDS_NOTES \ 189#define UT_THRESHOLDS_NOTES \
185 _("\ 190 _("\
186 See:\n\ 191 See:\n\
187 https://www.monitoring-plugins.org/doc/guidelines.html#THRESHOLDFORMAT\n\ 192 https://www.monitoring-plugins.org/doc/guidelines.html#THRESHOLDFORMAT\n\
188 for THRESHOLD format and examples.\n") 193 for THRESHOLD format and examples.\n")
189 194
190#define UT_SUPPORT \ 195#define UT_SUPPORT \
191 _("\n\ 196 _("\n\
192Send email to help@monitoring-plugins.org if you have questions regarding\n\ 197Send email to help@monitoring-plugins.org if you have questions regarding\n\
193use of this software. To submit patches or suggest improvements, send email\n\ 198use of this software. To submit patches or suggest improvements, send email\n\
194to devel@monitoring-plugins.org\n\n") 199to devel@monitoring-plugins.org\n\n")
195 200
196#define UT_NOWARRANTY \ 201#define UT_NOWARRANTY \
197 _("\n\ 202 _("\n\
198The Monitoring Plugins come with ABSOLUTELY NO WARRANTY. You may redistribute\n\ 203The Monitoring Plugins come with ABSOLUTELY NO WARRANTY. You may redistribute\n\
199copies of the plugins under the terms of the GNU General Public License.\n\ 204copies of the plugins under the terms of the GNU General Public License.\n\
200For more information about these matters, see the file named COPYING.\n") 205For more information about these matters, see the file named COPYING.\n")
201 206
202#define UT_OUTPUT_FORMAT \ 207#define UT_OUTPUT_FORMAT \
203 _("\ 208 _("\
204 --output-format=OUTPUT_FORMAT\n\ 209 --output-format=OUTPUT_FORMAT\n\
205 Select output format. Valid values: \"multi-line\", \"mp-test-json\"\n") 210 Select output format. Valid values: \"multi-line\", \"mp-test-json\"\n")
diff --git a/tap/tap.c b/tap/tap.c
index 00ceab27..fb40736f 100644
--- a/tap/tap.c
+++ b/tap/tap.c
@@ -65,7 +65,8 @@ static void _cleanup(void);
65 * test_name -- the name of the test, may be NULL 65 * test_name -- the name of the test, may be NULL
66 * test_comment -- a comment to print afterwards, may be NULL 66 * test_comment -- a comment to print afterwards, may be NULL
67 */ 67 */
68unsigned int _gen_result(int ok, const char *func, char *file, unsigned int line, char *test_name, ...) { 68unsigned int _gen_result(int ok, const char *func, char *file, unsigned int line, char *test_name,
69 ...) {
69 va_list ap; 70 va_list ap;
70 char *local_test_name = NULL; 71 char *local_test_name = NULL;
71 char *c; 72 char *c;
@@ -95,7 +96,9 @@ unsigned int _gen_result(int ok, const char *func, char *file, unsigned int line
95 } 96 }
96 97
97 if (name_is_digits) { 98 if (name_is_digits) {
98 diag(" You named your test '%s'. You shouldn't use numbers for your test names.", local_test_name); 99 diag(
100 " You named your test '%s'. You shouldn't use numbers for your test names.",
101 local_test_name);
99 diag(" Very confusing."); 102 diag(" Very confusing.");
100 } 103 }
101 } 104 }
@@ -116,8 +119,9 @@ unsigned int _gen_result(int ok, const char *func, char *file, unsigned int line
116 if (local_test_name != NULL) { 119 if (local_test_name != NULL) {
117 flockfile(stdout); 120 flockfile(stdout);
118 for (c = local_test_name; *c != '\0'; c++) { 121 for (c = local_test_name; *c != '\0'; c++) {
119 if (*c == '#') 122 if (*c == '#') {
120 fputc('\\', stdout); 123 fputc('\\', stdout);
124 }
121 fputc((int)*c, stdout); 125 fputc((int)*c, stdout);
122 } 126 }
123 funlockfile(stdout); 127 funlockfile(stdout);
@@ -135,14 +139,16 @@ unsigned int _gen_result(int ok, const char *func, char *file, unsigned int line
135 the test failed. */ 139 the test failed. */
136 if (todo) { 140 if (todo) {
137 printf(" # TODO %s", todo_msg ? todo_msg : todo_msg_fixed); 141 printf(" # TODO %s", todo_msg ? todo_msg : todo_msg_fixed);
138 if (!ok) 142 if (!ok) {
139 failures--; 143 failures--;
144 }
140 } 145 }
141 146
142 printf("\n"); 147 printf("\n");
143 148
144 if (!ok) 149 if (!ok) {
145 diag(" Failed %stest (%s:%s() at line %d)", todo ? "(TODO) " : "", file, func, line); 150 diag(" Failed %stest (%s:%s() at line %d)", todo ? "(TODO) " : "", file, func, line);
151 }
146 152
147 free(local_test_name); 153 free(local_test_name);
148 154
@@ -212,8 +218,9 @@ int plan_skip_all(char *reason) {
212 218
213 printf("1..0"); 219 printf("1..0");
214 220
215 if (reason != NULL) 221 if (reason != NULL) {
216 printf(" # Skip %s", reason); 222 printf(" # Skip %s", reason);
223 }
217 224
218 printf("\n"); 225 printf("\n");
219 226
@@ -294,7 +301,8 @@ int skip(unsigned int n, char *fmt, ...) {
294 301
295 while (n-- > 0) { 302 while (n-- > 0) {
296 test_count++; 303 test_count++;
297 printf("ok %d # skip %s\n", test_count, skip_msg != NULL ? skip_msg : "libtap():malloc() failed"); 304 printf("ok %d # skip %s\n", test_count,
305 skip_msg != NULL ? skip_msg : "libtap():malloc() failed");
298 } 306 }
299 307
300 free(skip_msg); 308 free(skip_msg);
@@ -396,8 +404,9 @@ void _cleanup(void) {
396 return; 404 return;
397 } 405 }
398 406
399 if (failures) 407 if (failures) {
400 diag("Looks like you failed %d tests of %d.", failures, test_count); 408 diag("Looks like you failed %d tests of %d.", failures, test_count);
409 }
401 410
402 UNLOCK; 411 UNLOCK;
403} 412}
diff --git a/tap/tap.h b/tap/tap.h
index 5abbd76a..0c550bfd 100644
--- a/tap/tap.h
+++ b/tap/tap.h
@@ -28,45 +28,50 @@
28 and requires the caller to add the final comma if they've omitted 28 and requires the caller to add the final comma if they've omitted
29 the optional arguments */ 29 the optional arguments */
30#ifdef __GNUC__ 30#ifdef __GNUC__
31# define ok(e, test, ...) \ 31# define ok(e, test, ...) \
32 ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, test, ##__VA_ARGS__) \ 32 ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, test, ##__VA_ARGS__) \
33 : _gen_result(0, __func__, __FILE__, __LINE__, test, ##__VA_ARGS__)) 33 : _gen_result(0, __func__, __FILE__, __LINE__, test, ##__VA_ARGS__))
34 34
35# define ok1(e) ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, "%s", #e) : _gen_result(0, __func__, __FILE__, __LINE__, "%s", #e)) 35# define ok1(e) \
36 ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, "%s", #e) \
37 : _gen_result(0, __func__, __FILE__, __LINE__, "%s", #e))
36 38
37# define pass(test, ...) ok(1, test, ##__VA_ARGS__); 39# define pass(test, ...) ok(1, test, ##__VA_ARGS__);
38# define fail(test, ...) ok(0, test, ##__VA_ARGS__); 40# define fail(test, ...) ok(0, test, ##__VA_ARGS__);
39 41
40# define skip_start(test, n, fmt, ...) \ 42# define skip_start(test, n, fmt, ...) \
41 do { \ 43 do { \
42 if ((test)) { \ 44 if ((test)) { \
43 skip(n, fmt, ##__VA_ARGS__); \ 45 skip(n, fmt, ##__VA_ARGS__); \
44 continue; \ 46 continue; \
45 } 47 }
46#else /* __GNUC__ */ 48#else /* __GNUC__ */
47/* The original tap.h used to test if __STDC_VERSION__ >= 199901L here. This 49/* The original tap.h used to test if __STDC_VERSION__ >= 199901L here. This
48 * doesn't seem to work on HP-UX even though the code compile fine. I'm not 50 * doesn't seem to work on HP-UX even though the code compile fine. I'm not
49 * sure how to add an exception here for HP-UX so I just removed the check 51 * sure how to add an exception here for HP-UX so I just removed the check
50 * for now */ 52 * for now */
51# define ok(e, ...) \ 53# define ok(e, ...) \
52 ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, __VA_ARGS__) : _gen_result(0, __func__, __FILE__, __LINE__, __VA_ARGS__)) 54 ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, __VA_ARGS__) \
55 : _gen_result(0, __func__, __FILE__, __LINE__, __VA_ARGS__))
53 56
54# define ok1(e) ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, "%s", #e) : _gen_result(0, __func__, __FILE__, __LINE__, "%s", #e)) 57# define ok1(e) \
58 ((e) ? _gen_result(1, __func__, __FILE__, __LINE__, "%s", #e) \
59 : _gen_result(0, __func__, __FILE__, __LINE__, "%s", #e))
55 60
56# define pass(...) ok(1, __VA_ARGS__); 61# define pass(...) ok(1, __VA_ARGS__);
57# define fail(...) ok(0, __VA_ARGS__); 62# define fail(...) ok(0, __VA_ARGS__);
58 63
59# define skip_start(test, n, ...) \ 64# define skip_start(test, n, ...) \
60 do { \ 65 do { \
61 if ((test)) { \ 66 if ((test)) { \
62 skip(n, __VA_ARGS__); \ 67 skip(n, __VA_ARGS__); \
63 continue; \ 68 continue; \
64 } 69 }
65#endif /* __GNUC__ */ 70#endif /* __GNUC__ */
66 71
67#define skip_end \ 72#define skip_end \
68 } \ 73 } \
69 while (0) \ 74 while (0) \
70 ; 75 ;
71 76
72unsigned int _gen_result(int, const char *, char *, unsigned int, char *, ...); 77unsigned int _gen_result(int, const char *, char *, unsigned int, char *, ...);
diff --git a/tools/mini_epn.c b/tools/mini_epn.c
index 6f3c5d02..1b09f1c1 100644
--- a/tools/mini_epn.c
+++ b/tools/mini_epn.c
@@ -1,14 +1,14 @@
1/* 1/*
2 * 2 *
3 * MINI_EPN.C - Mini Embedded Perl Nagios 3 * MINI_EPN.C - Mini Embedded Perl Nagios
4 * Contributed by Stanley Hopcroft 4 * Contributed by Stanley Hopcroft
5 * Modified by Douglas Warner 5 * Modified by Douglas Warner
6 * Last Modified: 05/02/2002 6 * Last Modified: 05/02/2002
7 * 7 *
8 * This is a sample mini embedded Perl interpreter (hacked out checks.c and 8 * This is a sample mini embedded Perl interpreter (hacked out checks.c and
9 * perlembed) for use in testing Perl plugins. 9 * perlembed) for use in testing Perl plugins.
10 * 10 *
11 * It can be compiled with the following command (see 'man perlembed' for 11 * It can be compiled with the following command (see 'man perlembed' for
12 * more info): 12 * more info):
13 * 13 *
14 * gcc -omini_epn mini_epn.c `perl -MExtUtils::Embed -e ccopts -e ldopts` 14 * gcc -omini_epn mini_epn.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
@@ -21,7 +21,6 @@
21 * 21 *
22 */ 22 */
23 23
24
25#include <EXTERN.h> 24#include <EXTERN.h>
26#include <perl.h> 25#include <perl.h>
27#include <fcntl.h> 26#include <fcntl.h>
@@ -30,7 +29,7 @@
30/* include PERL xs_init code for module and C library support */ 29/* include PERL xs_init code for module and C library support */
31 30
32#if defined(__cplusplus) 31#if defined(__cplusplus)
33#define is_cplusplus 32# define is_cplusplus
34#endif 33#endif
35 34
36#ifdef is_cplusplus 35#ifdef is_cplusplus
@@ -42,22 +41,20 @@ extern "C" {
42 41
43#ifdef is_cplusplus 42#ifdef is_cplusplus
44} 43}
45# ifndef EXTERN_C 44# ifndef EXTERN_C
46# define EXTERN_C extern "C" 45# define EXTERN_C extern "C"
47# endif 46# endif
48#else 47#else
49# ifndef EXTERN_C 48# ifndef EXTERN_C
50# define EXTERN_C extern 49# define EXTERN_C extern
51# endif 50# endif
52#endif 51#endif
53
54 52
55EXTERN_C void xs_init _((void)); 53EXTERN_C void xs_init _((void));
56 54
57EXTERN_C void boot_DynaLoader _((CV* cv)); 55EXTERN_C void boot_DynaLoader _((CV * cv));
58 56
59EXTERN_C void xs_init(void) 57EXTERN_C void xs_init(void) {
60{
61 char *file = __FILE__; 58 char *file = __FILE__;
62 dXSUB_SYS; 59 dXSUB_SYS;
63 60
@@ -65,85 +62,80 @@ EXTERN_C void xs_init(void)
65 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file); 62 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
66} 63}
67 64
68
69static PerlInterpreter *perl = NULL; 65static PerlInterpreter *perl = NULL;
70 66
71 67int main(int argc, char **argv, char **env) {
72int main(int argc, char **argv, char **env) 68 char *embedding[] = {"", "p1.pl"};
73{
74 char *embedding[] = { "", "p1.pl" };
75 char plugin_output[1024]; 69 char plugin_output[1024];
76 char buffer[512]; 70 char buffer[512];
77 char tmpfname[32]; 71 char tmpfname[32];
78 char fname[32]; 72 char fname[32];
79 char *args[] = {"","0", "", "", NULL }; 73 char *args[] = {"", "0", "", "", NULL};
80 FILE *fp; 74 FILE *fp;
81 75
82 const int command_line_size = 160; 76 const int command_line_size = 160;
83 char command_line[command_line_size]; 77 char command_line[command_line_size];
84 char *ap ; 78 char *ap;
85 int exitstatus; 79 int exitstatus;
86 int pclose_result; 80 int pclose_result;
87#ifdef THREADEDPERL 81#ifdef THREADEDPERL
88 dTHX; 82 dTHX;
89#endif 83#endif
90 dSP; 84 dSP;
91 85
92 if ((perl=perl_alloc())==NULL) { 86 if ((perl = perl_alloc()) == NULL) {
93 snprintf(buffer,sizeof(buffer),"Error: Could not allocate memory for embedded Perl interpreter!\n"); 87 snprintf(buffer, sizeof(buffer),
94 buffer[sizeof(buffer)-1]='\x0'; 88 "Error: Could not allocate memory for embedded Perl interpreter!\n");
89 buffer[sizeof(buffer) - 1] = '\x0';
95 printf("%s\n", buffer); 90 printf("%s\n", buffer);
96 exit(1); 91 exit(1);
97 } 92 }
98 perl_construct(perl); 93 perl_construct(perl);
99 exitstatus=perl_parse(perl,xs_init,2,embedding,NULL); 94 exitstatus = perl_parse(perl, xs_init, 2, embedding, NULL);
100 if (!exitstatus) { 95 if (!exitstatus) {
101 96
102 exitstatus=perl_run(perl); 97 exitstatus = perl_run(perl);
103 98
104 while(printf("Enter file name: ") && fgets(command_line, command_line_size, stdin)) { 99 while (printf("Enter file name: ") && fgets(command_line, command_line_size, stdin)) {
105 100
106 /* call the subroutine, passing it the filename as an argument */ 101 /* call the subroutine, passing it the filename as an argument */
107 102
108 command_line[strlen(command_line) -1] = '\0'; 103 command_line[strlen(command_line) - 1] = '\0';
109 104
110 strncpy(fname,command_line,strcspn(command_line," ")); 105 strncpy(fname, command_line, strcspn(command_line, " "));
111 fname[strcspn(command_line," ")] = '\x0'; 106 fname[strcspn(command_line, " ")] = '\x0';
112 args[0] = fname ; 107 args[0] = fname;
113 args[3] = command_line + strlen(fname) + 1 ; 108 args[3] = command_line + strlen(fname) + 1;
114 109
115 /* generate a temporary filename to which stdout can be redirected. */ 110 /* generate a temporary filename to which stdout can be redirected. */
116 sprintf(tmpfname,"/tmp/embedded%d",getpid()); 111 sprintf(tmpfname, "/tmp/embedded%d", getpid());
117 args[2] = tmpfname; 112 args[2] = tmpfname;
118 113
119 /* call our perl interpreter to compile and optionally cache the command */ 114 /* call our perl interpreter to compile and optionally cache the command */
120 perl_call_argv("Embed::Persistent::eval_file", G_DISCARD | G_EVAL, args); 115 perl_call_argv("Embed::Persistent::eval_file", G_DISCARD | G_EVAL, args);
121 116
122 perl_call_argv("Embed::Persistent::run_package", G_DISCARD | G_EVAL, args); 117 perl_call_argv("Embed::Persistent::run_package", G_DISCARD | G_EVAL, args);
123 118
124 /* check return status */ 119 /* check return status */
125 if(SvTRUE(ERRSV)){ 120 if (SvTRUE(ERRSV)) {
126 pclose_result=-2; 121 pclose_result = -2;
127 printf("embedded perl ran %s with error %s\n",fname,SvPV(ERRSV,PL_na)); 122 printf("embedded perl ran %s with error %s\n", fname, SvPV(ERRSV, PL_na));
128 } 123 }
129 124
130 /* read back stdout from script */ 125 /* read back stdout from script */
131 fp=fopen(tmpfname, "r"); 126 fp = fopen(tmpfname, "r");
132 127
133 /* default return string in case nothing was returned */ 128 /* default return string in case nothing was returned */
134 strcpy(plugin_output,"(No output!)"); 129 strcpy(plugin_output, "(No output!)");
135
136 fgets(plugin_output,sizeof(plugin_output)-1,fp);
137 plugin_output[sizeof(plugin_output)-1]='\x0';
138 fclose(fp);
139 unlink(tmpfname);
140 printf("embedded perl plugin output was %d,%s\n",pclose_result, plugin_output);
141 130
131 fgets(plugin_output, sizeof(plugin_output) - 1, fp);
132 plugin_output[sizeof(plugin_output) - 1] = '\x0';
133 fclose(fp);
134 unlink(tmpfname);
135 printf("embedded perl plugin output was %d,%s\n", pclose_result, plugin_output);
142 } 136 }
143
144 } 137 }
145 138
146
147 PL_perl_destruct_level = 0; 139 PL_perl_destruct_level = 0;
148 perl_destruct(perl); 140 perl_destruct(perl);
149 perl_free(perl); 141 perl_free(perl);