summaryrefslogtreecommitdiffstats
path: root/plugins
diff options
context:
space:
mode:
Diffstat (limited to 'plugins')
-rw-r--r--plugins/Makefile.am9
-rw-r--r--plugins/check_apt.c94
-rw-r--r--plugins/check_by_ssh.c9
-rw-r--r--plugins/check_cluster.c10
-rw-r--r--plugins/check_curl.c2467
-rw-r--r--plugins/check_dbi.c1
-rw-r--r--plugins/check_dig.c8
-rw-r--r--plugins/check_disk.c61
-rw-r--r--plugins/check_dns.c108
-rw-r--r--plugins/check_fping.c2
-rw-r--r--plugins/check_hpjd.c12
-rw-r--r--plugins/check_http.c120
-rw-r--r--plugins/check_ide_smart.c28
-rw-r--r--plugins/check_ldap.c4
-rw-r--r--plugins/check_load.c63
-rw-r--r--plugins/check_mysql.c3
-rw-r--r--plugins/check_mysql_query.c12
-rw-r--r--plugins/check_ntp.c10
-rw-r--r--plugins/check_ntp_peer.c2
-rw-r--r--plugins/check_ntp_time.c8
-rw-r--r--plugins/check_pgsql.c5
-rw-r--r--plugins/check_procs.c5
-rw-r--r--plugins/check_radius.c42
-rw-r--r--plugins/check_real.c2
-rw-r--r--plugins/check_smtp.c52
-rw-r--r--plugins/check_snmp.c24
-rw-r--r--plugins/check_swap.c16
-rw-r--r--plugins/check_tcp.c27
-rw-r--r--plugins/check_users.c60
-rw-r--r--plugins/common.h26
-rw-r--r--plugins/negate.c8
-rw-r--r--plugins/netutils.c15
-rw-r--r--plugins/netutils.h7
-rw-r--r--plugins/picohttpparser/Makefile.am3
-rw-r--r--plugins/picohttpparser/picohttpparser.c645
-rw-r--r--plugins/picohttpparser/picohttpparser.h87
-rw-r--r--plugins/popen.c85
-rw-r--r--plugins/popen.h1
-rw-r--r--plugins/runcmd.c23
-rw-r--r--plugins/sslutils.c50
-rw-r--r--plugins/t/NPTest.cache.travis58
-rw-r--r--plugins/t/check_apt.t18
-rw-r--r--plugins/t/check_by_ssh.t14
-rw-r--r--plugins/t/check_curl.t201
-rw-r--r--plugins/t/check_disk.t8
-rw-r--r--plugins/t/check_dns.t26
-rw-r--r--plugins/t/check_fping.t44
-rw-r--r--plugins/t/check_ftp.t11
-rw-r--r--plugins/t/check_http.t163
-rw-r--r--plugins/t/check_imap.t15
-rw-r--r--plugins/t/check_jabber.t20
-rw-r--r--plugins/t/check_ldap.t17
-rw-r--r--plugins/t/check_mysql.t29
-rw-r--r--plugins/t/check_mysql_query.t11
-rw-r--r--plugins/t/check_snmp.t24
-rw-r--r--plugins/t/check_ssh.t14
-rw-r--r--plugins/t/check_tcp.t25
-rw-r--r--plugins/t/check_time.t11
-rw-r--r--plugins/t/check_udp.t6
-rw-r--r--plugins/t/check_users.t4
-rw-r--r--plugins/tests/certs/expired-cert.pem41
-rw-r--r--plugins/tests/certs/expired-key.pem43
-rw-r--r--plugins/tests/certs/server-cert.pem41
-rw-r--r--plugins/tests/certs/server-key.pem43
-rwxr-xr-xplugins/tests/check_curl.t509
-rwxr-xr-xplugins/tests/check_http.t89
-rwxr-xr-xplugins/tests/check_snmp.t110
-rw-r--r--plugins/utils.c86
-rw-r--r--plugins/utils.h45
69 files changed, 5072 insertions, 868 deletions
diff --git a/plugins/Makefile.am b/plugins/Makefile.am
index 0ddf9bd..3fde54d 100644
--- a/plugins/Makefile.am
+++ b/plugins/Makefile.am
@@ -38,7 +38,9 @@ check_tcp_programs = check_ftp check_imap check_nntp check_pop \
38EXTRA_PROGRAMS = check_mysql check_radius check_pgsql check_snmp check_hpjd \ 38EXTRA_PROGRAMS = check_mysql check_radius check_pgsql check_snmp check_hpjd \
39 check_swap check_fping check_ldap check_game check_dig \ 39 check_swap check_fping check_ldap check_game check_dig \
40 check_nagios check_by_ssh check_dns check_nt check_ide_smart \ 40 check_nagios check_by_ssh check_dns check_nt check_ide_smart \
41 check_procs check_mysql_query check_apt check_dbi 41 check_procs check_mysql_query check_apt check_dbi check_curl
42
43SUBDIRS = picohttpparser
42 44
43EXTRA_DIST = t tests 45EXTRA_DIST = t tests
44 46
@@ -69,6 +71,9 @@ test-debug:
69 71
70check_apt_LDADD = $(BASEOBJS) 72check_apt_LDADD = $(BASEOBJS)
71check_cluster_LDADD = $(BASEOBJS) 73check_cluster_LDADD = $(BASEOBJS)
74check_curl_CFLAGS = $(AM_CFLAGS) $(LIBCURLCFLAGS) $(URIPARSERCFLAGS) $(LIBCURLINCLUDE) $(URIPARSERINCLUDE) -Ipicohttpparser
75check_curl_CPPFLAGS = $(AM_CPPFLAGS) $(LIBCURLCFLAGS) $(URIPARSERCFLAGS) $(LIBCURLINCLUDE) $(URIPARSERINCLUDE) -Ipicohttpparser
76check_curl_LDADD = $(NETLIBS) $(LIBCURLLIBS) $(SSLOBJS) $(URIPARSERLIBS) picohttpparser/libpicohttpparser.a
72check_dbi_LDADD = $(NETLIBS) $(DBILIBS) 77check_dbi_LDADD = $(NETLIBS) $(DBILIBS)
73check_dig_LDADD = $(NETLIBS) 78check_dig_LDADD = $(NETLIBS)
74check_disk_LDADD = $(BASEOBJS) 79check_disk_LDADD = $(BASEOBJS)
@@ -89,7 +94,7 @@ check_mysql_query_CFLAGS = $(AM_CFLAGS) $(MYSQLCFLAGS)
89check_mysql_query_CPPFLAGS = $(AM_CPPFLAGS) $(MYSQLINCLUDE) 94check_mysql_query_CPPFLAGS = $(AM_CPPFLAGS) $(MYSQLINCLUDE)
90check_mysql_query_LDADD = $(NETLIBS) $(MYSQLLIBS) 95check_mysql_query_LDADD = $(NETLIBS) $(MYSQLLIBS)
91check_nagios_LDADD = $(BASEOBJS) 96check_nagios_LDADD = $(BASEOBJS)
92check_nt_LDADD = $(NETLIBS) 97check_nt_LDADD = $(NETLIBS)
93check_ntp_LDADD = $(NETLIBS) $(MATHLIBS) 98check_ntp_LDADD = $(NETLIBS) $(MATHLIBS)
94check_ntp_peer_LDADD = $(NETLIBS) $(MATHLIBS) 99check_ntp_peer_LDADD = $(NETLIBS) $(MATHLIBS)
95check_nwstat_LDADD = $(NETLIBS) 100check_nwstat_LDADD = $(NETLIBS)
diff --git a/plugins/check_apt.c b/plugins/check_apt.c
index a639a41..d7be575 100644
--- a/plugins/check_apt.c
+++ b/plugins/check_apt.c
@@ -66,13 +66,19 @@ char* construct_cmdline(upgrade_type u, const char *opts);
66/* run an apt-get update */ 66/* run an apt-get update */
67int run_update(void); 67int run_update(void);
68/* run an apt-get upgrade */ 68/* run an apt-get upgrade */
69int run_upgrade(int *pkgcount, int *secpkgcount); 69int run_upgrade(int *pkgcount, int *secpkgcount, char ***pkglist, char ***secpkglist);
70/* add another clause to a regexp */ 70/* add another clause to a regexp */
71char* add_to_regexp(char *expr, const char *next); 71char* add_to_regexp(char *expr, const char *next);
72/* extract package name from Inst line */
73char* pkg_name(char *line);
74/* string comparison function for qsort */
75int cmpstringp(const void *p1, const void *p2);
72 76
73/* configuration variables */ 77/* configuration variables */
74static int verbose = 0; /* -v */ 78static int verbose = 0; /* -v */
79static int list = 0; /* list packages available for upgrade */
75static int do_update = 0; /* whether to call apt-get update */ 80static int do_update = 0; /* whether to call apt-get update */
81static int only_critical = 0; /* whether to warn about non-critical updates */
76static upgrade_type upgrade = UPGRADE; /* which type of upgrade to do */ 82static upgrade_type upgrade = UPGRADE; /* which type of upgrade to do */
77static char *upgrade_opts = NULL; /* options to override defaults for upgrade */ 83static char *upgrade_opts = NULL; /* options to override defaults for upgrade */
78static char *update_opts = NULL; /* options to override defaults for update */ 84static char *update_opts = NULL; /* options to override defaults for update */
@@ -80,13 +86,16 @@ static char *do_include = NULL; /* regexp to only include certain packages */
80static char *do_exclude = NULL; /* regexp to only exclude certain packages */ 86static char *do_exclude = NULL; /* regexp to only exclude certain packages */
81static char *do_critical = NULL; /* regexp specifying critical packages */ 87static char *do_critical = NULL; /* regexp specifying critical packages */
82static char *input_filename = NULL; /* input filename for testing */ 88static char *input_filename = NULL; /* input filename for testing */
89/* number of packages available for upgrade to return WARNING status */
90static int packages_warning = 1;
83 91
84/* other global variables */ 92/* other global variables */
85static int stderr_warning = 0; /* if a cmd issued output on stderr */ 93static int stderr_warning = 0; /* if a cmd issued output on stderr */
86static int exec_warning = 0; /* if a cmd exited non-zero */ 94static int exec_warning = 0; /* if a cmd exited non-zero */
87 95
88int main (int argc, char **argv) { 96int main (int argc, char **argv) {
89 int result=STATE_UNKNOWN, packages_available=0, sec_count=0; 97 int result=STATE_UNKNOWN, packages_available=0, sec_count=0, i=0;
98 char **packages_list=NULL, **secpackages_list=NULL;
90 99
91 /* Parse extra opts if any */ 100 /* Parse extra opts if any */
92 argv=np_extra_opts(&argc, argv, progname); 101 argv=np_extra_opts(&argc, argv, progname);
@@ -106,11 +115,11 @@ int main (int argc, char **argv) {
106 if(do_update) result = run_update(); 115 if(do_update) result = run_update();
107 116
108 /* apt-get upgrade */ 117 /* apt-get upgrade */
109 result = max_state(result, run_upgrade(&packages_available, &sec_count)); 118 result = max_state(result, run_upgrade(&packages_available, &sec_count, &packages_list, &secpackages_list));
110 119
111 if(sec_count > 0){ 120 if(sec_count > 0){
112 result = max_state(result, STATE_CRITICAL); 121 result = max_state(result, STATE_CRITICAL);
113 } else if(packages_available > 0){ 122 } else if(packages_available >= packages_warning && only_critical == 0){
114 result = max_state(result, STATE_WARNING); 123 result = max_state(result, STATE_WARNING);
115 } else if(result > STATE_UNKNOWN){ 124 } else if(result > STATE_UNKNOWN){
116 result = STATE_UNKNOWN; 125 result = STATE_UNKNOWN;
@@ -129,6 +138,18 @@ int main (int argc, char **argv) {
129 sec_count 138 sec_count
130 ); 139 );
131 140
141 if(list) {
142 qsort(secpackages_list, sec_count, sizeof(char*), cmpstringp);
143 qsort(packages_list, packages_available-sec_count, sizeof(char*), cmpstringp);
144
145 for(i = 0; i < sec_count; i++)
146 printf("%s (security)\n", secpackages_list[i]);
147 if (only_critical == 0) {
148 for(i = 0; i < packages_available - sec_count; i++)
149 printf("%s\n", packages_list[i]);
150 }
151 }
152
132 return result; 153 return result;
133} 154}
134 155
@@ -145,15 +166,18 @@ int process_arguments (int argc, char **argv) {
145 {"upgrade", optional_argument, 0, 'U'}, 166 {"upgrade", optional_argument, 0, 'U'},
146 {"no-upgrade", no_argument, 0, 'n'}, 167 {"no-upgrade", no_argument, 0, 'n'},
147 {"dist-upgrade", optional_argument, 0, 'd'}, 168 {"dist-upgrade", optional_argument, 0, 'd'},
169 {"list", no_argument, 0, 'l'},
148 {"include", required_argument, 0, 'i'}, 170 {"include", required_argument, 0, 'i'},
149 {"exclude", required_argument, 0, 'e'}, 171 {"exclude", required_argument, 0, 'e'},
150 {"critical", required_argument, 0, 'c'}, 172 {"critical", required_argument, 0, 'c'},
173 {"only-critical", no_argument, 0, 'o'},
151 {"input-file", required_argument, 0, INPUT_FILE_OPT}, 174 {"input-file", required_argument, 0, INPUT_FILE_OPT},
175 {"packages-warning", required_argument, 0, 'w'},
152 {0, 0, 0, 0} 176 {0, 0, 0, 0}
153 }; 177 };
154 178
155 while(1) { 179 while(1) {
156 c = getopt_long(argc, argv, "hVvt:u::U::d::ni:e:c:", longopts, NULL); 180 c = getopt_long(argc, argv, "hVvt:u::U::d::nli:e:c:ow:", longopts, NULL);
157 181
158 if(c == -1 || c == EOF || c == 1) break; 182 if(c == -1 || c == EOF || c == 1) break;
159 183
@@ -194,6 +218,9 @@ int process_arguments (int argc, char **argv) {
194 if(update_opts==NULL) die(STATE_UNKNOWN, "strdup failed"); 218 if(update_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
195 } 219 }
196 break; 220 break;
221 case 'l':
222 list=1;
223 break;
197 case 'i': 224 case 'i':
198 do_include=add_to_regexp(do_include, optarg); 225 do_include=add_to_regexp(do_include, optarg);
199 break; 226 break;
@@ -203,9 +230,15 @@ int process_arguments (int argc, char **argv) {
203 case 'c': 230 case 'c':
204 do_critical=add_to_regexp(do_critical, optarg); 231 do_critical=add_to_regexp(do_critical, optarg);
205 break; 232 break;
233 case 'o':
234 only_critical=1;
235 break;
206 case INPUT_FILE_OPT: 236 case INPUT_FILE_OPT:
207 input_filename = optarg; 237 input_filename = optarg;
208 break; 238 break;
239 case 'w':
240 packages_warning = atoi(optarg);
241 break;
209 default: 242 default:
210 /* print short usage statement if args not parsable */ 243 /* print short usage statement if args not parsable */
211 usage5(); 244 usage5();
@@ -217,7 +250,7 @@ int process_arguments (int argc, char **argv) {
217 250
218 251
219/* run an apt-get upgrade */ 252/* run an apt-get upgrade */
220int run_upgrade(int *pkgcount, int *secpkgcount){ 253int run_upgrade(int *pkgcount, int *secpkgcount, char ***pkglist, char ***secpkglist){
221 int i=0, result=STATE_UNKNOWN, regres=0, pc=0, spc=0; 254 int i=0, result=STATE_UNKNOWN, regres=0, pc=0, spc=0;
222 struct output chld_out, chld_err; 255 struct output chld_out, chld_err;
223 regex_t ireg, ereg, sreg; 256 regex_t ireg, ereg, sreg;
@@ -273,6 +306,11 @@ int run_upgrade(int *pkgcount, int *secpkgcount){
273 cmdline); 306 cmdline);
274 } 307 }
275 308
309 *pkglist=malloc(sizeof(char *) * chld_out.lines);
310 if(!pkglist) die(STATE_UNKNOWN, "malloc failed!\n");
311 *secpkglist=malloc(sizeof(char *) * chld_out.lines);
312 if(!secpkglist) die(STATE_UNKNOWN, "malloc failed!\n");
313
276 /* parse the output, which should only consist of lines like 314 /* parse the output, which should only consist of lines like
277 * 315 *
278 * Inst package .... 316 * Inst package ....
@@ -297,6 +335,9 @@ int run_upgrade(int *pkgcount, int *secpkgcount){
297 if(regexec(&sreg, chld_out.line[i], 0, NULL, 0)==0){ 335 if(regexec(&sreg, chld_out.line[i], 0, NULL, 0)==0){
298 spc++; 336 spc++;
299 if(verbose) printf("*"); 337 if(verbose) printf("*");
338 (*secpkglist)[spc-1] = pkg_name(chld_out.line[i]);
339 } else {
340 (*pkglist)[pc-spc-1] = pkg_name(chld_out.line[i]);
300 } 341 }
301 if(verbose){ 342 if(verbose){
302 printf("*%s\n", chld_out.line[i]); 343 printf("*%s\n", chld_out.line[i]);
@@ -363,6 +404,31 @@ int run_update(void){
363 return result; 404 return result;
364} 405}
365 406
407char* pkg_name(char *line){
408 char *start=NULL, *space=NULL, *pkg=NULL;
409 int len=0;
410
411 start = line + strlen(PKGINST_PREFIX);
412 len = strlen(start);
413
414 space = index(start, ' ');
415 if(space!=NULL){
416 len = space - start;
417 }
418
419 pkg=malloc(sizeof(char)*(len+1));
420 if(!pkg) die(STATE_UNKNOWN, "malloc failed!\n");
421
422 strncpy(pkg, start, len);
423 pkg[len]='\0';
424
425 return pkg;
426}
427
428int cmpstringp(const void *p1, const void *p2){
429 return strcmp(* (char * const *) p1, * (char * const *) p2);
430}
431
366char* add_to_regexp(char *expr, const char *next){ 432char* add_to_regexp(char *expr, const char *next){
367 char *re=NULL; 433 char *re=NULL;
368 434
@@ -445,8 +511,11 @@ print_help (void)
445 printf (" %s\n", "-d, --dist-upgrade=OPTS"); 511 printf (" %s\n", "-d, --dist-upgrade=OPTS");
446 printf (" %s\n", _("Perform a dist-upgrade instead of normal upgrade. Like with -U OPTS")); 512 printf (" %s\n", _("Perform a dist-upgrade instead of normal upgrade. Like with -U OPTS"));
447 printf (" %s\n", _("can be provided to override the default options.")); 513 printf (" %s\n", _("can be provided to override the default options."));
448 printf (" %s\n", " -n, --no-upgrade"); 514 printf (" %s\n", "-n, --no-upgrade");
449 printf (" %s\n", _("Do not run the upgrade. Probably not useful (without -u at least).")); 515 printf (" %s\n", _("Do not run the upgrade. Probably not useful (without -u at least)."));
516 printf (" %s\n", "-l, --list");
517 printf (" %s\n", _("List packages available for upgrade. Packages are printed sorted by"));
518 printf (" %s\n", _("name with security packages listed first."));
450 printf (" %s\n", "-i, --include=REGEXP"); 519 printf (" %s\n", "-i, --include=REGEXP");
451 printf (" %s\n", _("Include only packages matching REGEXP. Can be specified multiple times")); 520 printf (" %s\n", _("Include only packages matching REGEXP. Can be specified multiple times"));
452 printf (" %s\n", _("the values will be combined together. Any packages matching this list")); 521 printf (" %s\n", _("the values will be combined together. Any packages matching this list"));
@@ -463,7 +532,14 @@ print_help (void)
463 printf (" %s\n", _("upgrades for Debian and Ubuntu:")); 532 printf (" %s\n", _("upgrades for Debian and Ubuntu:"));
464 printf (" \t\%s\n", SECURITY_RE); 533 printf (" \t\%s\n", SECURITY_RE);
465 printf (" %s\n", _("Note that the package must first match the include list before its")); 534 printf (" %s\n", _("Note that the package must first match the include list before its"));
466 printf (" %s\n\n", _("information is compared against the critical list.")); 535 printf (" %s\n", _("information is compared against the critical list."));
536 printf (" %s\n", "-o, --only-critical");
537 printf (" %s\n", _("Only warn about upgrades matching the critical list. The total number"));
538 printf (" %s\n", _("of upgrades will be printed, but any non-critical upgrades will not cause"));
539 printf (" %s\n", _("the plugin to return WARNING status."));
540 printf (" %s\n", "-w, --packages-warning");
541 printf (" %s\n", _("Minumum number of packages available for upgrade to return WARNING status."));
542 printf (" %s\n\n", _("Default is 1 package."));
467 543
468 printf ("%s\n\n", _("The following options require root privileges and should be used with care:")); 544 printf ("%s\n\n", _("The following options require root privileges and should be used with care:"));
469 printf (" %s\n", "-u, --update=OPTS"); 545 printf (" %s\n", "-u, --update=OPTS");
@@ -481,5 +557,5 @@ void
481print_usage(void) 557print_usage(void)
482{ 558{
483 printf ("%s\n", _("Usage:")); 559 printf ("%s\n", _("Usage:"));
484 printf ("%s [[-d|-u|-U]opts] [-n] [-t timeout]\n", progname); 560 printf ("%s [[-d|-u|-U]opts] [-n] [-l] [-t timeout] [-w packages-warning]\n", progname);
485} 561}
diff --git a/plugins/check_by_ssh.c b/plugins/check_by_ssh.c
index 04bce38..485bf3b 100644
--- a/plugins/check_by_ssh.c
+++ b/plugins/check_by_ssh.c
@@ -100,6 +100,13 @@ main (int argc, char **argv)
100 100
101 result = cmd_run_array (commargv, &chld_out, &chld_err, 0); 101 result = cmd_run_array (commargv, &chld_out, &chld_err, 0);
102 102
103 if (verbose) {
104 for(i = 0; i < chld_out.lines; i++)
105 printf("stdout: %s\n", chld_out.line[i]);
106 for(i = 0; i < chld_err.lines; i++)
107 printf("stderr: %s\n", chld_err.line[i]);
108 }
109
103 if (skip_stdout == -1) /* --skip-stdout specified without argument */ 110 if (skip_stdout == -1) /* --skip-stdout specified without argument */
104 skip_stdout = chld_out.lines; 111 skip_stdout = chld_out.lines;
105 if (skip_stderr == -1) /* --skip-stderr specified without argument */ 112 if (skip_stderr == -1) /* --skip-stderr specified without argument */
@@ -223,7 +230,6 @@ process_arguments (int argc, char **argv)
223 timeout_interval = atoi (optarg); 230 timeout_interval = atoi (optarg);
224 break; 231 break;
225 case 'H': /* host */ 232 case 'H': /* host */
226 host_or_die(optarg);
227 hostname = optarg; 233 hostname = optarg;
228 break; 234 break;
229 case 'p': /* port number */ 235 case 'p': /* port number */
@@ -322,7 +328,6 @@ process_arguments (int argc, char **argv)
322 if (c <= argc) { 328 if (c <= argc) {
323 die (STATE_UNKNOWN, _("%s: You must provide a host name\n"), progname); 329 die (STATE_UNKNOWN, _("%s: You must provide a host name\n"), progname);
324 } 330 }
325 host_or_die(argv[c]);
326 hostname = argv[c++]; 331 hostname = argv[c++];
327 } 332 }
328 333
diff --git a/plugins/check_cluster.c b/plugins/check_cluster.c
index b86e501..e1ede9f 100644
--- a/plugins/check_cluster.c
+++ b/plugins/check_cluster.c
@@ -143,6 +143,7 @@ int main(int argc, char **argv){
143 143
144int process_arguments(int argc, char **argv){ 144int process_arguments(int argc, char **argv){
145 int c; 145 int c;
146 char *ptr;
146 int option=0; 147 int option=0;
147 static struct option longopts[]={ 148 static struct option longopts[]={
148 {"data", required_argument,0,'d'}, 149 {"data", required_argument,0,'d'},
@@ -188,6 +189,15 @@ int process_arguments(int argc, char **argv){
188 189
189 case 'd': /* data values */ 190 case 'd': /* data values */
190 data_vals=(char *)strdup(optarg); 191 data_vals=(char *)strdup(optarg);
192 /* validate data */
193 for (ptr=data_vals;ptr!=NULL;ptr+=2){
194 if (ptr[0]<'0' || ptr[0]>'3')
195 return ERROR;
196 if (ptr[1]=='\0')
197 break;
198 if (ptr[1]!=',')
199 return ERROR;
200 }
191 break; 201 break;
192 202
193 case 'l': /* text label */ 203 case 'l': /* text label */
diff --git a/plugins/check_curl.c b/plugins/check_curl.c
new file mode 100644
index 0000000..5990b95
--- /dev/null
+++ b/plugins/check_curl.c
@@ -0,0 +1,2467 @@
1/*****************************************************************************
2*
3* Monitoring check_curl plugin
4*
5* License: GPL
6* Copyright (c) 1999-2019 Monitoring Plugins Development Team
7*
8* Description:
9*
10* This file contains the check_curl plugin
11*
12* This plugin tests the HTTP service on the specified host. It can test
13* normal (http) and secure (https) servers, follow redirects, search for
14* strings and regular expressions, check connection times, and report on
15* certificate expiration times.
16*
17* This plugin uses functions from the curl library, see
18* http://curl.haxx.se
19*
20* This program is free software: you can redistribute it and/or modify
21* it under the terms of the GNU General Public License as published by
22* the Free Software Foundation, either version 3 of the License, or
23* (at your option) any later version.
24*
25* This program is distributed in the hope that it will be useful,
26* but WITHOUT ANY WARRANTY; without even the implied warranty of
27* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28* GNU General Public License for more details.
29*
30* You should have received a copy of the GNU General Public License
31* along with this program. If not, see <http://www.gnu.org/licenses/>.
32*
33*
34*****************************************************************************/
35const char *progname = "check_curl";
36
37const char *copyright = "2006-2019";
38const char *email = "devel@monitoring-plugins.org";
39
40#include <ctype.h>
41
42#include "common.h"
43#include "utils.h"
44
45#ifndef LIBCURL_PROTOCOL_HTTP
46#error libcurl compiled without HTTP support, compiling check_curl plugin does not makes a lot of sense
47#endif
48
49#include "curl/curl.h"
50#include "curl/easy.h"
51
52#include "picohttpparser.h"
53
54#include "uriparser/Uri.h"
55
56#include <arpa/inet.h>
57
58#if defined(HAVE_SSL) && defined(USE_OPENSSL)
59#include <openssl/opensslv.h>
60#endif
61
62#include <netdb.h>
63
64#define MAKE_LIBCURL_VERSION(major, minor, patch) ((major)*0x10000 + (minor)*0x100 + (patch))
65
66#define DEFAULT_BUFFER_SIZE 2048
67#define DEFAULT_SERVER_URL "/"
68#define HTTP_EXPECT "HTTP/"
69#define DEFAULT_MAX_REDIRS 15
70#define INET_ADDR_MAX_SIZE INET6_ADDRSTRLEN
71enum {
72 MAX_IPV4_HOSTLENGTH = 255,
73 HTTP_PORT = 80,
74 HTTPS_PORT = 443,
75 MAX_PORT = 65535
76};
77
78enum {
79 STICKY_NONE = 0,
80 STICKY_HOST = 1,
81 STICKY_PORT = 2
82};
83
84enum {
85 FOLLOW_HTTP_CURL = 0,
86 FOLLOW_LIBCURL = 1
87};
88
89/* for buffers for header and body */
90typedef struct {
91 char *buf;
92 size_t buflen;
93 size_t bufsize;
94} curlhelp_write_curlbuf;
95
96/* for buffering the data sent in PUT */
97typedef struct {
98 char *buf;
99 size_t buflen;
100 off_t pos;
101} curlhelp_read_curlbuf;
102
103/* for parsing the HTTP status line */
104typedef struct {
105 int http_major; /* major version of the protocol, always 1 (HTTP/0.9
106 * never reached the big internet most likely) */
107 int http_minor; /* minor version of the protocol, usually 0 or 1 */
108 int http_code; /* HTTP return code as in RFC 2145 */
109 int http_subcode; /* Microsoft IIS extension, HTTP subcodes, see
110 * http://support.microsoft.com/kb/318380/en-us */
111 const char *msg; /* the human readable message */
112 char *first_line; /* a copy of the first line */
113} curlhelp_statusline;
114
115/* to know the underlying SSL library used by libcurl */
116typedef enum curlhelp_ssl_library {
117 CURLHELP_SSL_LIBRARY_UNKNOWN,
118 CURLHELP_SSL_LIBRARY_OPENSSL,
119 CURLHELP_SSL_LIBRARY_LIBRESSL,
120 CURLHELP_SSL_LIBRARY_GNUTLS,
121 CURLHELP_SSL_LIBRARY_NSS
122} curlhelp_ssl_library;
123
124enum {
125 REGS = 2,
126 MAX_RE_SIZE = 1024
127};
128#include "regex.h"
129regex_t preg;
130regmatch_t pmatch[REGS];
131char regexp[MAX_RE_SIZE];
132int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE;
133int errcode;
134int invert_regex = 0;
135
136char *server_address = NULL;
137char *host_name = NULL;
138char *server_url = 0;
139char server_ip[DEFAULT_BUFFER_SIZE];
140struct curl_slist *server_ips = NULL;
141int specify_port = FALSE;
142unsigned short server_port = HTTP_PORT;
143unsigned short virtual_port = 0;
144int host_name_length;
145char output_header_search[30] = "";
146char output_string_search[30] = "";
147char *warning_thresholds = NULL;
148char *critical_thresholds = NULL;
149int days_till_exp_warn, days_till_exp_crit;
150thresholds *thlds;
151char user_agent[DEFAULT_BUFFER_SIZE];
152int verbose = 0;
153int show_extended_perfdata = FALSE;
154int show_body = FALSE;
155int min_page_len = 0;
156int max_page_len = 0;
157int redir_depth = 0;
158int max_depth = DEFAULT_MAX_REDIRS;
159char *http_method = NULL;
160char *http_post_data = NULL;
161char *http_content_type = NULL;
162CURL *curl;
163struct curl_slist *header_list = NULL;
164curlhelp_write_curlbuf body_buf;
165curlhelp_write_curlbuf header_buf;
166curlhelp_statusline status_line;
167curlhelp_read_curlbuf put_buf;
168char http_header[DEFAULT_BUFFER_SIZE];
169long code;
170long socket_timeout = DEFAULT_SOCKET_TIMEOUT;
171double total_time;
172double time_connect;
173double time_appconnect;
174double time_headers;
175double time_firstbyte;
176char errbuf[CURL_ERROR_SIZE+1];
177CURLcode res;
178char url[DEFAULT_BUFFER_SIZE];
179char msg[DEFAULT_BUFFER_SIZE];
180char perfstring[DEFAULT_BUFFER_SIZE];
181char header_expect[MAX_INPUT_BUFFER] = "";
182char string_expect[MAX_INPUT_BUFFER] = "";
183char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT;
184int server_expect_yn = 0;
185char user_auth[MAX_INPUT_BUFFER] = "";
186char proxy_auth[MAX_INPUT_BUFFER] = "";
187char **http_opt_headers;
188int http_opt_headers_count = 0;
189int display_html = FALSE;
190int onredirect = STATE_OK;
191int followmethod = FOLLOW_HTTP_CURL;
192int followsticky = STICKY_NONE;
193int use_ssl = FALSE;
194int use_sni = TRUE;
195int check_cert = FALSE;
196typedef union {
197 struct curl_slist* to_info;
198 struct curl_certinfo* to_certinfo;
199} cert_ptr_union;
200cert_ptr_union cert_ptr;
201int ssl_version = CURL_SSLVERSION_DEFAULT;
202char *client_cert = NULL;
203char *client_privkey = NULL;
204char *ca_cert = NULL;
205int verify_peer_and_host = FALSE;
206int is_openssl_callback = FALSE;
207#if defined(HAVE_SSL) && defined(USE_OPENSSL)
208X509 *cert = NULL;
209#endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */
210int no_body = FALSE;
211int maximum_age = -1;
212int address_family = AF_UNSPEC;
213curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN;
214int curl_http_version = CURL_HTTP_VERSION_NONE;
215int automatic_decompression = FALSE;
216
217int process_arguments (int, char**);
218void handle_curl_option_return_code (CURLcode res, const char* option);
219int check_http (void);
220void redir (curlhelp_write_curlbuf*);
221char *perfd_time (double microsec);
222char *perfd_time_connect (double microsec);
223char *perfd_time_ssl (double microsec);
224char *perfd_time_firstbyte (double microsec);
225char *perfd_time_headers (double microsec);
226char *perfd_time_transfer (double microsec);
227char *perfd_size (int page_len);
228void print_help (void);
229void print_usage (void);
230void print_curl_version (void);
231int curlhelp_initwritebuffer (curlhelp_write_curlbuf*);
232int curlhelp_buffer_write_callback (void*, size_t , size_t , void*);
233void curlhelp_freewritebuffer (curlhelp_write_curlbuf*);
234int curlhelp_initreadbuffer (curlhelp_read_curlbuf *, const char *, size_t);
235int curlhelp_buffer_read_callback (void *, size_t , size_t , void *);
236void curlhelp_freereadbuffer (curlhelp_read_curlbuf *);
237curlhelp_ssl_library curlhelp_get_ssl_library (CURL*);
238const char* curlhelp_get_ssl_library_string (curlhelp_ssl_library);
239int net_noopenssl_check_certificate (cert_ptr_union*, int, int);
240
241int curlhelp_parse_statusline (const char*, curlhelp_statusline *);
242void curlhelp_free_statusline (curlhelp_statusline *);
243char *get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header);
244int check_document_dates (const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]);
245int get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_write_curlbuf* body_buf);
246
247#if defined(HAVE_SSL) && defined(USE_OPENSSL)
248int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit);
249#endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */
250
251void remove_newlines (char *);
252void test_file (char *);
253
254int
255main (int argc, char **argv)
256{
257 int result = STATE_UNKNOWN;
258
259 setlocale (LC_ALL, "");
260 bindtextdomain (PACKAGE, LOCALEDIR);
261 textdomain (PACKAGE);
262
263 /* Parse extra opts if any */
264 argv = np_extra_opts (&argc, argv, progname);
265
266 /* set defaults */
267 snprintf( user_agent, DEFAULT_BUFFER_SIZE, "%s/v%s (monitoring-plugins %s, %s)",
268 progname, NP_VERSION, VERSION, curl_version());
269
270 /* parse arguments */
271 if (process_arguments (argc, argv) == ERROR)
272 usage4 (_("Could not parse arguments"));
273
274 if (display_html == TRUE)
275 printf ("<A HREF=\"%s://%s:%d%s\" target=\"_blank\">",
276 use_ssl ? "https" : "http",
277 host_name ? host_name : server_address,
278 virtual_port ? virtual_port : server_port,
279 server_url);
280
281 result = check_http ();
282 return result;
283}
284
285#ifdef HAVE_SSL
286#ifdef USE_OPENSSL
287
288int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
289{
290 /* TODO: we get all certificates of the chain, so which ones
291 * should we test?
292 * TODO: is the last certificate always the server certificate?
293 */
294 cert = X509_STORE_CTX_get_current_cert(x509_ctx);
295#if OPENSSL_VERSION_NUMBER >= 0x10100000L
296 X509_up_ref(cert);
297#endif
298 if (verbose>=2) {
299 puts("* SSL verify callback with certificate:");
300 X509_NAME *subject, *issuer;
301 printf("* issuer:\n");
302 issuer = X509_get_issuer_name( cert );
303 X509_NAME_print_ex_fp(stdout, issuer, 5, XN_FLAG_MULTILINE);
304 printf("* curl verify_callback:\n* subject:\n");
305 subject = X509_get_subject_name( cert );
306 X509_NAME_print_ex_fp(stdout, subject, 5, XN_FLAG_MULTILINE);
307 puts("");
308 }
309 return 1;
310}
311
312CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm)
313{
314 SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback);
315
316 return CURLE_OK;
317}
318
319#endif /* USE_OPENSSL */
320#endif /* HAVE_SSL */
321
322/* returns a string "HTTP/1.x" or "HTTP/2" */
323static char *string_statuscode (int major, int minor)
324{
325 static char buf[10];
326
327 switch (major) {
328 case 1:
329 snprintf (buf, sizeof (buf), "HTTP/%d.%d", major, minor);
330 break;
331 case 2:
332 case 3:
333 snprintf (buf, sizeof (buf), "HTTP/%d", major);
334 break;
335 default:
336 /* assuming here HTTP/N with N>=4 */
337 snprintf (buf, sizeof (buf), "HTTP/%d", major);
338 break;
339 }
340
341 return buf;
342}
343
344/* Checks if the server 'reply' is one of the expected 'statuscodes' */
345static int
346expected_statuscode (const char *reply, const char *statuscodes)
347{
348 char *expected, *code;
349 int result = 0;
350
351 if ((expected = strdup (statuscodes)) == NULL)
352 die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n"));
353
354 for (code = strtok (expected, ","); code != NULL; code = strtok (NULL, ","))
355 if (strstr (reply, code) != NULL) {
356 result = 1;
357 break;
358 }
359
360 free (expected);
361 return result;
362}
363
364void
365handle_curl_option_return_code (CURLcode res, const char* option)
366{
367 if (res != CURLE_OK) {
368 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Error while setting cURL option '%s': cURL returned %d - %s"),
369 option, res, curl_easy_strerror(res));
370 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
371 }
372}
373
374int
375lookup_host (const char *host, char *buf, size_t buflen)
376{
377 struct addrinfo hints, *res, *result;
378 int errcode;
379 void *ptr;
380
381 memset (&hints, 0, sizeof (hints));
382 hints.ai_family = address_family;
383 hints.ai_socktype = SOCK_STREAM;
384 hints.ai_flags |= AI_CANONNAME;
385
386 errcode = getaddrinfo (host, NULL, &hints, &result);
387 if (errcode != 0)
388 return errcode;
389
390 res = result;
391
392 while (res) {
393 inet_ntop (res->ai_family, res->ai_addr->sa_data, buf, buflen);
394 switch (res->ai_family) {
395 case AF_INET:
396 ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr;
397 break;
398 case AF_INET6:
399 ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr;
400 break;
401 }
402 inet_ntop (res->ai_family, ptr, buf, buflen);
403 if (verbose >= 1)
404 printf ("* getaddrinfo IPv%d address: %s\n",
405 res->ai_family == PF_INET6 ? 6 : 4, buf);
406 res = res->ai_next;
407 }
408
409 freeaddrinfo(result);
410
411 return 0;
412}
413
414int
415check_http (void)
416{
417 int result = STATE_OK;
418 int page_len = 0;
419 int i;
420 char *force_host_header = NULL;
421 struct curl_slist *host = NULL;
422 char addrstr[100];
423 char dnscache[DEFAULT_BUFFER_SIZE];
424
425 /* initialize curl */
426 if (curl_global_init (CURL_GLOBAL_DEFAULT) != CURLE_OK)
427 die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n");
428
429 if ((curl = curl_easy_init()) == NULL)
430 die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n");
431
432 if (verbose >= 1)
433 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_VERBOSE, TRUE), "CURLOPT_VERBOSE");
434
435 /* print everything on stdout like check_http would do */
436 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_STDERR, stdout), "CURLOPT_STDERR");
437
438 if (automatic_decompression)
439#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6)
440 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""), "CURLOPT_ACCEPT_ENCODING");
441#else
442 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_ENCODING, ""), "CURLOPT_ENCODING");
443#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 21, 6) */
444
445 /* initialize buffer for body of the answer */
446 if (curlhelp_initwritebuffer(&body_buf) < 0)
447 die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n");
448 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_WRITEFUNCTION");
449 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEDATA, (void *)&body_buf), "CURLOPT_WRITEDATA");
450
451 /* initialize buffer for header of the answer */
452 if (curlhelp_initwritebuffer( &header_buf ) < 0)
453 die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for header\n" );
454 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HEADERFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_HEADERFUNCTION");
455 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEHEADER, (void *)&header_buf), "CURLOPT_WRITEHEADER");
456
457 /* set the error buffer */
458 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, errbuf), "CURLOPT_ERRORBUFFER");
459
460 /* set timeouts */
461 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, socket_timeout), "CURLOPT_CONNECTTIMEOUT");
462 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_TIMEOUT, socket_timeout), "CURLOPT_TIMEOUT");
463
464 // fill dns resolve cache to make curl connect to the given server_address instead of the host_name, only required for ssl, because we use the host_name later on to make SNI happy
465 if(use_ssl && host_name != NULL) {
466 if ( (res=lookup_host (server_address, addrstr, 100)) != 0) {
467 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Unable to lookup IP address for '%s': getaddrinfo returned %d - %s"),
468 server_address, res, gai_strerror (res));
469 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
470 }
471 snprintf (dnscache, DEFAULT_BUFFER_SIZE, "%s:%d:%s", host_name, server_port, addrstr);
472 host = curl_slist_append(NULL, dnscache);
473 curl_easy_setopt(curl, CURLOPT_RESOLVE, host);
474 if (verbose>=1)
475 printf ("* curl CURLOPT_RESOLVE: %s\n", dnscache);
476 }
477
478 /* compose URL: use the address we want to connect to, set Host: header later */
479 snprintf (url, DEFAULT_BUFFER_SIZE, "%s://%s:%d%s",
480 use_ssl ? "https" : "http",
481 use_ssl & host_name != NULL ? host_name : server_address,
482 server_port,
483 server_url
484 );
485
486 if (verbose>=1)
487 printf ("* curl CURLOPT_URL: %s\n", url);
488 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, url), "CURLOPT_URL");
489
490 /* extract proxy information for legacy proxy https requests */
491 if (!strcmp(http_method, "CONNECT") || strstr(server_url, "http") == server_url) {
492 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXY, server_address), "CURLOPT_PROXY");
493 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXYPORT, (long)server_port), "CURLOPT_PROXYPORT");
494 if (verbose>=2)
495 printf ("* curl CURLOPT_PROXY: %s:%d\n", server_address, server_port);
496 http_method = "GET";
497 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, server_url), "CURLOPT_URL");
498 }
499
500 /* disable body for HEAD request */
501 if (http_method && !strcmp (http_method, "HEAD" )) {
502 no_body = TRUE;
503 }
504
505 /* set HTTP protocol version */
506 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HTTP_VERSION, curl_http_version), "CURLOPT_HTTP_VERSION");
507
508 /* set HTTP method */
509 if (http_method) {
510 if (!strcmp(http_method, "POST"))
511 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POST, 1), "CURLOPT_POST");
512 else if (!strcmp(http_method, "PUT"))
513 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_UPLOAD, 1), "CURLOPT_UPLOAD");
514 else
515 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CUSTOMREQUEST, http_method), "CURLOPT_CUSTOMREQUEST");
516 }
517
518 /* check if Host header is explicitly set in options */
519 if (http_opt_headers_count) {
520 for (i = 0; i < http_opt_headers_count ; i++) {
521 if (strncmp(http_opt_headers[i], "Host:", 5) == 0) {
522 force_host_header = http_opt_headers[i];
523 }
524 }
525 }
526
527 /* set hostname (virtual hosts), not needed if CURLOPT_CONNECT_TO is used, but left in anyway */
528 if(host_name != NULL && force_host_header == NULL) {
529 if((virtual_port != HTTP_PORT && !use_ssl) || (virtual_port != HTTPS_PORT && use_ssl)) {
530 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s:%d", host_name, virtual_port);
531 } else {
532 snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s", host_name);
533 }
534 header_list = curl_slist_append (header_list, http_header);
535 }
536
537 /* always close connection, be nice to servers */
538 snprintf (http_header, DEFAULT_BUFFER_SIZE, "Connection: close");
539 header_list = curl_slist_append (header_list, http_header);
540
541 /* attach additional headers supplied by the user */
542 /* optionally send any other header tag */
543 if (http_opt_headers_count) {
544 for (i = 0; i < http_opt_headers_count ; i++) {
545 header_list = curl_slist_append (header_list, http_opt_headers[i]);
546 }
547 /* This cannot be free'd here because a redirection will then try to access this and segfault */
548 /* Covered in a testcase in tests/check_http.t */
549 /* free(http_opt_headers); */
550 }
551
552 /* set HTTP headers */
553 handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPHEADER, header_list ), "CURLOPT_HTTPHEADER");
554
555#ifdef LIBCURL_FEATURE_SSL
556
557 /* set SSL version, warn about unsecure or unsupported versions */
558 if (use_ssl) {
559 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLVERSION, ssl_version), "CURLOPT_SSLVERSION");
560 }
561
562 /* client certificate and key to present to server (SSL) */
563 if (client_cert)
564 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLCERT, client_cert), "CURLOPT_SSLCERT");
565 if (client_privkey)
566 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLKEY, client_privkey), "CURLOPT_SSLKEY");
567 if (ca_cert) {
568 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO");
569 }
570 if (ca_cert || verify_peer_and_host) {
571 /* per default if we have a CA verify both the peer and the
572 * hostname in the certificate, can be switched off later */
573 handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER");
574 handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST");
575 } else {
576 /* backward-compatible behaviour, be tolerant in checks
577 * TODO: depending on more options have aspects we want
578 * to be less tolerant about ssl verfications
579 */
580 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0), "CURLOPT_SSL_VERIFYPEER");
581 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0), "CURLOPT_SSL_VERIFYHOST");
582 }
583
584 /* detect SSL library used by libcurl */
585 ssl_library = curlhelp_get_ssl_library (curl);
586
587 /* try hard to get a stack of certificates to verify against */
588 if (check_cert) {
589#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1)
590 /* inform curl to report back certificates */
591 switch (ssl_library) {
592 case CURLHELP_SSL_LIBRARY_OPENSSL:
593 case CURLHELP_SSL_LIBRARY_LIBRESSL:
594 /* set callback to extract certificate with OpenSSL context function (works with
595 * OpenSSL-style libraries only!) */
596#ifdef USE_OPENSSL
597 /* libcurl and monitoring plugins built with OpenSSL, good */
598 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION");
599 is_openssl_callback = TRUE;
600#else /* USE_OPENSSL */
601#endif /* USE_OPENSSL */
602 /* libcurl is built with OpenSSL, monitoring plugins, so falling
603 * back to manually extracting certificate information */
604 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
605 break;
606
607 case CURLHELP_SSL_LIBRARY_NSS:
608#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
609 /* NSS: support for CERTINFO is implemented since 7.34.0 */
610 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
611#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
612 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n", curlhelp_get_ssl_library_string (ssl_library));
613#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
614 break;
615
616 case CURLHELP_SSL_LIBRARY_GNUTLS:
617#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0)
618 /* GnuTLS: support for CERTINFO is implemented since 7.42.0 */
619 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO");
620#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */
621 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n", curlhelp_get_ssl_library_string (ssl_library));
622#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */
623 break;
624
625 case CURLHELP_SSL_LIBRARY_UNKNOWN:
626 default:
627 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (unknown SSL library '%s', must implement first)\n", curlhelp_get_ssl_library_string (ssl_library));
628 break;
629 }
630#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */
631 /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */
632 if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL || ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL)
633 handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION");
634 else
635 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (no CURLOPT_SSL_CTX_FUNCTION, no OpenSSL library or libcurl too old and has no CURLOPT_CERTINFO)\n");
636#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */
637 }
638
639#endif /* LIBCURL_FEATURE_SSL */
640
641 /* set default or user-given user agent identification */
642 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERAGENT, user_agent), "CURLOPT_USERAGENT");
643
644 /* proxy-authentication */
645 if (strcmp(proxy_auth, ""))
646 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXYUSERPWD, proxy_auth), "CURLOPT_PROXYUSERPWD");
647
648 /* authentication */
649 if (strcmp(user_auth, ""))
650 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERPWD, user_auth), "CURLOPT_USERPWD");
651
652 /* TODO: parameter auth method, bitfield of following methods:
653 * CURLAUTH_BASIC (default)
654 * CURLAUTH_DIGEST
655 * CURLAUTH_DIGEST_IE
656 * CURLAUTH_NEGOTIATE
657 * CURLAUTH_NTLM
658 * CURLAUTH_NTLM_WB
659 *
660 * convenience tokens for typical sets of methods:
661 * CURLAUTH_ANYSAFE: most secure, without BASIC
662 * or CURLAUTH_ANY: most secure, even BASIC if necessary
663 *
664 * handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST ), "CURLOPT_HTTPAUTH");
665 */
666
667 /* handle redirections */
668 if (onredirect == STATE_DEPENDENT) {
669 if( followmethod == FOLLOW_LIBCURL ) {
670 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1), "CURLOPT_FOLLOWLOCATION");
671
672 /* default -1 is infinite, not good, could lead to zombie plugins!
673 Setting it to one bigger than maximal limit to handle errors nicely below
674 */
675 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_MAXREDIRS, max_depth+1), "CURLOPT_MAXREDIRS");
676
677 /* for now allow only http and https (we are a http(s) check plugin in the end) */
678#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4)
679 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS), "CURLOPT_REDIRECT_PROTOCOLS");
680#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4) */
681
682 /* TODO: handle the following aspects of redirection, make them
683 * command line options too later:
684 CURLOPT_POSTREDIR: method switch
685 CURLINFO_REDIRECT_URL: custom redirect option
686 CURLOPT_REDIRECT_PROTOCOLS: allow people to step outside safe protocols
687 CURLINFO_REDIRECT_COUNT: get the number of redirects, print it, maybe a range option here is nice like for expected page size?
688 */
689 } else {
690 /* old style redirection is handled below */
691 }
692 }
693
694 /* no-body */
695 if (no_body)
696 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_NOBODY, 1), "CURLOPT_NOBODY");
697
698 /* IPv4 or IPv6 forced DNS resolution */
699 if (address_family == AF_UNSPEC)
700 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_WHATEVER)");
701 else if (address_family == AF_INET)
702 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V4)");
703#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6)
704 else if (address_family == AF_INET6)
705 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V6)");
706#endif
707
708 /* either send http POST data (any data, not only POST)*/
709 if (!strcmp(http_method, "POST") ||!strcmp(http_method, "PUT")) {
710 /* set content of payload for POST and PUT */
711 if (http_content_type) {
712 snprintf (http_header, DEFAULT_BUFFER_SIZE, "Content-Type: %s", http_content_type);
713 header_list = curl_slist_append (header_list, http_header);
714 }
715 /* NULL indicates "HTTP Continue" in libcurl, provide an empty string
716 * in case of no POST/PUT data */
717 if (!http_post_data)
718 http_post_data = "";
719 if (!strcmp(http_method, "POST")) {
720 /* POST method, set payload with CURLOPT_POSTFIELDS */
721 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POSTFIELDS, http_post_data), "CURLOPT_POSTFIELDS");
722 } else if (!strcmp(http_method, "PUT")) {
723 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READFUNCTION, (curl_read_callback)curlhelp_buffer_read_callback), "CURLOPT_READFUNCTION");
724 curlhelp_initreadbuffer (&put_buf, http_post_data, strlen (http_post_data));
725 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READDATA, (void *)&put_buf), "CURLOPT_READDATA");
726 handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_INFILESIZE, (curl_off_t)strlen (http_post_data)), "CURLOPT_INFILESIZE");
727 }
728 }
729
730 /* do the request */
731 res = curl_easy_perform(curl);
732
733 if (verbose>=2 && http_post_data)
734 printf ("**** REQUEST CONTENT ****\n%s\n", http_post_data);
735
736 /* free header and server IP resolve lists, we don't need it anymore */
737 curl_slist_free_all (header_list); header_list = NULL;
738 curl_slist_free_all (server_ips); server_ips = NULL;
739
740 /* Curl errors, result in critical Nagios state */
741 if (res != CURLE_OK) {
742 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: cURL returned %d - %s"),
743 server_port, res, errbuf[0] ? errbuf : curl_easy_strerror(res));
744 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
745 }
746
747 /* certificate checks */
748#ifdef LIBCURL_FEATURE_SSL
749 if (use_ssl == TRUE) {
750 if (check_cert == TRUE) {
751 if (is_openssl_callback) {
752#ifdef USE_OPENSSL
753 /* check certificate with OpenSSL functions, curl has been built against OpenSSL
754 * and we actually have OpenSSL in the monitoring tools
755 */
756 result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit);
757 return result;
758#else /* USE_OPENSSL */
759 die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL callback used and not linked against OpenSSL\n");
760#endif /* USE_OPENSSL */
761 } else {
762 int i;
763 struct curl_slist *slist;
764
765 cert_ptr.to_info = NULL;
766 res = curl_easy_getinfo (curl, CURLINFO_CERTINFO, &cert_ptr.to_info);
767 if (!res && cert_ptr.to_info) {
768#ifdef USE_OPENSSL
769 /* We have no OpenSSL in libcurl, but we can use OpenSSL for X509 cert parsing
770 * We only check the first certificate and assume it's the one of the server
771 */
772 const char* raw_cert = NULL;
773 for (i = 0; i < cert_ptr.to_certinfo->num_of_certs; i++) {
774 for (slist = cert_ptr.to_certinfo->certinfo[i]; slist; slist = slist->next) {
775 if (verbose >= 2)
776 printf ("%d ** %s\n", i, slist->data);
777 if (strncmp (slist->data, "Cert:", 5) == 0) {
778 raw_cert = &slist->data[5];
779 goto GOT_FIRST_CERT;
780 }
781 }
782 }
783GOT_FIRST_CERT:
784 if (!raw_cert) {
785 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates from CERTINFO information - certificate data was empty"));
786 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
787 }
788 BIO* cert_BIO = BIO_new (BIO_s_mem());
789 BIO_write (cert_BIO, raw_cert, strlen(raw_cert));
790 cert = PEM_read_bio_X509 (cert_BIO, NULL, NULL, NULL);
791 if (!cert) {
792 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot read certificate from CERTINFO information - BIO error"));
793 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
794 }
795 BIO_free (cert_BIO);
796 result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit);
797 return result;
798#else /* USE_OPENSSL */
799 /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our disposal,
800 * so we use the libcurl CURLINFO data
801 */
802 result = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit);
803 return result;
804#endif /* USE_OPENSSL */
805 } else {
806 snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates - cURL returned %d - %s"),
807 res, curl_easy_strerror(res));
808 die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg);
809 }
810 }
811 }
812 }
813#endif /* LIBCURL_FEATURE_SSL */
814
815 /* we got the data and we executed the request in a given time, so we can append
816 * performance data to the answer always
817 */
818 handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_TOTAL_TIME, &total_time), "CURLINFO_TOTAL_TIME");
819 page_len = get_content_length(&header_buf, &body_buf);
820 if(show_extended_perfdata) {
821 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &time_connect), "CURLINFO_CONNECT_TIME");
822 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &time_appconnect), "CURLINFO_APPCONNECT_TIME");
823 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &time_headers), "CURLINFO_PRETRANSFER_TIME");
824 handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &time_firstbyte), "CURLINFO_STARTTRANSFER_TIME");
825 snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s %s %s %s %s %s",
826 perfd_time(total_time),
827 perfd_size(page_len),
828 perfd_time_connect(time_connect),
829 use_ssl == TRUE ? perfd_time_ssl (time_appconnect-time_connect) : "",
830 perfd_time_headers(time_headers - time_appconnect),
831 perfd_time_firstbyte(time_firstbyte - time_headers),
832 perfd_time_transfer(total_time-time_firstbyte)
833 );
834 } else {
835 snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s",
836 perfd_time(total_time),
837 perfd_size(page_len)
838 );
839 }
840
841 /* return a CRITICAL status if we couldn't read any data */
842 if (strlen(header_buf.buf) == 0 && strlen(body_buf.buf) == 0)
843 die (STATE_CRITICAL, _("HTTP CRITICAL - No header received from host\n"));
844
845 /* get status line of answer, check sanity of HTTP code */
846 if (curlhelp_parse_statusline (header_buf.buf, &status_line) < 0) {
847 snprintf (msg, DEFAULT_BUFFER_SIZE, "Unparsable status line in %.3g seconds response time|%s\n",
848 total_time, perfstring);
849 /* we cannot know the major/minor version here for sure as we cannot parse the first line */
850 die (STATE_CRITICAL, "HTTP CRITICAL HTTP/x.x %ld unknown - %s", code, msg);
851 }
852
853 /* get result code from cURL */
854 handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE");
855 if (verbose>=2)
856 printf ("* curl CURLINFO_RESPONSE_CODE is %ld\n", code);
857
858 /* print status line, header, body if verbose */
859 if (verbose >= 2) {
860 printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header_buf.buf,
861 (no_body ? " [[ skipped ]]" : body_buf.buf));
862 }
863
864 /* make sure the status line matches the response we are looking for */
865 if (!expected_statuscode(status_line.first_line, server_expect)) {
866 if (server_port == HTTP_PORT)
867 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host: %s\n"), status_line.first_line);
868 else
869 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: %s\n"), server_port, status_line.first_line);
870 die (STATE_CRITICAL, "HTTP CRITICAL - %s%s%s", msg,
871 show_body ? "\n" : "",
872 show_body ? body_buf.buf : "");
873 }
874
875 if( server_expect_yn ) {
876 snprintf(msg, DEFAULT_BUFFER_SIZE, _("Status line output matched \"%s\" - "), server_expect);
877 if (verbose)
878 printf ("%s\n",msg);
879 result = STATE_OK;
880 }
881 else {
882 /* illegal return codes result in a critical state */
883 if (code >= 600 || code < 100) {
884 die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%d, %.40s)\n"), status_line.http_code, status_line.msg);
885 /* server errors result in a critical state */
886 } else if (code >= 500) {
887 result = STATE_CRITICAL;
888 /* client errors result in a warning state */
889 } else if (code >= 400) {
890 result = STATE_WARNING;
891 /* check redirected page if specified */
892 } else if (code >= 300) {
893 if (onredirect == STATE_DEPENDENT) {
894 if( followmethod == FOLLOW_LIBCURL ) {
895 code = status_line.http_code;
896 } else {
897 /* old check_http style redirection, if we come
898 * back here, we are in the same status as with
899 * the libcurl method
900 */
901 redir (&header_buf);
902 }
903 } else {
904 /* this is a specific code in the command line to
905 * be returned when a redirection is encoutered
906 */
907 }
908 result = max_state_alt (onredirect, result);
909 /* all other codes are considered ok */
910 } else {
911 result = STATE_OK;
912 }
913 }
914
915 /* libcurl redirection internally, handle error states here */
916 if( followmethod == FOLLOW_LIBCURL ) {
917 handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_REDIRECT_COUNT, &redir_depth), "CURLINFO_REDIRECT_COUNT");
918 if (verbose >= 2)
919 printf(_("* curl LIBINFO_REDIRECT_COUNT is %d\n"), redir_depth);
920 if (redir_depth > max_depth) {
921 snprintf (msg, DEFAULT_BUFFER_SIZE, "maximum redirection depth %d exceeded in libcurl",
922 max_depth);
923 die (STATE_WARNING, "HTTP WARNING - %s", msg);
924 }
925 }
926
927 /* check status codes, set exit status accordingly */
928 if( status_line.http_code != code ) {
929 die (STATE_CRITICAL, _("HTTP CRITICAL %s %d %s - different HTTP codes (cUrl has %ld)\n"),
930 string_statuscode (status_line.http_major, status_line.http_minor),
931 status_line.http_code, status_line.msg, code);
932 }
933
934 if (maximum_age >= 0) {
935 result = max_state_alt(check_document_dates(&header_buf, &msg), result);
936 }
937
938 /* Page and Header content checks go here */
939
940 if (strlen (header_expect)) {
941 if (!strstr (header_buf.buf, header_expect)) {
942 strncpy(&output_header_search[0],header_expect,sizeof(output_header_search));
943 if(output_header_search[sizeof(output_header_search)-1]!='\0') {
944 bcopy("...",&output_header_search[sizeof(output_header_search)-4],4);
945 }
946 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%sheader '%s' not found on '%s://%s:%d%s', "), msg, output_header_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url);
947 result = STATE_CRITICAL;
948 }
949 }
950
951 if (strlen (string_expect)) {
952 if (!strstr (body_buf.buf, string_expect)) {
953 strncpy(&output_string_search[0],string_expect,sizeof(output_string_search));
954 if(output_string_search[sizeof(output_string_search)-1]!='\0') {
955 bcopy("...",&output_string_search[sizeof(output_string_search)-4],4);
956 }
957 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%sstring '%s' not found on '%s://%s:%d%s', "), msg, output_string_search, use_ssl ? "https" : "http", host_name ? host_name : server_address, server_port, server_url);
958 result = STATE_CRITICAL;
959 }
960 }
961
962 if (strlen (regexp)) {
963 errcode = regexec (&preg, body_buf.buf, REGS, pmatch, 0);
964 if ((errcode == 0 && invert_regex == 0) || (errcode == REG_NOMATCH && invert_regex == 1)) {
965 /* OK - No-op to avoid changing the logic around it */
966 result = max_state_alt(STATE_OK, result);
967 }
968 else if ((errcode == REG_NOMATCH && invert_regex == 0) || (errcode == 0 && invert_regex == 1)) {
969 if (invert_regex == 0)
970 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spattern not found, "), msg);
971 else
972 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spattern found, "), msg);
973 result = STATE_CRITICAL;
974 }
975 else {
976 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
977 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%sExecute Error: %s, "), msg, errbuf);
978 result = STATE_UNKNOWN;
979 }
980 }
981
982 /* make sure the page is of an appropriate size */
983 if ((max_page_len > 0) && (page_len > max_page_len)) {
984 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spage size %d too large, "), msg, page_len);
985 result = max_state_alt(STATE_WARNING, result);
986 } else if ((min_page_len > 0) && (page_len < min_page_len)) {
987 snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spage size %d too small, "), msg, page_len);
988 result = max_state_alt(STATE_WARNING, result);
989 }
990
991 /* -w, -c: check warning and critical level */
992 result = max_state_alt(get_status(total_time, thlds), result);
993
994 /* Cut-off trailing characters */
995 if(msg[strlen(msg)-2] == ',')
996 msg[strlen(msg)-2] = '\0';
997 else
998 msg[strlen(msg)-3] = '\0';
999
1000 /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */
1001 die (result, "HTTP %s: %s %d %s%s%s - %d bytes in %.3f second response time %s|%s\n%s%s",
1002 state_text(result), string_statuscode (status_line.http_major, status_line.http_minor),
1003 status_line.http_code, status_line.msg,
1004 strlen(msg) > 0 ? " - " : "",
1005 msg, page_len, total_time,
1006 (display_html ? "</A>" : ""),
1007 perfstring,
1008 (show_body ? body_buf.buf : ""),
1009 (show_body ? "\n" : "") );
1010
1011 /* proper cleanup after die? */
1012 curlhelp_free_statusline(&status_line);
1013 curl_easy_cleanup (curl);
1014 curl_global_cleanup ();
1015 curlhelp_freewritebuffer (&body_buf);
1016 curlhelp_freewritebuffer (&header_buf);
1017 if (!strcmp (http_method, "PUT")) {
1018 curlhelp_freereadbuffer (&put_buf);
1019 }
1020
1021 return result;
1022}
1023
1024int
1025uri_strcmp (const UriTextRangeA range, const char* s)
1026{
1027 if (!range.first) return -1;
1028 if (range.afterLast - range.first < strlen (s)) return -1;
1029 return strncmp (s, range.first, min( range.afterLast - range.first, strlen (s)));
1030}
1031
1032char*
1033uri_string (const UriTextRangeA range, char* buf, size_t buflen)
1034{
1035 if (!range.first) return "(null)";
1036 strncpy (buf, range.first, max (buflen-1, range.afterLast - range.first));
1037 buf[max (buflen-1, range.afterLast - range.first)] = '\0';
1038 buf[range.afterLast - range.first] = '\0';
1039 return buf;
1040}
1041
1042void
1043redir (curlhelp_write_curlbuf* header_buf)
1044{
1045 char *location = NULL;
1046 curlhelp_statusline status_line;
1047 struct phr_header headers[255];
1048 size_t nof_headers = 255;
1049 size_t msglen;
1050 char buf[DEFAULT_BUFFER_SIZE];
1051 char ipstr[INET_ADDR_MAX_SIZE];
1052 int new_port;
1053 char *new_host;
1054 char *new_url;
1055
1056 int res = phr_parse_response (header_buf->buf, header_buf->buflen,
1057 &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen,
1058 headers, &nof_headers, 0);
1059
1060 location = get_header_value (headers, nof_headers, "location");
1061
1062 if (verbose >= 2)
1063 printf(_("* Seen redirect location %s\n"), location);
1064
1065 if (++redir_depth > max_depth)
1066 die (STATE_WARNING,
1067 _("HTTP WARNING - maximum redirection depth %d exceeded - %s%s\n"),
1068 max_depth, location, (display_html ? "</A>" : ""));
1069
1070 UriParserStateA state;
1071 UriUriA uri;
1072 state.uri = &uri;
1073 if (uriParseUriA (&state, location) != URI_SUCCESS) {
1074 if (state.errorCode == URI_ERROR_SYNTAX) {
1075 die (STATE_UNKNOWN,
1076 _("HTTP UNKNOWN - Could not parse redirect location '%s'%s\n"),
1077 location, (display_html ? "</A>" : ""));
1078 } else if (state.errorCode == URI_ERROR_MALLOC) {
1079 die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n"));
1080 }
1081 }
1082
1083 if (verbose >= 2) {
1084 printf (_("** scheme: %s\n"),
1085 uri_string (uri.scheme, buf, DEFAULT_BUFFER_SIZE));
1086 printf (_("** host: %s\n"),
1087 uri_string (uri.hostText, buf, DEFAULT_BUFFER_SIZE));
1088 printf (_("** port: %s\n"),
1089 uri_string (uri.portText, buf, DEFAULT_BUFFER_SIZE));
1090 if (uri.hostData.ip4) {
1091 inet_ntop (AF_INET, uri.hostData.ip4->data, ipstr, sizeof (ipstr));
1092 printf (_("** IPv4: %s\n"), ipstr);
1093 }
1094 if (uri.hostData.ip6) {
1095 inet_ntop (AF_INET, uri.hostData.ip6->data, ipstr, sizeof (ipstr));
1096 printf (_("** IPv6: %s\n"), ipstr);
1097 }
1098 if (uri.pathHead) {
1099 printf (_("** path: "));
1100 const UriPathSegmentA* p = uri.pathHead;
1101 for (; p; p = p->next) {
1102 printf ("/%s", uri_string (p->text, buf, DEFAULT_BUFFER_SIZE));
1103 }
1104 puts ("");
1105 }
1106 if (uri.query.first) {
1107 printf (_("** query: %s\n"),
1108 uri_string (uri.query, buf, DEFAULT_BUFFER_SIZE));
1109 }
1110 if (uri.fragment.first) {
1111 printf (_("** fragment: %s\n"),
1112 uri_string (uri.fragment, buf, DEFAULT_BUFFER_SIZE));
1113 }
1114 }
1115
1116 use_ssl = !uri_strcmp (uri.scheme, "https");
1117
1118 /* we do a sloppy test here only, because uriparser would have failed
1119 * above, if the port would be invalid, we just check for MAX_PORT
1120 */
1121 if (uri.portText.first) {
1122 new_port = atoi (uri_string (uri.portText, buf, DEFAULT_BUFFER_SIZE));
1123 } else {
1124 new_port = HTTP_PORT;
1125 if (use_ssl)
1126 new_port = HTTPS_PORT;
1127 }
1128 if (new_port > MAX_PORT)
1129 die (STATE_UNKNOWN,
1130 _("HTTP UNKNOWN - Redirection to port above %d - %s%s\n"),
1131 MAX_PORT, location, display_html ? "</A>" : "");
1132
1133 /* by RFC 7231 relative URLs in Location should be taken relative to
1134 * the original URL, so wy try to form a new absolute URL here
1135 */
1136 if (!uri.scheme.first && !uri.hostText.first) {
1137 new_host = strdup (host_name ? host_name : server_address);
1138 } else {
1139 new_host = strdup (uri_string (uri.hostText, buf, DEFAULT_BUFFER_SIZE));
1140 }
1141
1142 /* compose new path */
1143 /* TODO: handle fragments and query part of URL */
1144 new_url = (char *)calloc( 1, DEFAULT_BUFFER_SIZE);
1145 if (uri.pathHead) {
1146 const UriPathSegmentA* p = uri.pathHead;
1147 for (; p; p = p->next) {
1148 strncat (new_url, "/", DEFAULT_BUFFER_SIZE);
1149 strncat (new_url, uri_string (p->text, buf, DEFAULT_BUFFER_SIZE), DEFAULT_BUFFER_SIZE-1);
1150 }
1151 }
1152
1153 if (server_port==new_port &&
1154 !strncmp(server_address, new_host, MAX_IPV4_HOSTLENGTH) &&
1155 (host_name && !strncmp(host_name, new_host, MAX_IPV4_HOSTLENGTH)) &&
1156 !strcmp(server_url, new_url))
1157 die (STATE_CRITICAL,
1158 _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"),
1159 use_ssl ? "https" : "http", new_host, new_port, new_url, (display_html ? "</A>" : ""));
1160
1161 /* set new values for redirected request */
1162
1163 if (!(followsticky & STICKY_HOST)) {
1164 free (server_address);
1165 server_address = strndup (new_host, MAX_IPV4_HOSTLENGTH);
1166 }
1167 if (!(followsticky & STICKY_PORT)) {
1168 server_port = (unsigned short)new_port;
1169 }
1170
1171 free (host_name);
1172 host_name = strndup (new_host, MAX_IPV4_HOSTLENGTH);
1173
1174 /* reset virtual port */
1175 virtual_port = server_port;
1176
1177 free(new_host);
1178 free (server_url);
1179 server_url = new_url;
1180
1181 uriFreeUriMembersA (&uri);
1182
1183 if (verbose)
1184 printf (_("Redirection to %s://%s:%d%s\n"), use_ssl ? "https" : "http",
1185 host_name ? host_name : server_address, server_port, server_url);
1186
1187 /* TODO: the hash component MUST be taken from the original URL and
1188 * attached to the URL in Location
1189 */
1190
1191 check_http ();
1192}
1193
1194/* check whether a file exists */
1195void
1196test_file (char *path)
1197{
1198 if (access(path, R_OK) == 0)
1199 return;
1200 usage2 (_("file does not exist or is not readable"), path);
1201}
1202
1203int
1204process_arguments (int argc, char **argv)
1205{
1206 char *p;
1207 int c = 1;
1208 char *temp;
1209
1210 enum {
1211 INVERT_REGEX = CHAR_MAX + 1,
1212 SNI_OPTION,
1213 CA_CERT_OPTION,
1214 HTTP_VERSION_OPTION,
1215 AUTOMATIC_DECOMPRESSION
1216 };
1217
1218 int option = 0;
1219 int got_plus = 0;
1220 static struct option longopts[] = {
1221 STD_LONG_OPTS,
1222 {"link", no_argument, 0, 'L'},
1223 {"nohtml", no_argument, 0, 'n'},
1224 {"ssl", optional_argument, 0, 'S'},
1225 {"sni", no_argument, 0, SNI_OPTION},
1226 {"post", required_argument, 0, 'P'},
1227 {"method", required_argument, 0, 'j'},
1228 {"IP-address", required_argument, 0, 'I'},
1229 {"url", required_argument, 0, 'u'},
1230 {"port", required_argument, 0, 'p'},
1231 {"authorization", required_argument, 0, 'a'},
1232 {"proxy-authorization", required_argument, 0, 'b'},
1233 {"header-string", required_argument, 0, 'd'},
1234 {"string", required_argument, 0, 's'},
1235 {"expect", required_argument, 0, 'e'},
1236 {"regex", required_argument, 0, 'r'},
1237 {"ereg", required_argument, 0, 'r'},
1238 {"eregi", required_argument, 0, 'R'},
1239 {"linespan", no_argument, 0, 'l'},
1240 {"onredirect", required_argument, 0, 'f'},
1241 {"certificate", required_argument, 0, 'C'},
1242 {"client-cert", required_argument, 0, 'J'},
1243 {"private-key", required_argument, 0, 'K'},
1244 {"ca-cert", required_argument, 0, CA_CERT_OPTION},
1245 {"verify-cert", no_argument, 0, 'D'},
1246 {"useragent", required_argument, 0, 'A'},
1247 {"header", required_argument, 0, 'k'},
1248 {"no-body", no_argument, 0, 'N'},
1249 {"max-age", required_argument, 0, 'M'},
1250 {"content-type", required_argument, 0, 'T'},
1251 {"pagesize", required_argument, 0, 'm'},
1252 {"invert-regex", no_argument, NULL, INVERT_REGEX},
1253 {"use-ipv4", no_argument, 0, '4'},
1254 {"use-ipv6", no_argument, 0, '6'},
1255 {"extended-perfdata", no_argument, 0, 'E'},
1256 {"show-body", no_argument, 0, 'B'},
1257 {"http-version", required_argument, 0, HTTP_VERSION_OPTION},
1258 {"enable-automatic-decompression", no_argument, 0, AUTOMATIC_DECOMPRESSION},
1259 {0, 0, 0, 0}
1260 };
1261
1262 if (argc < 2)
1263 return ERROR;
1264
1265 /* support check_http compatible arguments */
1266 for (c = 1; c < argc; c++) {
1267 if (strcmp ("-to", argv[c]) == 0)
1268 strcpy (argv[c], "-t");
1269 if (strcmp ("-hn", argv[c]) == 0)
1270 strcpy (argv[c], "-H");
1271 if (strcmp ("-wt", argv[c]) == 0)
1272 strcpy (argv[c], "-w");
1273 if (strcmp ("-ct", argv[c]) == 0)
1274 strcpy (argv[c], "-c");
1275 if (strcmp ("-nohtml", argv[c]) == 0)
1276 strcpy (argv[c], "-n");
1277 }
1278
1279 server_url = strdup(DEFAULT_SERVER_URL);
1280
1281 while (1) {
1282 c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:DnlLS::m:M:NEB", longopts, &option);
1283 if (c == -1 || c == EOF || c == 1)
1284 break;
1285
1286 switch (c) {
1287 case 'h':
1288 print_help();
1289 exit(STATE_UNKNOWN);
1290 break;
1291 case 'V':
1292 print_revision(progname, NP_VERSION);
1293 print_curl_version();
1294 exit(STATE_UNKNOWN);
1295 break;
1296 case 'v':
1297 verbose++;
1298 break;
1299 case 't': /* timeout period */
1300 if (!is_intnonneg (optarg))
1301 usage2 (_("Timeout interval must be a positive integer"), optarg);
1302 else
1303 socket_timeout = (int)strtol (optarg, NULL, 10);
1304 break;
1305 case 'c': /* critical time threshold */
1306 critical_thresholds = optarg;
1307 break;
1308 case 'w': /* warning time threshold */
1309 warning_thresholds = optarg;
1310 break;
1311 case 'H': /* virtual host */
1312 host_name = strdup (optarg);
1313 if (host_name[0] == '[') {
1314 if ((p = strstr (host_name, "]:")) != NULL) { /* [IPv6]:port */
1315 virtual_port = atoi (p + 2);
1316 /* cut off the port */
1317 host_name_length = strlen (host_name) - strlen (p) - 1;
1318 free (host_name);
1319 host_name = strndup (optarg, host_name_length);
1320 }
1321 } else if ((p = strchr (host_name, ':')) != NULL
1322 && strchr (++p, ':') == NULL) { /* IPv4:port or host:port */
1323 virtual_port = atoi (p);
1324 /* cut off the port */
1325 host_name_length = strlen (host_name) - strlen (p) - 1;
1326 free (host_name);
1327 host_name = strndup (optarg, host_name_length);
1328 }
1329 break;
1330 case 'I': /* internet address */
1331 server_address = strdup (optarg);
1332 break;
1333 case 'u': /* URL path */
1334 server_url = strdup (optarg);
1335 break;
1336 case 'p': /* Server port */
1337 if (!is_intnonneg (optarg))
1338 usage2 (_("Invalid port number, expecting a non-negative number"), optarg);
1339 else {
1340 if( strtol(optarg, NULL, 10) > MAX_PORT)
1341 usage2 (_("Invalid port number, supplied port number is too big"), optarg);
1342 server_port = (unsigned short)strtol(optarg, NULL, 10);
1343 specify_port = TRUE;
1344 }
1345 break;
1346 case 'a': /* authorization info */
1347 strncpy (user_auth, optarg, MAX_INPUT_BUFFER - 1);
1348 user_auth[MAX_INPUT_BUFFER - 1] = 0;
1349 break;
1350 case 'b': /* proxy-authorization info */
1351 strncpy (proxy_auth, optarg, MAX_INPUT_BUFFER - 1);
1352 proxy_auth[MAX_INPUT_BUFFER - 1] = 0;
1353 break;
1354 case 'P': /* HTTP POST data in URL encoded format; ignored if settings already */
1355 if (! http_post_data)
1356 http_post_data = strdup (optarg);
1357 if (! http_method)
1358 http_method = strdup("POST");
1359 break;
1360 case 'j': /* Set HTTP method */
1361 if (http_method)
1362 free(http_method);
1363 http_method = strdup (optarg);
1364 break;
1365 case 'A': /* useragent */
1366 strncpy (user_agent, optarg, DEFAULT_BUFFER_SIZE);
1367 user_agent[DEFAULT_BUFFER_SIZE-1] = '\0';
1368 break;
1369 case 'k': /* Additional headers */
1370 if (http_opt_headers_count == 0)
1371 http_opt_headers = malloc (sizeof (char *) * (++http_opt_headers_count));
1372 else
1373 http_opt_headers = realloc (http_opt_headers, sizeof (char *) * (++http_opt_headers_count));
1374 http_opt_headers[http_opt_headers_count - 1] = optarg;
1375 break;
1376 case 'L': /* show html link */
1377 display_html = TRUE;
1378 break;
1379 case 'n': /* do not show html link */
1380 display_html = FALSE;
1381 break;
1382 case 'C': /* Check SSL cert validity */
1383#ifdef LIBCURL_FEATURE_SSL
1384 if ((temp=strchr(optarg,','))!=NULL) {
1385 *temp='\0';
1386 if (!is_intnonneg (optarg))
1387 usage2 (_("Invalid certificate expiration period"), optarg);
1388 days_till_exp_warn = atoi(optarg);
1389 *temp=',';
1390 temp++;
1391 if (!is_intnonneg (temp))
1392 usage2 (_("Invalid certificate expiration period"), temp);
1393 days_till_exp_crit = atoi (temp);
1394 }
1395 else {
1396 days_till_exp_crit=0;
1397 if (!is_intnonneg (optarg))
1398 usage2 (_("Invalid certificate expiration period"), optarg);
1399 days_till_exp_warn = atoi (optarg);
1400 }
1401 check_cert = TRUE;
1402 goto enable_ssl;
1403#endif
1404 case 'J': /* use client certificate */
1405#ifdef LIBCURL_FEATURE_SSL
1406 test_file(optarg);
1407 client_cert = optarg;
1408 goto enable_ssl;
1409#endif
1410 case 'K': /* use client private key */
1411#ifdef LIBCURL_FEATURE_SSL
1412 test_file(optarg);
1413 client_privkey = optarg;
1414 goto enable_ssl;
1415#endif
1416#ifdef LIBCURL_FEATURE_SSL
1417 case CA_CERT_OPTION: /* use CA chain file */
1418 test_file(optarg);
1419 ca_cert = optarg;
1420 goto enable_ssl;
1421#endif
1422#ifdef LIBCURL_FEATURE_SSL
1423 case 'D': /* verify peer certificate & host */
1424 verify_peer_and_host = TRUE;
1425 goto enable_ssl;
1426#endif
1427 case 'S': /* use SSL */
1428#ifdef LIBCURL_FEATURE_SSL
1429 enable_ssl:
1430 use_ssl = TRUE;
1431 /* ssl_version initialized to CURL_SSLVERSION_DEFAULT as a default.
1432 * Only set if it's non-zero. This helps when we include multiple
1433 * parameters, like -S and -C combinations */
1434 ssl_version = CURL_SSLVERSION_DEFAULT;
1435 if (c=='S' && optarg != NULL) {
1436 char *plus_ptr = strchr(optarg, '+');
1437 if (plus_ptr) {
1438 got_plus = 1;
1439 *plus_ptr = '\0';
1440 }
1441
1442 if (optarg[0] == '2')
1443 ssl_version = CURL_SSLVERSION_SSLv2;
1444 else if (optarg[0] == '3')
1445 ssl_version = CURL_SSLVERSION_SSLv3;
1446 else if (!strcmp (optarg, "1") || !strcmp (optarg, "1.0"))
1447#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1448 ssl_version = CURL_SSLVERSION_TLSv1_0;
1449#else
1450 ssl_version = CURL_SSLVERSION_DEFAULT;
1451#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1452 else if (!strcmp (optarg, "1.1"))
1453#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1454 ssl_version = CURL_SSLVERSION_TLSv1_1;
1455#else
1456 ssl_version = CURL_SSLVERSION_DEFAULT;
1457#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1458 else if (!strcmp (optarg, "1.2"))
1459#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0)
1460 ssl_version = CURL_SSLVERSION_TLSv1_2;
1461#else
1462 ssl_version = CURL_SSLVERSION_DEFAULT;
1463#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */
1464 else if (!strcmp (optarg, "1.3"))
1465#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0)
1466 ssl_version = CURL_SSLVERSION_TLSv1_3;
1467#else
1468 ssl_version = CURL_SSLVERSION_DEFAULT;
1469#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) */
1470 else
1471 usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2, 1.3 (with optional '+' suffix)"));
1472 }
1473#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0)
1474 if (got_plus) {
1475 switch (ssl_version) {
1476 case CURL_SSLVERSION_TLSv1_3:
1477 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3;
1478 break;
1479 case CURL_SSLVERSION_TLSv1_2:
1480 case CURL_SSLVERSION_TLSv1_1:
1481 case CURL_SSLVERSION_TLSv1_0:
1482 ssl_version |= CURL_SSLVERSION_MAX_DEFAULT;
1483 break;
1484 }
1485 } else {
1486 switch (ssl_version) {
1487 case CURL_SSLVERSION_TLSv1_3:
1488 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3;
1489 break;
1490 case CURL_SSLVERSION_TLSv1_2:
1491 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_2;
1492 break;
1493 case CURL_SSLVERSION_TLSv1_1:
1494 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_1;
1495 break;
1496 case CURL_SSLVERSION_TLSv1_0:
1497 ssl_version |= CURL_SSLVERSION_MAX_TLSv1_0;
1498 break;
1499 }
1500 }
1501#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) */
1502 if (verbose >= 2)
1503 printf(_("* Set SSL/TLS version to %d\n"), ssl_version);
1504 if (specify_port == FALSE)
1505 server_port = HTTPS_PORT;
1506 break;
1507#else /* LIBCURL_FEATURE_SSL */
1508 /* -C -J and -K fall through to here without SSL */
1509 usage4 (_("Invalid option - SSL is not available"));
1510 break;
1511 case SNI_OPTION: /* --sni is parsed, but ignored, the default is TRUE with libcurl */
1512 use_sni = TRUE;
1513 break;
1514#endif /* LIBCURL_FEATURE_SSL */
1515 case 'f': /* onredirect */
1516 if (!strcmp (optarg, "ok"))
1517 onredirect = STATE_OK;
1518 else if (!strcmp (optarg, "warning"))
1519 onredirect = STATE_WARNING;
1520 else if (!strcmp (optarg, "critical"))
1521 onredirect = STATE_CRITICAL;
1522 else if (!strcmp (optarg, "unknown"))
1523 onredirect = STATE_UNKNOWN;
1524 else if (!strcmp (optarg, "follow"))
1525 onredirect = STATE_DEPENDENT;
1526 else if (!strcmp (optarg, "stickyport"))
1527 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST|STICKY_PORT;
1528 else if (!strcmp (optarg, "sticky"))
1529 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST;
1530 else if (!strcmp (optarg, "follow"))
1531 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_NONE;
1532 else if (!strcmp (optarg, "curl"))
1533 onredirect = STATE_DEPENDENT, followmethod = FOLLOW_LIBCURL;
1534 else usage2 (_("Invalid onredirect option"), optarg);
1535 if (verbose >= 2)
1536 printf(_("* Following redirects set to %s\n"), state_text(onredirect));
1537 break;
1538 case 'd': /* string or substring */
1539 strncpy (header_expect, optarg, MAX_INPUT_BUFFER - 1);
1540 header_expect[MAX_INPUT_BUFFER - 1] = 0;
1541 break;
1542 case 's': /* string or substring */
1543 strncpy (string_expect, optarg, MAX_INPUT_BUFFER - 1);
1544 string_expect[MAX_INPUT_BUFFER - 1] = 0;
1545 break;
1546 case 'e': /* string or substring */
1547 strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1);
1548 server_expect[MAX_INPUT_BUFFER - 1] = 0;
1549 server_expect_yn = 1;
1550 break;
1551 case 'T': /* Content-type */
1552 http_content_type = strdup (optarg);
1553 break;
1554 case 'l': /* linespan */
1555 cflags &= ~REG_NEWLINE;
1556 break;
1557 case 'R': /* regex */
1558 cflags |= REG_ICASE;
1559 case 'r': /* regex */
1560 strncpy (regexp, optarg, MAX_RE_SIZE - 1);
1561 regexp[MAX_RE_SIZE - 1] = 0;
1562 errcode = regcomp (&preg, regexp, cflags);
1563 if (errcode != 0) {
1564 (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
1565 printf (_("Could Not Compile Regular Expression: %s"), errbuf);
1566 return ERROR;
1567 }
1568 break;
1569 case INVERT_REGEX:
1570 invert_regex = 1;
1571 break;
1572 case '4':
1573 address_family = AF_INET;
1574 break;
1575 case '6':
1576#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6)
1577 address_family = AF_INET6;
1578#else
1579 usage4 (_("IPv6 support not available"));
1580#endif
1581 break;
1582 case 'm': /* min_page_length */
1583 {
1584 char *tmp;
1585 if (strchr(optarg, ':') != (char *)NULL) {
1586 /* range, so get two values, min:max */
1587 tmp = strtok(optarg, ":");
1588 if (tmp == NULL) {
1589 printf("Bad format: try \"-m min:max\"\n");
1590 exit (STATE_WARNING);
1591 } else
1592 min_page_len = atoi(tmp);
1593
1594 tmp = strtok(NULL, ":");
1595 if (tmp == NULL) {
1596 printf("Bad format: try \"-m min:max\"\n");
1597 exit (STATE_WARNING);
1598 } else
1599 max_page_len = atoi(tmp);
1600 } else
1601 min_page_len = atoi (optarg);
1602 break;
1603 }
1604 case 'N': /* no-body */
1605 no_body = TRUE;
1606 break;
1607 case 'M': /* max-age */
1608 {
1609 int L = strlen(optarg);
1610 if (L && optarg[L-1] == 'm')
1611 maximum_age = atoi (optarg) * 60;
1612 else if (L && optarg[L-1] == 'h')
1613 maximum_age = atoi (optarg) * 60 * 60;
1614 else if (L && optarg[L-1] == 'd')
1615 maximum_age = atoi (optarg) * 60 * 60 * 24;
1616 else if (L && (optarg[L-1] == 's' ||
1617 isdigit (optarg[L-1])))
1618 maximum_age = atoi (optarg);
1619 else {
1620 fprintf (stderr, "unparsable max-age: %s\n", optarg);
1621 exit (STATE_WARNING);
1622 }
1623 if (verbose >= 2)
1624 printf ("* Maximal age of document set to %d seconds\n", maximum_age);
1625 }
1626 break;
1627 case 'E': /* show extended perfdata */
1628 show_extended_perfdata = TRUE;
1629 break;
1630 case 'B': /* print body content after status line */
1631 show_body = TRUE;
1632 break;
1633 case HTTP_VERSION_OPTION:
1634 curl_http_version = CURL_HTTP_VERSION_NONE;
1635 if (strcmp (optarg, "1.0") == 0) {
1636 curl_http_version = CURL_HTTP_VERSION_1_0;
1637 } else if (strcmp (optarg, "1.1") == 0) {
1638 curl_http_version = CURL_HTTP_VERSION_1_1;
1639 } else if ((strcmp (optarg, "2.0") == 0) || (strcmp (optarg, "2") == 0)) {
1640#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0)
1641 curl_http_version = CURL_HTTP_VERSION_2_0;
1642#else
1643 curl_http_version = CURL_HTTP_VERSION_NONE;
1644#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 33, 0) */
1645 } else {
1646 fprintf (stderr, "unkown http-version parameter: %s\n", optarg);
1647 exit (STATE_WARNING);
1648 }
1649 break;
1650 case AUTOMATIC_DECOMPRESSION:
1651 automatic_decompression = TRUE;
1652 break;
1653 case '?':
1654 /* print short usage statement if args not parsable */
1655 usage5 ();
1656 break;
1657 }
1658 }
1659
1660 c = optind;
1661
1662 if (server_address == NULL && c < argc)
1663 server_address = strdup (argv[c++]);
1664
1665 if (host_name == NULL && c < argc)
1666 host_name = strdup (argv[c++]);
1667
1668 if (server_address == NULL) {
1669 if (host_name == NULL)
1670 usage4 (_("You must specify a server address or host name"));
1671 else
1672 server_address = strdup (host_name);
1673 }
1674
1675 set_thresholds(&thlds, warning_thresholds, critical_thresholds);
1676
1677 if (critical_thresholds && thlds->critical->end>(double)socket_timeout)
1678 socket_timeout = (int)thlds->critical->end + 1;
1679 if (verbose >= 2)
1680 printf ("* Socket timeout set to %ld seconds\n", socket_timeout);
1681
1682 if (http_method == NULL)
1683 http_method = strdup ("GET");
1684
1685 if (client_cert && !client_privkey)
1686 usage4 (_("If you use a client certificate you must also specify a private key file"));
1687
1688 if (virtual_port == 0)
1689 virtual_port = server_port;
1690 else {
1691 if ((use_ssl && server_port == HTTPS_PORT) || (!use_ssl && server_port == HTTP_PORT))
1692 if(specify_port == FALSE)
1693 server_port = virtual_port;
1694 }
1695
1696 return TRUE;
1697}
1698
1699char *perfd_time (double elapsed_time)
1700{
1701 return fperfdata ("time", elapsed_time, "s",
1702 thlds->warning?TRUE:FALSE, thlds->warning?thlds->warning->end:0,
1703 thlds->critical?TRUE:FALSE, thlds->critical?thlds->critical->end:0,
1704 TRUE, 0, TRUE, socket_timeout);
1705}
1706
1707char *perfd_time_connect (double elapsed_time_connect)
1708{
1709 return fperfdata ("time_connect", elapsed_time_connect, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1710}
1711
1712char *perfd_time_ssl (double elapsed_time_ssl)
1713{
1714 return fperfdata ("time_ssl", elapsed_time_ssl, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1715}
1716
1717char *perfd_time_headers (double elapsed_time_headers)
1718{
1719 return fperfdata ("time_headers", elapsed_time_headers, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1720}
1721
1722char *perfd_time_firstbyte (double elapsed_time_firstbyte)
1723{
1724 return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1725}
1726
1727char *perfd_time_transfer (double elapsed_time_transfer)
1728{
1729 return fperfdata ("time_transfer", elapsed_time_transfer, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1730}
1731
1732char *perfd_size (int page_len)
1733{
1734 return perfdata ("size", page_len, "B",
1735 (min_page_len>0?TRUE:FALSE), min_page_len,
1736 (min_page_len>0?TRUE:FALSE), 0,
1737 TRUE, 0, FALSE, 0);
1738}
1739
1740void
1741print_help (void)
1742{
1743 print_revision (progname, NP_VERSION);
1744
1745 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
1746 printf (COPYRIGHT, copyright, email);
1747
1748 printf ("%s\n", _("This plugin tests the HTTP service on the specified host. It can test"));
1749 printf ("%s\n", _("normal (http) and secure (https) servers, follow redirects, search for"));
1750 printf ("%s\n", _("strings and regular expressions, check connection times, and report on"));
1751 printf ("%s\n", _("certificate expiration times."));
1752 printf ("\n");
1753 printf ("%s\n", _("It makes use of libcurl to do so. It tries to be as compatible to check_http"));
1754 printf ("%s\n", _("as possible."));
1755
1756 printf ("\n\n");
1757
1758 print_usage ();
1759
1760 printf (_("NOTE: One or both of -H and -I must be specified"));
1761
1762 printf ("\n");
1763
1764 printf (UT_HELP_VRSN);
1765 printf (UT_EXTRA_OPTS);
1766
1767 printf (" %s\n", "-H, --hostname=ADDRESS");
1768 printf (" %s\n", _("Host name argument for servers using host headers (virtual host)"));
1769 printf (" %s\n", _("Append a port to include it in the header (eg: example.com:5000)"));
1770 printf (" %s\n", "-I, --IP-address=ADDRESS");
1771 printf (" %s\n", _("IP address or name (use numeric address if possible to bypass DNS lookup)."));
1772 printf (" %s\n", "-p, --port=INTEGER");
1773 printf (" %s", _("Port number (default: "));
1774 printf ("%d)\n", HTTP_PORT);
1775
1776 printf (UT_IPv46);
1777
1778#ifdef LIBCURL_FEATURE_SSL
1779 printf (" %s\n", "-S, --ssl=VERSION[+]");
1780 printf (" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is optional, and prevents"));
1781 printf (" %s\n", _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,"));
1782 printf (" %s\n", _("1.2 = TLSv1.2, 1.3 = TLSv1.3). With a '+' suffix, newer versions are also accepted."));
1783 printf (" %s\n", _("Note: SSLv2 and SSLv3 are deprecated and are usually disabled in libcurl"));
1784 printf (" %s\n", "--sni");
1785 printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)"));
1786#if LIBCURL_VERSION_NUM >= 0x071801
1787 printf (" %s\n", _("Note: --sni is the default in libcurl as SSLv2 and SSLV3 are deprecated and"));
1788 printf (" %s\n", _(" SNI only really works since TLSv1.0"));
1789#else
1790 printf (" %s\n", _("Note: SNI is not supported in libcurl before 7.18.1"));
1791#endif
1792 printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]");
1793 printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443"));
1794 printf (" %s\n", _("(when this option is used the URL is not checked.)"));
1795 printf (" %s\n", "-J, --client-cert=FILE");
1796 printf (" %s\n", _("Name of file that contains the client certificate (PEM format)"));
1797 printf (" %s\n", _("to be used in establishing the SSL session"));
1798 printf (" %s\n", "-K, --private-key=FILE");
1799 printf (" %s\n", _("Name of file containing the private key (PEM format)"));
1800 printf (" %s\n", _("matching the client certificate"));
1801 printf (" %s\n", "--ca-cert=FILE");
1802 printf (" %s\n", _("CA certificate file to verify peer against"));
1803 printf (" %s\n", "-D, --verify-cert");
1804 printf (" %s\n", _("Verify the peer's SSL certificate and hostname"));
1805#endif
1806
1807 printf (" %s\n", "-e, --expect=STRING");
1808 printf (" %s\n", _("Comma-delimited list of strings, at least one of them is expected in"));
1809 printf (" %s", _("the first (status) line of the server response (default: "));
1810 printf ("%s)\n", HTTP_EXPECT);
1811 printf (" %s\n", _("If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)"));
1812 printf (" %s\n", "-d, --header-string=STRING");
1813 printf (" %s\n", _("String to expect in the response headers"));
1814 printf (" %s\n", "-s, --string=STRING");
1815 printf (" %s\n", _("String to expect in the content"));
1816 printf (" %s\n", "-u, --url=PATH");
1817 printf (" %s\n", _("URL to GET or POST (default: /)"));
1818 printf (" %s\n", "-P, --post=STRING");
1819 printf (" %s\n", _("URL encoded http POST data"));
1820 printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)");
1821 printf (" %s\n", _("Set HTTP method."));
1822 printf (" %s\n", "-N, --no-body");
1823 printf (" %s\n", _("Don't wait for document body: stop reading after headers."));
1824 printf (" %s\n", _("(Note that this still does an HTTP GET or POST, not a HEAD.)"));
1825 printf (" %s\n", "-M, --max-age=SECONDS");
1826 printf (" %s\n", _("Warn if document is more than SECONDS old. the number can also be of"));
1827 printf (" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or \"10d\" for days."));
1828 printf (" %s\n", "-T, --content-type=STRING");
1829 printf (" %s\n", _("specify Content-Type header media type when POSTing\n"));
1830 printf (" %s\n", "-l, --linespan");
1831 printf (" %s\n", _("Allow regex to span newlines (must precede -r or -R)"));
1832 printf (" %s\n", "-r, --regex, --ereg=STRING");
1833 printf (" %s\n", _("Search page for regex STRING"));
1834 printf (" %s\n", "-R, --eregi=STRING");
1835 printf (" %s\n", _("Search page for case-insensitive regex STRING"));
1836 printf (" %s\n", "--invert-regex");
1837 printf (" %s\n", _("Return CRITICAL if found, OK if not\n"));
1838 printf (" %s\n", "-a, --authorization=AUTH_PAIR");
1839 printf (" %s\n", _("Username:password on sites with basic authentication"));
1840 printf (" %s\n", "-b, --proxy-authorization=AUTH_PAIR");
1841 printf (" %s\n", _("Username:password on proxy-servers with basic authentication"));
1842 printf (" %s\n", "-A, --useragent=STRING");
1843 printf (" %s\n", _("String to be sent in http header as \"User Agent\""));
1844 printf (" %s\n", "-k, --header=STRING");
1845 printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers"));
1846 printf (" %s\n", "-E, --extended-perfdata");
1847 printf (" %s\n", _("Print additional performance data"));
1848 printf (" %s\n", "-B, --show-body");
1849 printf (" %s\n", _("Print body content below status line"));
1850 printf (" %s\n", "-L, --link");
1851 printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)"));
1852 printf (" %s\n", "-f, --onredirect=<ok|warning|critical|follow|sticky|stickyport|curl>");
1853 printf (" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the"));
1854 printf (" %s\n", _("specified IP address. stickyport also ensures port stays the same."));
1855 printf (" %s\n", _("follow uses the old redirection algorithm of check_http."));
1856 printf (" %s\n", _("curl uses CURL_FOLLOWLOCATION built into libcurl."));
1857 printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>");
1858 printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)"));
1859 printf ("\n");
1860 printf (" %s\n", "--http-version=VERSION");
1861 printf (" %s\n", _("Connect via specific HTTP protocol."));
1862 printf (" %s\n", _("1.0 = HTTP/1.0, 1.1 = HTTP/1.1, 2.0 = HTTP/2 (HTTP/2 will fail without -S)"));
1863 printf (" %s\n", "--enable-automatic-decompression");
1864 printf (" %s\n", _("Enable automatic decompression of body (CURLOPT_ACCEPT_ENCODING)."));
1865 printf ("\n");
1866
1867 printf (UT_WARN_CRIT);
1868
1869 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
1870
1871 printf (UT_VERBOSE);
1872
1873 printf ("\n");
1874 printf ("%s\n", _("Notes:"));
1875 printf (" %s\n", _("This plugin will attempt to open an HTTP connection with the host."));
1876 printf (" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL"));
1877 printf (" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect response"));
1878 printf (" %s\n", _("messages from the host result in STATE_WARNING return values. If you are"));
1879 printf (" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN"));
1880 printf (" %s\n", _("(fully qualified domain name) as the [host_name] argument."));
1881
1882#ifdef LIBCURL_FEATURE_SSL
1883 printf ("\n");
1884 printf (" %s\n", _("This plugin can also check whether an SSL enabled web server is able to"));
1885 printf (" %s\n", _("serve content (optionally within a specified time) or whether the X509 "));
1886 printf (" %s\n", _("certificate is still valid for the specified number of days."));
1887 printf ("\n");
1888 printf (" %s\n", _("Please note that this plugin does not check if the presented server"));
1889 printf (" %s\n", _("certificate matches the hostname of the server, or if the certificate"));
1890 printf (" %s\n", _("has a valid chain of trust to one of the locally installed CAs."));
1891 printf ("\n");
1892 printf ("%s\n", _("Examples:"));
1893 printf (" %s\n\n", "CHECK CONTENT: check_curl -w 5 -c 10 --ssl -H www.verisign.com");
1894 printf (" %s\n", _("When the 'www.verisign.com' server returns its content within 5 seconds,"));
1895 printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds"));
1896 printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,"));
1897 printf (" %s\n", _("a STATE_CRITICAL will be returned."));
1898 printf ("\n");
1899 printf (" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 14");
1900 printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,"));
1901 printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
1902 printf (" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when"));
1903 printf (" %s\n\n", _("the certificate is expired."));
1904 printf ("\n");
1905 printf (" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 30,14");
1906 printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 30 days,"));
1907 printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
1908 printf (" %s\n", _("30 days, but more than 14 days, a STATE_WARNING is returned."));
1909 printf (" %s\n", _("A STATE_CRITICAL will be returned when certificate expires in less than 14 days"));
1910#endif
1911
1912 printf ("\n %s\n", "CHECK WEBSERVER CONTENT VIA PROXY:");
1913 printf (" %s\n", _("It is recommended to use an environment proxy like:"));
1914 printf (" %s\n", _("http_proxy=http://192.168.100.35:3128 ./check_curl -H www.monitoring-plugins.org"));
1915 printf (" %s\n", _("legacy proxy requests in check_http style still work:"));
1916 printf (" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u http://www.monitoring-plugins.org/ -H www.monitoring-plugins.org"));
1917
1918#ifdef LIBCURL_FEATURE_SSL
1919 printf ("\n %s\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: ");
1920 printf (" %s\n", _("It is recommended to use an environment proxy like:"));
1921 printf (" %s\n", _("https_proxy=http://192.168.100.35:3128 ./check_curl -H www.verisign.com -S"));
1922 printf (" %s\n", _("legacy proxy requests in check_http style still work:"));
1923 printf (" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u https://www.verisign.com/ -S -j CONNECT -H www.verisign.com "));
1924 printf (" %s\n", _("all these options are needed: -I <proxy> -p <proxy-port> -u <check-url> -S(sl) -j CONNECT -H <webserver>"));
1925 printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds"));
1926 printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,"));
1927 printf (" %s\n", _("a STATE_CRITICAL will be returned."));
1928
1929#endif
1930
1931 printf (UT_SUPPORT);
1932
1933}
1934
1935
1936
1937void
1938print_usage (void)
1939{
1940 printf ("%s\n", _("Usage:"));
1941 printf (" %s -H <vhost> | -I <IP-address> [-u <uri>] [-p <port>]\n",progname);
1942 printf (" [-J <client certificate file>] [-K <private key>] [--ca-cert <CA certificate file>] [-D]\n");
1943 printf (" [-w <warn time>] [-c <critical time>] [-t <timeout>] [-L] [-E] [-a auth]\n");
1944 printf (" [-b proxy_auth] [-f <ok|warning|critcal|follow|sticky|stickyport|curl>]\n");
1945 printf (" [-e <expect>] [-d string] [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n");
1946 printf (" [-P string] [-m <min_pg_size>:<max_pg_size>] [-4|-6] [-N] [-M <age>]\n");
1947 printf (" [-A string] [-k string] [-S <version>] [--sni]\n");
1948 printf (" [-T <content-type>] [-j method]\n");
1949 printf (" [--http-version=<version>]\n");
1950 printf (" %s -H <vhost> | -I <IP-address> -C <warn_age>[,<crit_age>]\n",progname);
1951 printf (" [-p <port>] [-t <timeout>] [-4|-6] [--sni]\n");
1952 printf ("\n");
1953#ifdef LIBCURL_FEATURE_SSL
1954 printf ("%s\n", _("In the first form, make an HTTP request."));
1955 printf ("%s\n\n", _("In the second form, connect to the server and check the TLS certificate."));
1956#endif
1957 printf ("%s\n", _("WARNING: check_curl is experimental. Please use"));
1958 printf ("%s\n\n", _("check_http if you need a stable version."));
1959}
1960
1961void
1962print_curl_version (void)
1963{
1964 printf( "%s\n", curl_version());
1965}
1966
1967int
1968curlhelp_initwritebuffer (curlhelp_write_curlbuf *buf)
1969{
1970 buf->bufsize = DEFAULT_BUFFER_SIZE;
1971 buf->buflen = 0;
1972 buf->buf = (char *)malloc ((size_t)buf->bufsize);
1973 if (buf->buf == NULL) return -1;
1974 return 0;
1975}
1976
1977int
1978curlhelp_buffer_write_callback (void *buffer, size_t size, size_t nmemb, void *stream)
1979{
1980 curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream;
1981
1982 while (buf->bufsize < buf->buflen + size * nmemb + 1) {
1983 buf->bufsize *= buf->bufsize * 2;
1984 buf->buf = (char *)realloc (buf->buf, buf->bufsize);
1985 if (buf->buf == NULL) return -1;
1986 }
1987
1988 memcpy (buf->buf + buf->buflen, buffer, size * nmemb);
1989 buf->buflen += size * nmemb;
1990 buf->buf[buf->buflen] = '\0';
1991
1992 return (int)(size * nmemb);
1993}
1994
1995int
1996curlhelp_buffer_read_callback (void *buffer, size_t size, size_t nmemb, void *stream)
1997{
1998 curlhelp_read_curlbuf *buf = (curlhelp_read_curlbuf *)stream;
1999
2000 size_t n = min (nmemb * size, buf->buflen - buf->pos);
2001
2002 memcpy (buffer, buf->buf + buf->pos, n);
2003 buf->pos += n;
2004
2005 return (int)n;
2006}
2007
2008void
2009curlhelp_freewritebuffer (curlhelp_write_curlbuf *buf)
2010{
2011 free (buf->buf);
2012 buf->buf = NULL;
2013}
2014
2015int
2016curlhelp_initreadbuffer (curlhelp_read_curlbuf *buf, const char *data, size_t datalen)
2017{
2018 buf->buflen = datalen;
2019 buf->buf = (char *)malloc ((size_t)buf->buflen);
2020 if (buf->buf == NULL) return -1;
2021 memcpy (buf->buf, data, datalen);
2022 buf->pos = 0;
2023 return 0;
2024}
2025
2026void
2027curlhelp_freereadbuffer (curlhelp_read_curlbuf *buf)
2028{
2029 free (buf->buf);
2030 buf->buf = NULL;
2031}
2032
2033/* TODO: where to put this, it's actually part of sstrings2 (logically)?
2034 */
2035const char*
2036strrstr2(const char *haystack, const char *needle)
2037{
2038 int counter;
2039 size_t len;
2040 const char *prev_pos;
2041 const char *pos;
2042
2043 if (haystack == NULL || needle == NULL)
2044 return NULL;
2045
2046 if (haystack[0] == '\0' || needle[0] == '\0')
2047 return NULL;
2048
2049 counter = 0;
2050 prev_pos = NULL;
2051 pos = haystack;
2052 len = strlen (needle);
2053 for (;;) {
2054 pos = strstr (pos, needle);
2055 if (pos == NULL) {
2056 if (counter == 0)
2057 return NULL;
2058 else
2059 return prev_pos;
2060 }
2061 counter++;
2062 prev_pos = pos;
2063 pos += len;
2064 if (*pos == '\0') return prev_pos;
2065 }
2066}
2067
2068int
2069curlhelp_parse_statusline (const char *buf, curlhelp_statusline *status_line)
2070{
2071 char *first_line_end;
2072 char *p;
2073 size_t first_line_len;
2074 char *pp;
2075 const char *start;
2076 char *first_line_buf;
2077
2078 /* find last start of a new header */
2079 start = strrstr2 (buf, "\r\nHTTP/");
2080 if (start != NULL) {
2081 start += 2;
2082 buf = start;
2083 }
2084
2085 first_line_end = strstr(buf, "\r\n");
2086 if (first_line_end == NULL) return -1;
2087
2088 first_line_len = (size_t)(first_line_end - buf);
2089 status_line->first_line = (char *)malloc (first_line_len + 1);
2090 if (status_line->first_line == NULL) return -1;
2091 memcpy (status_line->first_line, buf, first_line_len);
2092 status_line->first_line[first_line_len] = '\0';
2093 first_line_buf = strdup( status_line->first_line );
2094
2095 /* protocol and version: "HTTP/x.x" SP or "HTTP/2" SP */
2096
2097 p = strtok(first_line_buf, "/");
2098 if( p == NULL ) { free( first_line_buf ); return -1; }
2099 if( strcmp( p, "HTTP" ) != 0 ) { free( first_line_buf ); return -1; }
2100
2101 p = strtok( NULL, " " );
2102 if( p == NULL ) { free( first_line_buf ); return -1; }
2103 if( strchr( p, '.' ) != NULL ) {
2104
2105 /* HTTP 1.x case */
2106 char *ppp;
2107 ppp = strtok( p, "." );
2108 status_line->http_major = (int)strtol( p, &pp, 10 );
2109 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
2110 ppp = strtok( NULL, " " );
2111 status_line->http_minor = (int)strtol( p, &pp, 10 );
2112 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
2113 p += 4; /* 1.x SP */
2114 } else {
2115 /* HTTP 2 case */
2116 status_line->http_major = (int)strtol( p, &pp, 10 );
2117 status_line->http_minor = 0;
2118 p += 2; /* 2 SP */
2119 }
2120
2121 /* status code: "404" or "404.1", then SP */
2122
2123 p = strtok( p, " " );
2124 if( p == NULL ) { free( first_line_buf ); return -1; }
2125 if( strchr( p, '.' ) != NULL ) {
2126 char *ppp;
2127 ppp = strtok( p, "." );
2128 status_line->http_code = (int)strtol( ppp, &pp, 10 );
2129 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
2130 ppp = strtok( NULL, "" );
2131 status_line->http_subcode = (int)strtol( ppp, &pp, 10 );
2132 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
2133 p += 6; /* 400.1 SP */
2134 } else {
2135 status_line->http_code = (int)strtol( p, &pp, 10 );
2136 status_line->http_subcode = -1;
2137 if( *pp != '\0' ) { free( first_line_buf ); return -1; }
2138 p += 4; /* 400 SP */
2139 }
2140
2141 /* Human readable message: "Not Found" CRLF */
2142
2143 p = strtok( p, "" );
2144 if( p == NULL ) { status_line->msg = ""; return 0; }
2145 status_line->msg = status_line->first_line + ( p - first_line_buf );
2146 free( first_line_buf );
2147
2148 return 0;
2149}
2150
2151void
2152curlhelp_free_statusline (curlhelp_statusline *status_line)
2153{
2154 free (status_line->first_line);
2155}
2156
2157void
2158remove_newlines (char *s)
2159{
2160 char *p;
2161
2162 for (p = s; *p != '\0'; p++)
2163 if (*p == '\r' || *p == '\n')
2164 *p = ' ';
2165}
2166
2167char *
2168get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header)
2169{
2170 int i;
2171 for( i = 0; i < nof_headers; i++ ) {
2172 if(headers[i].name != NULL && strncasecmp( header, headers[i].name, max( headers[i].name_len, 4 ) ) == 0 ) {
2173 return strndup( headers[i].value, headers[i].value_len );
2174 }
2175 }
2176 return NULL;
2177}
2178
2179int
2180check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFAULT_BUFFER_SIZE])
2181{
2182 char *server_date = NULL;
2183 char *document_date = NULL;
2184 int date_result = STATE_OK;
2185 curlhelp_statusline status_line;
2186 struct phr_header headers[255];
2187 size_t nof_headers = 255;
2188 size_t msglen;
2189
2190 int res = phr_parse_response (header_buf->buf, header_buf->buflen,
2191 &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen,
2192 headers, &nof_headers, 0);
2193
2194 server_date = get_header_value (headers, nof_headers, "date");
2195 document_date = get_header_value (headers, nof_headers, "last-modified");
2196
2197 if (!server_date || !*server_date) {
2198 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sServer date unknown, "), *msg);
2199 date_result = max_state_alt(STATE_UNKNOWN, date_result);
2200 } else if (!document_date || !*document_date) {
2201 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument modification date unknown, "), *msg);
2202 date_result = max_state_alt(STATE_CRITICAL, date_result);
2203 } else {
2204 time_t srv_data = curl_getdate (server_date, NULL);
2205 time_t doc_data = curl_getdate (document_date, NULL);
2206 if (verbose >= 2)
2207 printf ("* server date: '%s' (%d), doc_date: '%s' (%d)\n", server_date, (int)srv_data, document_date, (int)doc_data);
2208 if (srv_data <= 0) {
2209 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sServer date \"%100s\" unparsable, "), *msg, server_date);
2210 date_result = max_state_alt(STATE_CRITICAL, date_result);
2211 } else if (doc_data <= 0) {
2212 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date);
2213 date_result = max_state_alt(STATE_CRITICAL, date_result);
2214 } else if (doc_data > srv_data + 30) {
2215 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data);
2216 date_result = max_state_alt(STATE_CRITICAL, date_result);
2217 } else if (doc_data < srv_data - maximum_age) {
2218 int n = (srv_data - doc_data);
2219 if (n > (60 * 60 * 24 * 2)) {
2220 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24));
2221 date_result = max_state_alt(STATE_CRITICAL, date_result);
2222 } else {
2223 snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60);
2224 date_result = max_state_alt(STATE_CRITICAL, date_result);
2225 }
2226 }
2227 }
2228
2229 if (server_date) free (server_date);
2230 if (document_date) free (document_date);
2231
2232 return date_result;
2233}
2234
2235
2236int
2237get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_write_curlbuf* body_buf)
2238{
2239 const char *s;
2240 int content_length = 0;
2241 char *copy;
2242 struct phr_header headers[255];
2243 size_t nof_headers = 255;
2244 size_t msglen;
2245 char *content_length_s = NULL;
2246 curlhelp_statusline status_line;
2247
2248 int res = phr_parse_response (header_buf->buf, header_buf->buflen,
2249 &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen,
2250 headers, &nof_headers, 0);
2251
2252 content_length_s = get_header_value (headers, nof_headers, "content-length");
2253 if (!content_length_s) {
2254 return header_buf->buflen + body_buf->buflen;
2255 }
2256 content_length_s += strspn (content_length_s, " \t");
2257 content_length = atoi (content_length_s);
2258 if (content_length != body_buf->buflen) {
2259 /* TODO: should we warn if the actual and the reported body length don't match? */
2260 }
2261
2262 if (content_length_s) free (content_length_s);
2263
2264 return header_buf->buflen + body_buf->buflen;
2265}
2266
2267/* TODO: is there a better way in libcurl to check for the SSL library? */
2268curlhelp_ssl_library
2269curlhelp_get_ssl_library (CURL* curl)
2270{
2271 curl_version_info_data* version_data;
2272 char *ssl_version;
2273 char *library;
2274 curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN;
2275
2276 version_data = curl_version_info (CURLVERSION_NOW);
2277 if (version_data == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN;
2278
2279 ssl_version = strdup (version_data->ssl_version);
2280 if (ssl_version == NULL ) return CURLHELP_SSL_LIBRARY_UNKNOWN;
2281
2282 library = strtok (ssl_version, "/");
2283 if (library == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN;
2284
2285 if (strcmp (library, "OpenSSL") == 0)
2286 ssl_library = CURLHELP_SSL_LIBRARY_OPENSSL;
2287 else if (strcmp (library, "LibreSSL") == 0)
2288 ssl_library = CURLHELP_SSL_LIBRARY_LIBRESSL;
2289 else if (strcmp (library, "GnuTLS") == 0)
2290 ssl_library = CURLHELP_SSL_LIBRARY_GNUTLS;
2291 else if (strcmp (library, "NSS") == 0)
2292 ssl_library = CURLHELP_SSL_LIBRARY_NSS;
2293
2294 if (verbose >= 2)
2295 printf ("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library, ssl_library);
2296
2297 free (ssl_version);
2298
2299 return ssl_library;
2300}
2301
2302const char*
2303curlhelp_get_ssl_library_string (curlhelp_ssl_library ssl_library)
2304{
2305 switch (ssl_library) {
2306 case CURLHELP_SSL_LIBRARY_OPENSSL:
2307 return "OpenSSL";
2308 case CURLHELP_SSL_LIBRARY_LIBRESSL:
2309 return "LibreSSL";
2310 case CURLHELP_SSL_LIBRARY_GNUTLS:
2311 return "GnuTLS";
2312 case CURLHELP_SSL_LIBRARY_NSS:
2313 return "NSS";
2314 case CURLHELP_SSL_LIBRARY_UNKNOWN:
2315 default:
2316 return "unknown";
2317 }
2318}
2319
2320#ifdef LIBCURL_FEATURE_SSL
2321#ifndef USE_OPENSSL
2322time_t
2323parse_cert_date (const char *s)
2324{
2325 struct tm tm;
2326 time_t date;
2327 char *res;
2328
2329 if (!s) return -1;
2330
2331 /* Jan 17 14:25:12 2020 GMT */
2332 res = strptime (s, "%Y-%m-%d %H:%M:%S GMT", &tm);
2333 /* Sep 11 12:00:00 2020 GMT */
2334 if (res == NULL) strptime (s, "%Y %m %d %H:%M:%S GMT", &tm);
2335 date = mktime (&tm);
2336
2337 return date;
2338}
2339
2340/* TODO: this needs cleanup in the sslutils.c, maybe we the #else case to
2341 * OpenSSL could be this function
2342 */
2343int
2344net_noopenssl_check_certificate (cert_ptr_union* cert_ptr, int days_till_exp_warn, int days_till_exp_crit)
2345{
2346 int i;
2347 struct curl_slist* slist;
2348 int cname_found = 0;
2349 char* start_date_str = NULL;
2350 char* end_date_str = NULL;
2351 time_t start_date;
2352 time_t end_date;
2353 char *tz;
2354 float time_left;
2355 int days_left;
2356 int time_remaining;
2357 char timestamp[50] = "";
2358 int status = STATE_UNKNOWN;
2359
2360 if (verbose >= 2)
2361 printf ("**** REQUEST CERTIFICATES ****\n");
2362
2363 for (i = 0; i < cert_ptr->to_certinfo->num_of_certs; i++) {
2364 for (slist = cert_ptr->to_certinfo->certinfo[i]; slist; slist = slist->next) {
2365 /* find first common name in subject,
2366 * TODO: check alternative subjects for
2367 * TODO: have a decent parser here and not a hack
2368 * multi-host certificate, check wildcards
2369 */
2370 if (strncasecmp (slist->data, "Subject:", 8) == 0) {
2371 int d = 3;
2372 char* p = strstr (slist->data, "CN=");
2373 if (p == NULL) {
2374 d = 5;
2375 p = strstr (slist->data, "CN = ");
2376 }
2377 if (p != NULL) {
2378 if (strncmp (host_name, p+d, strlen (host_name)) == 0) {
2379 cname_found = 1;
2380 }
2381 }
2382 } else if (strncasecmp (slist->data, "Start Date:", 11) == 0) {
2383 start_date_str = &slist->data[11];
2384 } else if (strncasecmp (slist->data, "Expire Date:", 12) == 0) {
2385 end_date_str = &slist->data[12];
2386 } else if (strncasecmp (slist->data, "Cert:", 5) == 0) {
2387 goto HAVE_FIRST_CERT;
2388 }
2389 if (verbose >= 2)
2390 printf ("%d ** %s\n", i, slist->data);
2391 }
2392 }
2393HAVE_FIRST_CERT:
2394
2395 if (verbose >= 2)
2396 printf ("**** REQUEST CERTIFICATES ****\n");
2397
2398 if (!cname_found) {
2399 printf("%s\n",_("CRITICAL - Cannot retrieve certificate subject."));
2400 return STATE_CRITICAL;
2401 }
2402
2403 start_date = parse_cert_date (start_date_str);
2404 if (start_date <= 0) {
2405 snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Start Date' in certificate: '%s'"),
2406 start_date_str);
2407 puts (msg);
2408 return STATE_WARNING;
2409 }
2410
2411 end_date = parse_cert_date (end_date_str);
2412 if (end_date <= 0) {
2413 snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Expire Date' in certificate: '%s'"),
2414 start_date_str);
2415 puts (msg);
2416 return STATE_WARNING;
2417 }
2418
2419 time_left = difftime (end_date, time(NULL));
2420 days_left = time_left / 86400;
2421 tz = getenv("TZ");
2422 setenv("TZ", "GMT", 1);
2423 tzset();
2424 strftime(timestamp, 50, "%c %z", localtime(&end_date));
2425 if (tz)
2426 setenv("TZ", tz, 1);
2427 else
2428 unsetenv("TZ");
2429 tzset();
2430
2431 if (days_left > 0 && days_left <= days_till_exp_warn) {
2432 printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, days_left, timestamp);
2433 if (days_left > days_till_exp_crit)
2434 status = STATE_WARNING;
2435 else
2436 status = STATE_CRITICAL;
2437 } else if (days_left == 0 && time_left > 0) {
2438 if (time_left >= 3600)
2439 time_remaining = (int) time_left / 3600;
2440 else
2441 time_remaining = (int) time_left / 60;
2442
2443 printf (_("%s - Certificate '%s' expires in %u %s (%s)\n"),
2444 (days_left>days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name, time_remaining,
2445 time_left >= 3600 ? "hours" : "minutes", timestamp);
2446
2447 if ( days_left > days_till_exp_crit)
2448 status = STATE_WARNING;
2449 else
2450 status = STATE_CRITICAL;
2451 } else if (time_left < 0) {
2452 printf(_("CRITICAL - Certificate '%s' expired on %s.\n"), host_name, timestamp);
2453 status=STATE_CRITICAL;
2454 } else if (days_left == 0) {
2455 printf (_("%s - Certificate '%s' just expired (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, timestamp);
2456 if (days_left > days_till_exp_crit)
2457 status = STATE_WARNING;
2458 else
2459 status = STATE_CRITICAL;
2460 } else {
2461 printf(_("OK - Certificate '%s' will expire on %s.\n"), host_name, timestamp);
2462 status = STATE_OK;
2463 }
2464 return status;
2465}
2466#endif /* USE_OPENSSL */
2467#endif /* LIBCURL_FEATURE_SSL */
diff --git a/plugins/check_dbi.c b/plugins/check_dbi.c
index 826eb8d..ced13d0 100644
--- a/plugins/check_dbi.c
+++ b/plugins/check_dbi.c
@@ -35,6 +35,7 @@ const char *email = "devel@monitoring-plugins.org";
35 35
36#include "common.h" 36#include "common.h"
37#include "utils.h" 37#include "utils.h"
38#include "utils_cmd.h"
38 39
39#include "netutils.h" 40#include "netutils.h"
40 41
diff --git a/plugins/check_dig.c b/plugins/check_dig.c
index db4b20e..5d85ae2 100644
--- a/plugins/check_dig.c
+++ b/plugins/check_dig.c
@@ -48,7 +48,7 @@ void print_usage (void);
48 48
49#define UNDEFINED 0 49#define UNDEFINED 0
50#define DEFAULT_PORT 53 50#define DEFAULT_PORT 53
51#define DEFAULT_TRIES 3 51#define DEFAULT_TRIES 2
52 52
53char *query_address = NULL; 53char *query_address = NULL;
54char *record_type = "A"; 54char *record_type = "A";
@@ -94,7 +94,7 @@ main (int argc, char **argv)
94 timeout_interval_dig = timeout_interval / number_tries + number_tries; 94 timeout_interval_dig = timeout_interval / number_tries + number_tries;
95 95
96 /* get the command to run */ 96 /* get the command to run */
97 xasprintf (&command_line, "%s %s %s -p %d @%s %s %s +tries=%d +time=%d", 97 xasprintf (&command_line, "%s %s %s -p %d @%s %s %s +retry=%d +time=%d",
98 PATH_TO_DIG, dig_args, query_transport, server_port, dns_server, query_address, record_type, number_tries, timeout_interval_dig); 98 PATH_TO_DIG, dig_args, query_transport, server_port, dns_server, query_address, record_type, number_tries, timeout_interval_dig);
99 99
100 alarm (timeout_interval); 100 alarm (timeout_interval);
@@ -125,7 +125,7 @@ main (int argc, char **argv)
125 if (verbose) 125 if (verbose)
126 printf ("%s\n", chld_out.line[i]); 126 printf ("%s\n", chld_out.line[i]);
127 127
128 if (strstr (chld_out.line[i], (expected_address == NULL ? query_address : expected_address)) != NULL) { 128 if (strcasestr (chld_out.line[i], (expected_address == NULL ? query_address : expected_address)) != NULL) {
129 msg = chld_out.line[i]; 129 msg = chld_out.line[i];
130 result = STATE_OK; 130 result = STATE_OK;
131 131
@@ -331,7 +331,7 @@ print_help (void)
331 printf ("Copyright (c) 2000 Karl DeBisschop <kdebisschop@users.sourceforge.net>\n"); 331 printf ("Copyright (c) 2000 Karl DeBisschop <kdebisschop@users.sourceforge.net>\n");
332 printf (COPYRIGHT, copyright, email); 332 printf (COPYRIGHT, copyright, email);
333 333
334 printf (_("This plugin test the DNS service on the specified host using dig")); 334 printf (_("This plugin tests the DNS service on the specified host using dig"));
335 335
336 printf ("\n\n"); 336 printf ("\n\n");
337 337
diff --git a/plugins/check_disk.c b/plugins/check_disk.c
index b338684..a273519 100644
--- a/plugins/check_disk.c
+++ b/plugins/check_disk.c
@@ -58,9 +58,6 @@ const char *email = "devel@monitoring-plugins.org";
58# define ERROR -1 58# define ERROR -1
59#endif 59#endif
60 60
61/* If nonzero, show inode information. */
62static int inode_format = 1;
63
64/* If nonzero, show even filesystems with zero size or 61/* If nonzero, show even filesystems with zero size or
65 uninteresting types. */ 62 uninteresting types. */
66static int show_all_fs = 1; 63static int show_all_fs = 1;
@@ -144,6 +141,7 @@ int erronly = FALSE;
144int display_mntp = FALSE; 141int display_mntp = FALSE;
145int exact_match = FALSE; 142int exact_match = FALSE;
146int freespace_ignore_reserved = FALSE; 143int freespace_ignore_reserved = FALSE;
144int display_inodes_perfdata = FALSE;
147char *warn_freespace_units = NULL; 145char *warn_freespace_units = NULL;
148char *crit_freespace_units = NULL; 146char *crit_freespace_units = NULL;
149char *warn_freespace_percent = NULL; 147char *warn_freespace_percent = NULL;
@@ -170,6 +168,7 @@ main (int argc, char **argv)
170 char *output; 168 char *output;
171 char *details; 169 char *details;
172 char *perf; 170 char *perf;
171 char *perf_ilabel;
173 char *preamble; 172 char *preamble;
174 char *flag_header; 173 char *flag_header;
175 double inode_space_pct; 174 double inode_space_pct;
@@ -178,7 +177,7 @@ main (int argc, char **argv)
178 int temp_result; 177 int temp_result;
179 178
180 struct mount_entry *me; 179 struct mount_entry *me;
181 struct fs_usage fsp, tmpfsp; 180 struct fs_usage fsp;
182 struct parameter_list *temp_list, *path; 181 struct parameter_list *temp_list, *path;
183 182
184#ifdef __CYGWIN__ 183#ifdef __CYGWIN__
@@ -189,6 +188,7 @@ main (int argc, char **argv)
189 output = strdup (""); 188 output = strdup ("");
190 details = strdup (""); 189 details = strdup ("");
191 perf = strdup (""); 190 perf = strdup ("");
191 perf_ilabel = strdup ("");
192 stat_buf = malloc(sizeof *stat_buf); 192 stat_buf = malloc(sizeof *stat_buf);
193 193
194 setlocale (LC_ALL, ""); 194 setlocale (LC_ALL, "");
@@ -351,6 +351,29 @@ main (int argc, char **argv)
351 TRUE, 0, 351 TRUE, 0,
352 TRUE, path->dtotal_units)); 352 TRUE, path->dtotal_units));
353 353
354 if (display_inodes_perfdata) {
355 /* *_high_tide must be reinitialized at each run */
356 warning_high_tide = UINT_MAX;
357 critical_high_tide = UINT_MAX;
358
359 if (path->freeinodes_percent->warning != NULL) {
360 warning_high_tide = abs( min( (double) warning_high_tide, (double) (1.0 - path->freeinodes_percent->warning->end/100)*path->inodes_total ));
361 }
362 if (path->freeinodes_percent->critical != NULL) {
363 critical_high_tide = abs( min( (double) critical_high_tide, (double) (1.0 - path->freeinodes_percent->critical->end/100)*path->inodes_total ));
364 }
365
366 xasprintf (&perf_ilabel, "%s (inodes)", (!strcmp(me->me_mountdir, "none") || display_mntp) ? me->me_devname : me->me_mountdir);
367 /* Nb: *_high_tide are unset when == UINT_MAX */
368 xasprintf (&perf, "%s %s", perf,
369 perfdata (perf_ilabel,
370 path->inodes_used, "",
371 (warning_high_tide != UINT_MAX ? TRUE : FALSE), warning_high_tide,
372 (critical_high_tide != UINT_MAX ? TRUE : FALSE), critical_high_tide,
373 TRUE, 0,
374 TRUE, path->inodes_total));
375 }
376
354 if (disk_result==STATE_OK && erronly && !verbose) 377 if (disk_result==STATE_OK && erronly && !verbose)
355 continue; 378 continue;
356 379
@@ -423,9 +446,7 @@ process_arguments (int argc, char **argv)
423 int c, err; 446 int c, err;
424 struct parameter_list *se; 447 struct parameter_list *se;
425 struct parameter_list *temp_list = NULL, *previous = NULL; 448 struct parameter_list *temp_list = NULL, *previous = NULL;
426 struct parameter_list *temp_path_select_list = NULL; 449 struct mount_entry *me;
427 struct mount_entry *me, *temp_me;
428 int result = OK;
429 regex_t re; 450 regex_t re;
430 int cflags = REG_NOSUB | REG_EXTENDED; 451 int cflags = REG_NOSUB | REG_EXTENDED;
431 int default_cflags = cflags; 452 int default_cflags = cflags;
@@ -460,6 +481,7 @@ process_arguments (int argc, char **argv)
460 {"ignore-eregi-partition", required_argument, 0, 'I'}, 481 {"ignore-eregi-partition", required_argument, 0, 'I'},
461 {"local", no_argument, 0, 'l'}, 482 {"local", no_argument, 0, 'l'},
462 {"stat-remote-fs", no_argument, 0, 'L'}, 483 {"stat-remote-fs", no_argument, 0, 'L'},
484 {"iperfdata", no_argument, 0, 'P'},
463 {"mountpoint", no_argument, 0, 'M'}, 485 {"mountpoint", no_argument, 0, 'M'},
464 {"errors-only", no_argument, 0, 'e'}, 486 {"errors-only", no_argument, 0, 'e'},
465 {"exact-match", no_argument, 0, 'E'}, 487 {"exact-match", no_argument, 0, 'E'},
@@ -482,7 +504,7 @@ process_arguments (int argc, char **argv)
482 strcpy (argv[c], "-t"); 504 strcpy (argv[c], "-t");
483 505
484 while (1) { 506 while (1) {
485 c = getopt_long (argc, argv, "+?VqhvefCt:c:w:K:W:u:p:x:X:N:mklLg:R:r:i:I:MEA", longopts, &option); 507 c = getopt_long (argc, argv, "+?VqhvefCt:c:w:K:W:u:p:x:X:N:mklLPg:R:r:i:I:MEA", longopts, &option);
486 508
487 if (c == -1 || c == EOF) 509 if (c == -1 || c == EOF)
488 break; 510 break;
@@ -587,9 +609,13 @@ process_arguments (int argc, char **argv)
587 break; 609 break;
588 case 'L': 610 case 'L':
589 stat_remote_fs = 1; 611 stat_remote_fs = 1;
612 /* fallthrough */
590 case 'l': 613 case 'l':
591 show_local_fs = 1; 614 show_local_fs = 1;
592 break; 615 break;
616 case 'P':
617 display_inodes_perfdata = 1;
618 break;
593 case 'p': /* select path */ 619 case 'p': /* select path */
594 if (! (warn_freespace_units || crit_freespace_units || warn_freespace_percent || 620 if (! (warn_freespace_units || crit_freespace_units || warn_freespace_percent ||
595 crit_freespace_percent || warn_usedspace_units || crit_usedspace_units || 621 crit_freespace_percent || warn_usedspace_units || crit_usedspace_units ||
@@ -909,6 +935,8 @@ print_help (void)
909 printf (" %s\n", _("Display only devices/mountpoints with errors")); 935 printf (" %s\n", _("Display only devices/mountpoints with errors"));
910 printf (" %s\n", "-f, --freespace-ignore-reserved"); 936 printf (" %s\n", "-f, --freespace-ignore-reserved");
911 printf (" %s\n", _("Don't account root-reserved blocks into freespace in perfdata")); 937 printf (" %s\n", _("Don't account root-reserved blocks into freespace in perfdata"));
938 printf (" %s\n", "-P, --iperfdata");
939 printf (" %s\n", _("Display inode usage in perfdata"));
912 printf (" %s\n", "-g, --group=NAME"); 940 printf (" %s\n", "-g, --group=NAME");
913 printf (" %s\n", _("Group paths. Thresholds apply to (free-)space of all partitions together")); 941 printf (" %s\n", _("Group paths. Thresholds apply to (free-)space of all partitions together"));
914 printf (" %s\n", "-k, --kilobytes"); 942 printf (" %s\n", "-k, --kilobytes");
@@ -1017,6 +1045,8 @@ get_stats (struct parameter_list *p, struct fs_usage *fsp) {
1017 p->dtotal_units += p_list->dtotal_units; 1045 p->dtotal_units += p_list->dtotal_units;
1018 p->inodes_total += p_list->inodes_total; 1046 p->inodes_total += p_list->inodes_total;
1019 p->inodes_free += p_list->inodes_free; 1047 p->inodes_free += p_list->inodes_free;
1048 p->inodes_free_to_root += p_list->inodes_free_to_root;
1049 p->inodes_used += p_list->inodes_used;
1020 } 1050 }
1021 first = 0; 1051 first = 0;
1022 } 1052 }
@@ -1052,7 +1082,18 @@ get_path_stats (struct parameter_list *p, struct fs_usage *fsp) {
1052 p->dused_units = p->used*fsp->fsu_blocksize/mult; 1082 p->dused_units = p->used*fsp->fsu_blocksize/mult;
1053 p->dfree_units = p->available*fsp->fsu_blocksize/mult; 1083 p->dfree_units = p->available*fsp->fsu_blocksize/mult;
1054 p->dtotal_units = p->total*fsp->fsu_blocksize/mult; 1084 p->dtotal_units = p->total*fsp->fsu_blocksize/mult;
1055 p->inodes_total = fsp->fsu_files; /* Total file nodes. */ 1085 /* Free file nodes. Not sure the workaround is required, but in case...*/
1056 p->inodes_free = fsp->fsu_ffree; /* Free file nodes. */ 1086 p->inodes_free = fsp->fsu_favail > fsp->fsu_ffree ? 0 : fsp->fsu_favail;
1087 p->inodes_free_to_root = fsp->fsu_ffree; /* Free file nodes for root. */
1088 p->inodes_used = fsp->fsu_files - fsp->fsu_ffree;
1089 if (freespace_ignore_reserved) {
1090 /* option activated : we substract the root-reserved inodes from the total */
1091 /* not all OS report fsp->fsu_favail, only the ones with statvfs syscall */
1092 /* for others, fsp->fsu_ffree == fsp->fsu_favail */
1093 p->inodes_total = fsp->fsu_files - p->inodes_free_to_root + p->inodes_free;
1094 } else {
1095 /* default behaviour : take all the inodes into account */
1096 p->inodes_total = fsp->fsu_files;
1097 }
1057 np_add_name(&seen, p->best_match->me_mountdir); 1098 np_add_name(&seen, p->best_match->me_mountdir);
1058} 1099}
diff --git a/plugins/check_dns.c b/plugins/check_dns.c
index d6bd2c0..0f2e654 100644
--- a/plugins/check_dns.c
+++ b/plugins/check_dns.c
@@ -42,6 +42,8 @@ const char *email = "devel@monitoring-plugins.org";
42int process_arguments (int, char **); 42int process_arguments (int, char **);
43int validate_arguments (void); 43int validate_arguments (void);
44int error_scan (char *); 44int error_scan (char *);
45int ip_match_cidr(const char *, const char *);
46unsigned long ip2long(const char *);
45void print_help (void); 47void print_help (void);
46void print_usage (void); 48void print_usage (void);
47 49
@@ -54,6 +56,7 @@ char **expected_address = NULL;
54int expected_address_cnt = 0; 56int expected_address_cnt = 0;
55 57
56int expect_authority = FALSE; 58int expect_authority = FALSE;
59int all_match = FALSE;
57thresholds *time_thresholds = NULL; 60thresholds *time_thresholds = NULL;
58 61
59static int 62static int
@@ -81,7 +84,6 @@ main (int argc, char **argv)
81 double elapsed_time; 84 double elapsed_time;
82 long microsec; 85 long microsec;
83 struct timeval tv; 86 struct timeval tv;
84 int multi_address;
85 int parse_address = FALSE; /* This flag scans for Address: but only after Name: */ 87 int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
86 output chld_out, chld_err; 88 output chld_out, chld_err;
87 size_t i; 89 size_t i;
@@ -127,7 +129,7 @@ main (int argc, char **argv)
127 if (verbose) 129 if (verbose)
128 puts(chld_out.line[i]); 130 puts(chld_out.line[i]);
129 131
130 if (strstr (chld_out.line[i], ".in-addr.arpa")) { 132 if (strcasestr (chld_out.line[i], ".in-addr.arpa") || strcasestr (chld_out.line[i], ".ip6.arpa")) {
131 if ((temp_buffer = strstr (chld_out.line[i], "name = "))) 133 if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
132 addresses[n_addresses++] = strdup (temp_buffer + 7); 134 addresses[n_addresses++] = strdup (temp_buffer + 7);
133 else { 135 else {
@@ -167,8 +169,8 @@ main (int argc, char **argv)
167 temp_buffer++; 169 temp_buffer++;
168 170
169 /* Strip leading spaces */ 171 /* Strip leading spaces */
170 for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++) 172 while (*temp_buffer == ' ')
171 /* NOOP */; 173 temp_buffer++;
172 174
173 strip(temp_buffer); 175 strip(temp_buffer);
174 if (temp_buffer==NULL || strlen(temp_buffer)==0) { 176 if (temp_buffer==NULL || strlen(temp_buffer)==0) {
@@ -200,7 +202,10 @@ main (int argc, char **argv)
200 if (error_scan (chld_err.line[i]) != STATE_OK) { 202 if (error_scan (chld_err.line[i]) != STATE_OK) {
201 result = max_state (result, error_scan (chld_err.line[i])); 203 result = max_state (result, error_scan (chld_err.line[i]));
202 msg = strchr(input_buffer, ':'); 204 msg = strchr(input_buffer, ':');
203 if(msg) msg++; 205 if(msg)
206 msg++;
207 else
208 msg = input_buffer;
204 } 209 }
205 } 210 }
206 211
@@ -227,11 +232,27 @@ main (int argc, char **argv)
227 if (result == STATE_OK && expected_address_cnt > 0) { 232 if (result == STATE_OK && expected_address_cnt > 0) {
228 result = STATE_CRITICAL; 233 result = STATE_CRITICAL;
229 temp_buffer = ""; 234 temp_buffer = "";
235 unsigned long expect_match = (1 << expected_address_cnt) - 1;
236 unsigned long addr_match = (1 << n_addresses) - 1;
237
230 for (i=0; i<expected_address_cnt; i++) { 238 for (i=0; i<expected_address_cnt; i++) {
231 /* check if we get a match and prepare an error string */ 239 int j;
232 if (strcmp(address, expected_address[i]) == 0) result = STATE_OK; 240 /* check if we get a match on 'raw' ip or cidr */
241 for (j=0; j<n_addresses; j++) {
242 if ( strcmp(addresses[j], expected_address[i]) == 0
243 || ip_match_cidr(addresses[j], expected_address[i]) ) {
244 result = STATE_OK;
245 addr_match &= ~(1 << j);
246 expect_match &= ~(1 << i);
247 }
248 }
249
250 /* prepare an error string */
233 xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]); 251 xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
234 } 252 }
253 /* check if expected_address must cover all in addresses and none may be missing */
254 if (all_match && (expect_match != 0 || addr_match != 0))
255 result = STATE_CRITICAL;
235 if (result == STATE_CRITICAL) { 256 if (result == STATE_CRITICAL) {
236 /* Strip off last semicolon... */ 257 /* Strip off last semicolon... */
237 temp_buffer[strlen(temp_buffer)-2] = '\0'; 258 temp_buffer[strlen(temp_buffer)-2] = '\0';
@@ -249,11 +270,6 @@ main (int argc, char **argv)
249 elapsed_time = (double)microsec / 1.0e6; 270 elapsed_time = (double)microsec / 1.0e6;
250 271
251 if (result == STATE_OK) { 272 if (result == STATE_OK) {
252 if (strchr (address, ',') == NULL)
253 multi_address = FALSE;
254 else
255 multi_address = TRUE;
256
257 result = get_status(elapsed_time, time_thresholds); 273 result = get_status(elapsed_time, time_thresholds);
258 if (result == STATE_OK) { 274 if (result == STATE_OK) {
259 printf ("DNS %s: ", _("OK")); 275 printf ("DNS %s: ", _("OK"));
@@ -295,7 +311,32 @@ main (int argc, char **argv)
295 return result; 311 return result;
296} 312}
297 313
314int
315ip_match_cidr(const char *addr, const char *cidr_ro)
316{
317 char *subnet, *mask_c, *cidr = strdup(cidr_ro);
318 int mask;
319 subnet = strtok(cidr, "/");
320 mask_c = strtok(NULL, "\0");
321 if (!subnet || !mask_c)
322 return FALSE;
323 mask = atoi(mask_c);
324
325 /* https://www.cryptobells.com/verifying-ips-in-a-subnet-in-php/ */
326 return (ip2long(addr) & ~((1 << (32 - mask)) - 1)) == (ip2long(subnet) >> (32 - mask)) << (32 - mask);
327}
298 328
329unsigned long
330ip2long(const char* src) {
331 unsigned long ip[4];
332 /* http://computer-programming-forum.com/47-c-language/1376ffb92a12c471.htm */
333 return (sscanf(src, "%3lu.%3lu.%3lu.%3lu",
334 &ip[0], &ip[1], &ip[2], &ip[3]) == 4 &&
335 ip[0] < 256 && ip[1] < 256 &&
336 ip[2] < 256 && ip[3] < 256)
337 ? ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3]
338 : 0;
339}
299 340
300int 341int
301error_scan (char *input_buffer) 342error_scan (char *input_buffer)
@@ -310,6 +351,8 @@ error_scan (char *input_buffer)
310 /* DNS server is not running... */ 351 /* DNS server is not running... */
311 else if (strstr (input_buffer, "No response from server")) 352 else if (strstr (input_buffer, "No response from server"))
312 die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server); 353 die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server);
354 else if (strstr (input_buffer, "no servers could be reached"))
355 die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server);
313 356
314 /* Host name is valid, but server doesn't have records... */ 357 /* Host name is valid, but server doesn't have records... */
315 else if (strstr (input_buffer, "No records")) 358 else if (strstr (input_buffer, "No records"))
@@ -334,6 +377,7 @@ error_scan (char *input_buffer)
334 /* Host or domain name does not exist */ 377 /* Host or domain name does not exist */
335 else if (strstr (input_buffer, "Non-existent") || 378 else if (strstr (input_buffer, "Non-existent") ||
336 strstr (input_buffer, "** server can't find") || 379 strstr (input_buffer, "** server can't find") ||
380 strstr (input_buffer, "** Can't find") ||
337 strstr (input_buffer,"NXDOMAIN")) 381 strstr (input_buffer,"NXDOMAIN"))
338 die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address); 382 die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address);
339 383
@@ -374,6 +418,7 @@ process_arguments (int argc, char **argv)
374 {"reverse-server", required_argument, 0, 'r'}, 418 {"reverse-server", required_argument, 0, 'r'},
375 {"expected-address", required_argument, 0, 'a'}, 419 {"expected-address", required_argument, 0, 'a'},
376 {"expect-authority", no_argument, 0, 'A'}, 420 {"expect-authority", no_argument, 0, 'A'},
421 {"all", no_argument, 0, 'L'},
377 {"warning", required_argument, 0, 'w'}, 422 {"warning", required_argument, 0, 'w'},
378 {"critical", required_argument, 0, 'c'}, 423 {"critical", required_argument, 0, 'c'},
379 {0, 0, 0, 0} 424 {0, 0, 0, 0}
@@ -387,7 +432,7 @@ process_arguments (int argc, char **argv)
387 strcpy (argv[c], "-t"); 432 strcpy (argv[c], "-t");
388 433
389 while (1) { 434 while (1) {
390 c = getopt_long (argc, argv, "hVvAt:H:s:r:a:w:c:", long_opts, &opt_index); 435 c = getopt_long (argc, argv, "hVvALt:H:s:r:a:w:c:", long_opts, &opt_index);
391 436
392 if (c == -1 || c == EOF) 437 if (c == -1 || c == EOF)
393 break; 438 break;
@@ -428,13 +473,30 @@ process_arguments (int argc, char **argv)
428 case 'a': /* expected address */ 473 case 'a': /* expected address */
429 if (strlen (optarg) >= ADDRESS_LENGTH) 474 if (strlen (optarg) >= ADDRESS_LENGTH)
430 die (STATE_UNKNOWN, _("Input buffer overflow\n")); 475 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
431 expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**)); 476 if (strchr(optarg, ',') != NULL) {
432 expected_address[expected_address_cnt] = strdup(optarg); 477 char *comma = strchr(optarg, ',');
433 expected_address_cnt++; 478 while (comma != NULL) {
479 expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**));
480 expected_address[expected_address_cnt] = strndup(optarg, comma - optarg);
481 expected_address_cnt++;
482 optarg = comma + 1;
483 comma = strchr(optarg, ',');
484 }
485 expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**));
486 expected_address[expected_address_cnt] = strdup(optarg);
487 expected_address_cnt++;
488 } else {
489 expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**));
490 expected_address[expected_address_cnt] = strdup(optarg);
491 expected_address_cnt++;
492 }
434 break; 493 break;
435 case 'A': /* expect authority */ 494 case 'A': /* expect authority */
436 expect_authority = TRUE; 495 expect_authority = TRUE;
437 break; 496 break;
497 case 'L': /* all must match */
498 all_match = TRUE;
499 break;
438 case 'w': 500 case 'w':
439 warning = optarg; 501 warning = optarg;
440 break; 502 break;
@@ -500,17 +562,19 @@ print_help (void)
500 printf (" %s\n", _("The name or address you want to query")); 562 printf (" %s\n", _("The name or address you want to query"));
501 printf (" -s, --server=HOST\n"); 563 printf (" -s, --server=HOST\n");
502 printf (" %s\n", _("Optional DNS server you want to use for the lookup")); 564 printf (" %s\n", _("Optional DNS server you want to use for the lookup"));
503 printf (" -a, --expected-address=IP-ADDRESS|HOST\n"); 565 printf (" -a, --expected-address=IP-ADDRESS|CIDR|HOST\n");
504 printf (" %s\n", _("Optional IP-ADDRESS you expect the DNS server to return. HOST must end with")); 566 printf (" %s\n", _("Optional IP-ADDRESS/CIDR you expect the DNS server to return. HOST must end"));
505 printf (" %s\n", _("a dot (.). This option can be repeated multiple times (Returns OK if any")); 567 printf (" %s\n", _("with a dot (.). This option can be repeated multiple times (Returns OK if any"));
506 printf (" %s\n", _("value match). If multiple addresses are returned at once, you have to match")); 568 printf (" %s\n", _("value matches)."));
507 printf (" %s\n", _("the whole string of addresses separated with commas (sorted alphabetically)."));
508 printf (" -A, --expect-authority\n"); 569 printf (" -A, --expect-authority\n");
509 printf (" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup")); 570 printf (" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup"));
510 printf (" -w, --warning=seconds\n"); 571 printf (" -w, --warning=seconds\n");
511 printf (" %s\n", _("Return warning if elapsed time exceeds value. Default off")); 572 printf (" %s\n", _("Return warning if elapsed time exceeds value. Default off"));
512 printf (" -c, --critical=seconds\n"); 573 printf (" -c, --critical=seconds\n");
513 printf (" %s\n", _("Return critical if elapsed time exceeds value. Default off")); 574 printf (" %s\n", _("Return critical if elapsed time exceeds value. Default off"));
575 printf (" -L, --all\n");
576 printf (" %s\n", _("Return critical if the list of expected addresses does not match all addresses"));
577 printf (" %s\n", _("returned. Default off"));
514 578
515 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); 579 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
516 580
@@ -522,5 +586,5 @@ void
522print_usage (void) 586print_usage (void)
523{ 587{
524 printf ("%s\n", _("Usage:")); 588 printf ("%s\n", _("Usage:"));
525 printf ("%s -H host [-s server] [-a expected-address] [-A] [-t timeout] [-w warn] [-c crit]\n", progname); 589 printf ("%s -H host [-s server] [-a expected-address] [-A] [-t timeout] [-w warn] [-c crit] [-L]\n", progname);
526} 590}
diff --git a/plugins/check_fping.c b/plugins/check_fping.c
index da1ce1a..521d0fe 100644
--- a/plugins/check_fping.c
+++ b/plugins/check_fping.c
@@ -184,7 +184,7 @@ textscan (char *buf)
184 int status = STATE_UNKNOWN; 184 int status = STATE_UNKNOWN;
185 185
186 if (strstr (buf, "not found")) { 186 if (strstr (buf, "not found")) {
187 die (STATE_CRITICAL, _("FPING UNKNOW - %s not found\n"), server_name); 187 die (STATE_CRITICAL, _("FPING UNKNOWN - %s not found\n"), server_name);
188 188
189 } 189 }
190 else if (strstr (buf, "is unreachable") || strstr (buf, "Unreachable")) { 190 else if (strstr (buf, "is unreachable") || strstr (buf, "Unreachable")) {
diff --git a/plugins/check_hpjd.c b/plugins/check_hpjd.c
index f159f5a..6546556 100644
--- a/plugins/check_hpjd.c
+++ b/plugins/check_hpjd.c
@@ -67,6 +67,7 @@ void print_usage (void);
67char *community = NULL; 67char *community = NULL;
68char *address = NULL; 68char *address = NULL;
69char *port = NULL; 69char *port = NULL;
70int check_paper_out = 1;
70 71
71int 72int
72main (int argc, char **argv) 73main (int argc, char **argv)
@@ -240,7 +241,8 @@ main (int argc, char **argv)
240 strcpy (errmsg, _("Paper Jam")); 241 strcpy (errmsg, _("Paper Jam"));
241 } 242 }
242 else if (paper_out) { 243 else if (paper_out) {
243 result = STATE_WARNING; 244 if (check_paper_out)
245 result = STATE_WARNING;
244 strcpy (errmsg, _("Out of Paper")); 246 strcpy (errmsg, _("Out of Paper"));
245 } 247 }
246 else if (line_status == OFFLINE) { 248 else if (line_status == OFFLINE) {
@@ -325,7 +327,7 @@ process_arguments (int argc, char **argv)
325 327
326 328
327 while (1) { 329 while (1) {
328 c = getopt_long (argc, argv, "+hVH:C:p:", longopts, &option); 330 c = getopt_long (argc, argv, "+hVH:C:p:D", longopts, &option);
329 331
330 if (c == -1 || c == EOF || c == 1) 332 if (c == -1 || c == EOF || c == 1)
331 break; 333 break;
@@ -347,6 +349,8 @@ process_arguments (int argc, char **argv)
347 usage2 (_("Port must be a positive short integer"), optarg); 349 usage2 (_("Port must be a positive short integer"), optarg);
348 else 350 else
349 port = atoi(optarg); 351 port = atoi(optarg);
352 case 'D': /* disable paper out check*/
353 check_paper_out = 0;
350 break; 354 break;
351 case 'V': /* version */ 355 case 'V': /* version */
352 print_revision (progname, NP_VERSION); 356 print_revision (progname, NP_VERSION);
@@ -420,6 +424,8 @@ print_help (void)
420 printf (" %s", _("Specify the port to check ")); 424 printf (" %s", _("Specify the port to check "));
421 printf (_("(default=%s)"), DEFAULT_PORT); 425 printf (_("(default=%s)"), DEFAULT_PORT);
422 printf ("\n"); 426 printf ("\n");
427 printf (" %s\n", "-D");
428 printf (" %s", _("Disable paper check "));
423 429
424 printf (UT_SUPPORT); 430 printf (UT_SUPPORT);
425} 431}
@@ -430,5 +436,5 @@ void
430print_usage (void) 436print_usage (void)
431{ 437{
432 printf ("%s\n", _("Usage:")); 438 printf ("%s\n", _("Usage:"));
433 printf ("%s -H host [-C community] [-p port]\n", progname); 439 printf ("%s -H host [-C community] [-p port] [-D]\n", progname);
434} 440}
diff --git a/plugins/check_http.c b/plugins/check_http.c
index 2038f4a..34fb4f0 100644
--- a/plugins/check_http.c
+++ b/plugins/check_http.c
@@ -72,7 +72,7 @@ int maximum_age = -1;
72 72
73enum { 73enum {
74 REGS = 2, 74 REGS = 2,
75 MAX_RE_SIZE = 256 75 MAX_RE_SIZE = 1024
76}; 76};
77#include "regex.h" 77#include "regex.h"
78regex_t preg; 78regex_t preg;
@@ -91,10 +91,12 @@ struct timeval tv_temp;
91 91
92int specify_port = FALSE; 92int specify_port = FALSE;
93int server_port = HTTP_PORT; 93int server_port = HTTP_PORT;
94int virtual_port = 0;
94char server_port_text[6] = ""; 95char server_port_text[6] = "";
95char server_type[6] = "http"; 96char server_type[6] = "http";
96char *server_address; 97char *server_address;
97char *host_name; 98char *host_name;
99int host_name_length;
98char *server_url; 100char *server_url;
99char *user_agent; 101char *user_agent;
100int server_url_length; 102int server_url_length;
@@ -118,12 +120,14 @@ int use_ssl = FALSE;
118int use_sni = FALSE; 120int use_sni = FALSE;
119int verbose = FALSE; 121int verbose = FALSE;
120int show_extended_perfdata = FALSE; 122int show_extended_perfdata = FALSE;
123int show_body = FALSE;
121int sd; 124int sd;
122int min_page_len = 0; 125int min_page_len = 0;
123int max_page_len = 0; 126int max_page_len = 0;
124int redir_depth = 0; 127int redir_depth = 0;
125int max_depth = 15; 128int max_depth = 15;
126char *http_method; 129char *http_method;
130char *http_method_proxy;
127char *http_post_data; 131char *http_post_data;
128char *http_content_type; 132char *http_content_type;
129char buffer[MAX_INPUT_BUFFER]; 133char buffer[MAX_INPUT_BUFFER];
@@ -237,6 +241,7 @@ process_arguments (int argc, char **argv)
237 {"use-ipv4", no_argument, 0, '4'}, 241 {"use-ipv4", no_argument, 0, '4'},
238 {"use-ipv6", no_argument, 0, '6'}, 242 {"use-ipv6", no_argument, 0, '6'},
239 {"extended-perfdata", no_argument, 0, 'E'}, 243 {"extended-perfdata", no_argument, 0, 'E'},
244 {"show-body", no_argument, 0, 'B'},
240 {0, 0, 0, 0} 245 {0, 0, 0, 0}
241 }; 246 };
242 247
@@ -257,7 +262,7 @@ process_arguments (int argc, char **argv)
257 } 262 }
258 263
259 while (1) { 264 while (1) {
260 c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:nlLS::m:M:NE", longopts, &option); 265 c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:nlLS::m:M:NEB", longopts, &option);
261 if (c == -1 || c == EOF) 266 if (c == -1 || c == EOF)
262 break; 267 break;
263 268
@@ -391,11 +396,25 @@ process_arguments (int argc, char **argv)
391 case 'H': /* Host Name (virtual host) */ 396 case 'H': /* Host Name (virtual host) */
392 host_name = strdup (optarg); 397 host_name = strdup (optarg);
393 if (host_name[0] == '[') { 398 if (host_name[0] == '[') {
394 if ((p = strstr (host_name, "]:")) != NULL) /* [IPv6]:port */ 399 if ((p = strstr (host_name, "]:")) != NULL) { /* [IPv6]:port */
395 server_port = atoi (p + 2); 400 virtual_port = atoi (p + 2);
401 /* cut off the port */
402 host_name_length = strlen (host_name) - strlen (p) - 1;
403 free (host_name);
404 host_name = strndup (optarg, host_name_length);
405 if (specify_port == FALSE)
406 server_port = virtual_port;
407 }
396 } else if ((p = strchr (host_name, ':')) != NULL 408 } else if ((p = strchr (host_name, ':')) != NULL
397 && strchr (++p, ':') == NULL) /* IPv4:port or host:port */ 409 && strchr (++p, ':') == NULL) { /* IPv4:port or host:port */
398 server_port = atoi (p); 410 virtual_port = atoi (p);
411 /* cut off the port */
412 host_name_length = strlen (host_name) - strlen (p) - 1;
413 free (host_name);
414 host_name = strndup (optarg, host_name_length);
415 if (specify_port == FALSE)
416 server_port = virtual_port;
417 }
399 break; 418 break;
400 case 'I': /* Server IP-address */ 419 case 'I': /* Server IP-address */
401 server_address = strdup (optarg); 420 server_address = strdup (optarg);
@@ -430,6 +449,12 @@ process_arguments (int argc, char **argv)
430 if (http_method) 449 if (http_method)
431 free(http_method); 450 free(http_method);
432 http_method = strdup (optarg); 451 http_method = strdup (optarg);
452 char *tmp;
453 if ((tmp = strstr(http_method, ":")) > 0) {
454 tmp[0] = '\0';
455 http_method = http_method;
456 http_method_proxy = ++tmp;
457 }
433 break; 458 break;
434 case 'd': /* string or substring */ 459 case 'd': /* string or substring */
435 strncpy (header_expect, optarg, MAX_INPUT_BUFFER - 1); 460 strncpy (header_expect, optarg, MAX_INPUT_BUFFER - 1);
@@ -524,6 +549,9 @@ process_arguments (int argc, char **argv)
524 case 'E': /* show extended perfdata */ 549 case 'E': /* show extended perfdata */
525 show_extended_perfdata = TRUE; 550 show_extended_perfdata = TRUE;
526 break; 551 break;
552 case 'B': /* print body content after status line */
553 show_body = TRUE;
554 break;
527 } 555 }
528 } 556 }
529 557
@@ -550,9 +578,15 @@ process_arguments (int argc, char **argv)
550 if (http_method == NULL) 578 if (http_method == NULL)
551 http_method = strdup ("GET"); 579 http_method = strdup ("GET");
552 580
553 if (client_cert && !client_privkey) 581 if (http_method_proxy == NULL)
582 http_method_proxy = strdup ("GET");
583
584 if (client_cert && !client_privkey)
554 usage4 (_("If you use a client certificate you must also specify a private key file")); 585 usage4 (_("If you use a client certificate you must also specify a private key file"));
555 586
587 if (virtual_port == 0)
588 virtual_port = server_port;
589
556 return TRUE; 590 return TRUE;
557} 591}
558 592
@@ -897,6 +931,21 @@ check_http (void)
897 931
898 if (verbose) printf ("Entering CONNECT tunnel mode with proxy %s:%d to dst %s:%d\n", server_address, server_port, host_name, HTTPS_PORT); 932 if (verbose) printf ("Entering CONNECT tunnel mode with proxy %s:%d to dst %s:%d\n", server_address, server_port, host_name, HTTPS_PORT);
899 asprintf (&buf, "%s %s:%d HTTP/1.1\r\n%s\r\n", http_method, host_name, HTTPS_PORT, user_agent); 933 asprintf (&buf, "%s %s:%d HTTP/1.1\r\n%s\r\n", http_method, host_name, HTTPS_PORT, user_agent);
934 if (strlen(proxy_auth)) {
935 base64_encode_alloc (proxy_auth, strlen (proxy_auth), &auth);
936 xasprintf (&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth);
937 }
938 /* optionally send any other header tag */
939 if (http_opt_headers_count) {
940 for (i = 0; i < http_opt_headers_count ; i++) {
941 if (force_host_header != http_opt_headers[i]) {
942 xasprintf (&buf, "%s%s\r\n", buf, http_opt_headers[i]);
943 }
944 }
945 /* This cannot be free'd here because a redirection will then try to access this and segfault */
946 /* Covered in a testcase in tests/check_http.t */
947 /* free(http_opt_headers); */
948 }
900 asprintf (&buf, "%sProxy-Connection: keep-alive\r\n", buf); 949 asprintf (&buf, "%sProxy-Connection: keep-alive\r\n", buf);
901 asprintf (&buf, "%sHost: %s\r\n", buf, host_name); 950 asprintf (&buf, "%sHost: %s\r\n", buf, host_name);
902 /* we finished our request, send empty line with CRLF */ 951 /* we finished our request, send empty line with CRLF */
@@ -922,8 +971,8 @@ check_http (void)
922 elapsed_time_ssl = (double)microsec_ssl / 1.0e6; 971 elapsed_time_ssl = (double)microsec_ssl / 1.0e6;
923 if (check_cert == TRUE) { 972 if (check_cert == TRUE) {
924 result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); 973 result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
925 np_net_ssl_cleanup();
926 if (sd) close(sd); 974 if (sd) close(sd);
975 np_net_ssl_cleanup();
927 return result; 976 return result;
928 } 977 }
929 } 978 }
@@ -931,7 +980,7 @@ check_http (void)
931 980
932 if ( server_address != NULL && strcmp(http_method, "CONNECT") == 0 981 if ( server_address != NULL && strcmp(http_method, "CONNECT") == 0
933 && host_name != NULL && use_ssl == TRUE) 982 && host_name != NULL && use_ssl == TRUE)
934 asprintf (&buf, "%s %s %s\r\n%s\r\n", "GET", server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); 983 asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method_proxy, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent);
935 else 984 else
936 asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent); 985 asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent);
937 986
@@ -958,13 +1007,13 @@ check_http (void)
958 * 14.23). Some server applications/configurations cause trouble if the 1007 * 14.23). Some server applications/configurations cause trouble if the
959 * (default) port is explicitly specified in the "Host:" header line. 1008 * (default) port is explicitly specified in the "Host:" header line.
960 */ 1009 */
961 if ((use_ssl == FALSE && server_port == HTTP_PORT) || 1010 if ((use_ssl == FALSE && virtual_port == HTTP_PORT) ||
962 (use_ssl == TRUE && server_port == HTTPS_PORT) || 1011 (use_ssl == TRUE && virtual_port == HTTPS_PORT) ||
963 (server_address != NULL && strcmp(http_method, "CONNECT") == 0 1012 (server_address != NULL && strcmp(http_method, "CONNECT") == 0
964 && host_name != NULL && use_ssl == TRUE)) 1013 && host_name != NULL && use_ssl == TRUE))
965 xasprintf (&buf, "%sHost: %s\r\n", buf, host_name); 1014 xasprintf (&buf, "%sHost: %s\r\n", buf, host_name);
966 else 1015 else
967 xasprintf (&buf, "%sHost: %s:%d\r\n", buf, host_name, server_port); 1016 xasprintf (&buf, "%sHost: %s:%d\r\n", buf, host_name, virtual_port);
968 } 1017 }
969 } 1018 }
970 1019
@@ -1022,6 +1071,10 @@ check_http (void)
1022 microsec_firstbyte = deltime (tv_temp); 1071 microsec_firstbyte = deltime (tv_temp);
1023 elapsed_time_firstbyte = (double)microsec_firstbyte / 1.0e6; 1072 elapsed_time_firstbyte = (double)microsec_firstbyte / 1.0e6;
1024 } 1073 }
1074 while (pos = memchr(buffer, '\0', i)) {
1075 /* replace nul character with a blank */
1076 *pos = ' ';
1077 }
1025 buffer[i] = '\0'; 1078 buffer[i] = '\0';
1026 xasprintf (&full_page_new, "%s%s", full_page, buffer); 1079 xasprintf (&full_page_new, "%s%s", full_page, buffer);
1027 free (full_page); 1080 free (full_page);
@@ -1063,10 +1116,10 @@ check_http (void)
1063 die (STATE_CRITICAL, _("HTTP CRITICAL - No data received from host\n")); 1116 die (STATE_CRITICAL, _("HTTP CRITICAL - No data received from host\n"));
1064 1117
1065 /* close the connection */ 1118 /* close the connection */
1119 if (sd) close(sd);
1066#ifdef HAVE_SSL 1120#ifdef HAVE_SSL
1067 np_net_ssl_cleanup(); 1121 np_net_ssl_cleanup();
1068#endif 1122#endif
1069 if (sd) close(sd);
1070 1123
1071 /* Save check time */ 1124 /* Save check time */
1072 microsec = deltime (tv); 1125 microsec = deltime (tv);
@@ -1117,6 +1170,8 @@ check_http (void)
1117 xasprintf (&msg, 1170 xasprintf (&msg,
1118 _("Invalid HTTP response received from host on port %d: %s\n"), 1171 _("Invalid HTTP response received from host on port %d: %s\n"),
1119 server_port, status_line); 1172 server_port, status_line);
1173 if (show_body)
1174 xasprintf (&msg, _("%s\n%s"), msg, page);
1120 die (STATE_CRITICAL, "HTTP CRITICAL - %s", msg); 1175 die (STATE_CRITICAL, "HTTP CRITICAL - %s", msg);
1121 } 1176 }
1122 1177
@@ -1267,6 +1322,9 @@ check_http (void)
1267 perfd_time (elapsed_time), 1322 perfd_time (elapsed_time),
1268 perfd_size (page_len)); 1323 perfd_size (page_len));
1269 1324
1325 if (show_body)
1326 xasprintf (&msg, _("%s\n%s"), msg, page);
1327
1270 result = max_state_alt(get_status(elapsed_time, thlds), result); 1328 result = max_state_alt(get_status(elapsed_time, thlds), result);
1271 1329
1272 die (result, "HTTP %s: %s\n", state_text(result), msg); 1330 die (result, "HTTP %s: %s\n", state_text(result), msg);
@@ -1395,8 +1453,8 @@ redir (char *pos, char *status_line)
1395 !strncmp(server_address, addr, MAX_IPV4_HOSTLENGTH) && 1453 !strncmp(server_address, addr, MAX_IPV4_HOSTLENGTH) &&
1396 (host_name && !strncmp(host_name, addr, MAX_IPV4_HOSTLENGTH)) && 1454 (host_name && !strncmp(host_name, addr, MAX_IPV4_HOSTLENGTH)) &&
1397 !strcmp(server_url, url)) 1455 !strcmp(server_url, url))
1398 die (STATE_WARNING, 1456 die (STATE_CRITICAL,
1399 _("HTTP WARNING - redirection creates an infinite loop - %s://%s:%d%s%s\n"), 1457 _("HTTP CRITICAL - redirection creates an infinite loop - %s://%s:%d%s%s\n"),
1400 type, addr, i, url, (display_html ? "</A>" : "")); 1458 type, addr, i, url, (display_html ? "</A>" : ""));
1401 1459
1402 strcpy (server_type, type); 1460 strcpy (server_type, type);
@@ -1421,6 +1479,9 @@ redir (char *pos, char *status_line)
1421 MAX_PORT, server_type, server_address, server_port, server_url, 1479 MAX_PORT, server_type, server_address, server_port, server_url,
1422 display_html ? "</A>" : ""); 1480 display_html ? "</A>" : "");
1423 1481
1482 /* reset virtual port */
1483 virtual_port = server_port;
1484
1424 if (verbose) 1485 if (verbose)
1425 printf (_("Redirection to %s://%s:%d%s\n"), server_type, 1486 printf (_("Redirection to %s://%s:%d%s\n"), server_type,
1426 host_name ? host_name : server_address, server_port, server_url); 1487 host_name ? host_name : server_address, server_port, server_url);
@@ -1453,32 +1514,32 @@ char *perfd_time (double elapsed_time)
1453 return fperfdata ("time", elapsed_time, "s", 1514 return fperfdata ("time", elapsed_time, "s",
1454 thlds->warning?TRUE:FALSE, thlds->warning?thlds->warning->end:0, 1515 thlds->warning?TRUE:FALSE, thlds->warning?thlds->warning->end:0,
1455 thlds->critical?TRUE:FALSE, thlds->critical?thlds->critical->end:0, 1516 thlds->critical?TRUE:FALSE, thlds->critical?thlds->critical->end:0,
1456 TRUE, 0, FALSE, 0); 1517 TRUE, 0, TRUE, socket_timeout);
1457} 1518}
1458 1519
1459char *perfd_time_connect (double elapsed_time_connect) 1520char *perfd_time_connect (double elapsed_time_connect)
1460{ 1521{
1461 return fperfdata ("time_connect", elapsed_time_connect, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0); 1522 return fperfdata ("time_connect", elapsed_time_connect, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1462} 1523}
1463 1524
1464char *perfd_time_ssl (double elapsed_time_ssl) 1525char *perfd_time_ssl (double elapsed_time_ssl)
1465{ 1526{
1466 return fperfdata ("time_ssl", elapsed_time_ssl, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0); 1527 return fperfdata ("time_ssl", elapsed_time_ssl, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1467} 1528}
1468 1529
1469char *perfd_time_headers (double elapsed_time_headers) 1530char *perfd_time_headers (double elapsed_time_headers)
1470{ 1531{
1471 return fperfdata ("time_headers", elapsed_time_headers, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0); 1532 return fperfdata ("time_headers", elapsed_time_headers, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1472} 1533}
1473 1534
1474char *perfd_time_firstbyte (double elapsed_time_firstbyte) 1535char *perfd_time_firstbyte (double elapsed_time_firstbyte)
1475{ 1536{
1476 return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0); 1537 return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1477} 1538}
1478 1539
1479char *perfd_time_transfer (double elapsed_time_transfer) 1540char *perfd_time_transfer (double elapsed_time_transfer)
1480{ 1541{
1481 return fperfdata ("time_transfer", elapsed_time_transfer, "s", FALSE, 0, FALSE, 0, FALSE, 0, FALSE, 0); 1542 return fperfdata ("time_transfer", elapsed_time_transfer, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout);
1482} 1543}
1483 1544
1484char *perfd_size (int page_len) 1545char *perfd_size (int page_len)
@@ -1506,6 +1567,10 @@ print_help (void)
1506 1567
1507 print_usage (); 1568 print_usage ();
1508 1569
1570#ifdef HAVE_SSL
1571 printf (_("In the first form, make an HTTP request."));
1572 printf (_("In the second form, connect to the server and check the TLS certificate."));
1573#endif
1509 printf (_("NOTE: One or both of -H and -I must be specified")); 1574 printf (_("NOTE: One or both of -H and -I must be specified"));
1510 1575
1511 printf ("\n"); 1576 printf ("\n");
@@ -1555,7 +1620,7 @@ print_help (void)
1555 printf (" %s\n", _("URL to GET or POST (default: /)")); 1620 printf (" %s\n", _("URL to GET or POST (default: /)"));
1556 printf (" %s\n", "-P, --post=STRING"); 1621 printf (" %s\n", "-P, --post=STRING");
1557 printf (" %s\n", _("URL encoded http POST data")); 1622 printf (" %s\n", _("URL encoded http POST data"));
1558 printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)"); 1623 printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT, CONNECT:POST)");
1559 printf (" %s\n", _("Set HTTP method.")); 1624 printf (" %s\n", _("Set HTTP method."));
1560 printf (" %s\n", "-N, --no-body"); 1625 printf (" %s\n", "-N, --no-body");
1561 printf (" %s\n", _("Don't wait for document body: stop reading after headers.")); 1626 printf (" %s\n", _("Don't wait for document body: stop reading after headers."));
@@ -1585,6 +1650,8 @@ print_help (void)
1585 printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers")); 1650 printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers"));
1586 printf (" %s\n", "-E, --extended-perfdata"); 1651 printf (" %s\n", "-E, --extended-perfdata");
1587 printf (" %s\n", _("Print additional performance data")); 1652 printf (" %s\n", _("Print additional performance data"));
1653 printf (" %s\n", "-B, --show-body");
1654 printf (" %s\n", _("Print body content below status line"));
1588 printf (" %s\n", "-L, --link"); 1655 printf (" %s\n", "-L, --link");
1589 printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)")); 1656 printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)"));
1590 printf (" %s\n", "-f, --onredirect=<ok|warning|critical|follow|sticky|stickyport>"); 1657 printf (" %s\n", "-f, --onredirect=<ok|warning|critical|follow|sticky|stickyport>");
@@ -1603,7 +1670,7 @@ print_help (void)
1603 printf ("%s\n", _("Notes:")); 1670 printf ("%s\n", _("Notes:"));
1604 printf (" %s\n", _("This plugin will attempt to open an HTTP connection with the host.")); 1671 printf (" %s\n", _("This plugin will attempt to open an HTTP connection with the host."));
1605 printf (" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL")); 1672 printf (" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL"));
1606 printf (" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect reponse")); 1673 printf (" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect response"));
1607 printf (" %s\n", _("messages from the host result in STATE_WARNING return values. If you are")); 1674 printf (" %s\n", _("messages from the host result in STATE_WARNING return values. If you are"));
1608 printf (" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN")); 1675 printf (" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN"));
1609 printf (" %s\n", _("(fully qualified domain name) as the [host_name] argument.")); 1676 printf (" %s\n", _("(fully qualified domain name) as the [host_name] argument."));
@@ -1642,7 +1709,8 @@ print_help (void)
1642 printf (" %s\n", _("all these options are needed: -I <proxy> -p <proxy-port> -u <check-url> -S(sl) -j CONNECT -H <webserver>")); 1709 printf (" %s\n", _("all these options are needed: -I <proxy> -p <proxy-port> -u <check-url> -S(sl) -j CONNECT -H <webserver>"));
1643 printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); 1710 printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds"));
1644 printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); 1711 printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,"));
1645 printf (" %s\n", _("a STATE_CRITICAL will be returned.")); 1712 printf (" %s\n", _("a STATE_CRITICAL will be returned. By adding a colon to the method you can set the method used"));
1713 printf (" %s\n", _("inside the proxied connection: -j CONNECT:POST"));
1646 1714
1647#endif 1715#endif
1648 1716
@@ -1662,6 +1730,8 @@ print_usage (void)
1662 printf (" [-b proxy_auth] [-f <ok|warning|critcal|follow|sticky|stickyport>]\n"); 1730 printf (" [-b proxy_auth] [-f <ok|warning|critcal|follow|sticky|stickyport>]\n");
1663 printf (" [-e <expect>] [-d string] [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n"); 1731 printf (" [-e <expect>] [-d string] [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n");
1664 printf (" [-P string] [-m <min_pg_size>:<max_pg_size>] [-4|-6] [-N] [-M <age>]\n"); 1732 printf (" [-P string] [-m <min_pg_size>:<max_pg_size>] [-4|-6] [-N] [-M <age>]\n");
1665 printf (" [-A string] [-k string] [-S <version>] [--sni] [-C <warn_age>[,<crit_age>]]\n"); 1733 printf (" [-A string] [-k string] [-S <version>] [--sni]\n");
1666 printf (" [-T <content-type>] [-j method]\n"); 1734 printf (" [-T <content-type>] [-j method]\n");
1735 printf (" %s -H <vhost> | -I <IP-address> -C <warn_age>[,<crit_age>]\n",progname);
1736 printf (" [-p <port>] [-t <timeout>] [-4|-6] [--sni]\n");
1667} 1737}
diff --git a/plugins/check_ide_smart.c b/plugins/check_ide_smart.c
index 8d540ca..0160d98 100644
--- a/plugins/check_ide_smart.c
+++ b/plugins/check_ide_smart.c
@@ -166,7 +166,6 @@ enum SmartCommand
166 166
167char *get_offline_text (int); 167char *get_offline_text (int);
168int smart_read_values (int, values_t *); 168int smart_read_values (int, values_t *);
169int values_not_passed (values_t *, thresholds_t *);
170int nagios (values_t *, thresholds_t *); 169int nagios (values_t *, thresholds_t *);
171void print_value (value_t *, threshold_t *); 170void print_value (value_t *, threshold_t *);
172void print_values (values_t *, thresholds_t *); 171void print_values (values_t *, thresholds_t *);
@@ -284,7 +283,7 @@ get_offline_text (int status)
284 return offline_status_text[i].text; 283 return offline_status_text[i].text;
285 } 284 }
286 } 285 }
287 return "UNKNOW"; 286 return "UNKNOWN";
288} 287}
289 288
290 289
@@ -340,31 +339,6 @@ smart_read_values (int fd, values_t * values)
340 339
341 340
342int 341int
343values_not_passed (values_t * p, thresholds_t * t)
344{
345 value_t * value = p->values;
346 threshold_t * threshold = t->thresholds;
347 int failed = 0;
348 int passed = 0;
349 int i;
350 for (i = 0; i < NR_ATTRIBUTES; i++) {
351 if (value->id && threshold->id && value->id == threshold->id) {
352 if (value->value < threshold->threshold) {
353 ++failed;
354 }
355 else {
356 ++passed;
357 }
358 }
359 ++value;
360 ++threshold;
361 }
362 return (passed ? -failed : 2);
363}
364
365
366
367int
368nagios (values_t * p, thresholds_t * t) 342nagios (values_t * p, thresholds_t * t)
369{ 343{
370 value_t * value = p->values; 344 value_t * value = p->values;
diff --git a/plugins/check_ldap.c b/plugins/check_ldap.c
index e70d6a5..bc7bd44 100644
--- a/plugins/check_ldap.c
+++ b/plugins/check_ldap.c
@@ -237,7 +237,7 @@ main (int argc, char *argv[])
237 if(entries_thresholds != NULL) { 237 if(entries_thresholds != NULL) {
238 if (verbose) { 238 if (verbose) {
239 printf ("entries found: %d\n", num_entries); 239 printf ("entries found: %d\n", num_entries);
240 print_thresholds("entry threasholds", entries_thresholds); 240 print_thresholds("entry thresholds", entries_thresholds);
241 } 241 }
242 status_entries = get_status(num_entries, entries_thresholds); 242 status_entries = get_status(num_entries, entries_thresholds);
243 if (status_entries == STATE_CRITICAL) { 243 if (status_entries == STATE_CRITICAL) {
@@ -483,7 +483,7 @@ print_help (void)
483 483
484 printf (" %s\n", "-W [--warn-entries]"); 484 printf (" %s\n", "-W [--warn-entries]");
485 printf (" %s\n", _("Number of found entries to result in warning status")); 485 printf (" %s\n", _("Number of found entries to result in warning status"));
486 printf (" %s\n", "-W [--crit-entries]"); 486 printf (" %s\n", "-C [--crit-entries]");
487 printf (" %s\n", _("Number of found entries to result in critical status")); 487 printf (" %s\n", _("Number of found entries to result in critical status"));
488 488
489 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); 489 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
diff --git a/plugins/check_load.c b/plugins/check_load.c
index a96435f..bf7b94b 100644
--- a/plugins/check_load.c
+++ b/plugins/check_load.c
@@ -33,6 +33,7 @@ const char *copyright = "1999-2007";
33const char *email = "devel@monitoring-plugins.org"; 33const char *email = "devel@monitoring-plugins.org";
34 34
35#include "common.h" 35#include "common.h"
36#include "runcmd.h"
36#include "utils.h" 37#include "utils.h"
37#include "popen.h" 38#include "popen.h"
38 39
@@ -52,6 +53,9 @@ static int process_arguments (int argc, char **argv);
52static int validate_arguments (void); 53static int validate_arguments (void);
53void print_help (void); 54void print_help (void);
54void print_usage (void); 55void print_usage (void);
56static int print_top_consuming_processes();
57
58static int n_procs_to_show = 0;
55 59
56/* strictly for pretty-print usage in loops */ 60/* strictly for pretty-print usage in loops */
57static const int nums[3] = { 1, 5, 15 }; 61static const int nums[3] = { 1, 5, 15 };
@@ -160,7 +164,7 @@ main (int argc, char **argv)
160 sscanf (input_buffer, "%*[^l]load averages: %lf, %lf, %lf", &la1, &la5, &la15); 164 sscanf (input_buffer, "%*[^l]load averages: %lf, %lf, %lf", &la1, &la5, &la15);
161 } 165 }
162 else { 166 else {
163 printf (_("could not parse load from uptime: %s\n"), result, PATH_TO_UPTIME); 167 printf (_("could not parse load from uptime %s: %s\n"), PATH_TO_UPTIME, result);
164 return STATE_UNKNOWN; 168 return STATE_UNKNOWN;
165 } 169 }
166 170
@@ -210,6 +214,9 @@ main (int argc, char **argv)
210 printf("load%d=%.3f;%.3f;%.3f;0; ", nums[i], la[i], wload[i], cload[i]); 214 printf("load%d=%.3f;%.3f;%.3f;0; ", nums[i], la[i], wload[i], cload[i]);
211 215
212 putchar('\n'); 216 putchar('\n');
217 if (n_procs_to_show > 0) {
218 print_top_consuming_processes();
219 }
213 return result; 220 return result;
214} 221}
215 222
@@ -227,6 +234,7 @@ process_arguments (int argc, char **argv)
227 {"percpu", no_argument, 0, 'r'}, 234 {"percpu", no_argument, 0, 'r'},
228 {"version", no_argument, 0, 'V'}, 235 {"version", no_argument, 0, 'V'},
229 {"help", no_argument, 0, 'h'}, 236 {"help", no_argument, 0, 'h'},
237 {"procs-to-show", required_argument, 0, 'n'},
230 {0, 0, 0, 0} 238 {0, 0, 0, 0}
231 }; 239 };
232 240
@@ -234,7 +242,7 @@ process_arguments (int argc, char **argv)
234 return ERROR; 242 return ERROR;
235 243
236 while (1) { 244 while (1) {
237 c = getopt_long (argc, argv, "Vhrc:w:", longopts, &option); 245 c = getopt_long (argc, argv, "Vhrc:w:n:", longopts, &option);
238 246
239 if (c == -1 || c == EOF) 247 if (c == -1 || c == EOF)
240 break; 248 break;
@@ -255,6 +263,9 @@ process_arguments (int argc, char **argv)
255 case 'h': /* help */ 263 case 'h': /* help */
256 print_help (); 264 print_help ();
257 exit (STATE_UNKNOWN); 265 exit (STATE_UNKNOWN);
266 case 'n':
267 n_procs_to_show = atoi(optarg);
268 break;
258 case '?': /* help */ 269 case '?': /* help */
259 usage5 (); 270 usage5 ();
260 } 271 }
@@ -324,6 +335,9 @@ print_help (void)
324 printf (" %s\n", _("the load average format is the same used by \"uptime\" and \"w\"")); 335 printf (" %s\n", _("the load average format is the same used by \"uptime\" and \"w\""));
325 printf (" %s\n", "-r, --percpu"); 336 printf (" %s\n", "-r, --percpu");
326 printf (" %s\n", _("Divide the load averages by the number of CPUs (when possible)")); 337 printf (" %s\n", _("Divide the load averages by the number of CPUs (when possible)"));
338 printf (" %s\n", "-n, --procs-to-show=NUMBER_OF_PROCS");
339 printf (" %s\n", _("Number of processes to show when printing the top consuming processes."));
340 printf (" %s\n", _("NUMBER_OF_PROCS=0 disables this feature. Default value is 0"));
327 341
328 printf (UT_SUPPORT); 342 printf (UT_SUPPORT);
329} 343}
@@ -332,5 +346,48 @@ void
332print_usage (void) 346print_usage (void)
333{ 347{
334 printf ("%s\n", _("Usage:")); 348 printf ("%s\n", _("Usage:"));
335 printf ("%s [-r] -w WLOAD1,WLOAD5,WLOAD15 -c CLOAD1,CLOAD5,CLOAD15\n", progname); 349 printf ("%s [-r] -w WLOAD1,WLOAD5,WLOAD15 -c CLOAD1,CLOAD5,CLOAD15 [-n NUMBER_OF_PROCS]\n", progname);
350}
351
352#ifdef PS_USES_PROCPCPU
353int cmpstringp(const void *p1, const void *p2) {
354 int procuid = 0;
355 int procpid = 0;
356 int procppid = 0;
357 int procvsz = 0;
358 int procrss = 0;
359 float procpcpu = 0;
360 char procstat[8];
361#ifdef PS_USES_PROCETIME
362 char procetime[MAX_INPUT_BUFFER];
363#endif /* PS_USES_PROCETIME */
364 char procprog[MAX_INPUT_BUFFER];
365 int pos;
366 sscanf (* (char * const *) p1, PS_FORMAT, PS_VARLIST);
367 float procpcpu1 = procpcpu;
368 sscanf (* (char * const *) p2, PS_FORMAT, PS_VARLIST);
369 return procpcpu1 < procpcpu;
370}
371#endif /* PS_USES_PROCPCPU */
372
373static int print_top_consuming_processes() {
374 int i = 0;
375 struct output chld_out, chld_err;
376 if(np_runcmd(PS_COMMAND, &chld_out, &chld_err, 0) != 0){
377 fprintf(stderr, _("'%s' exited with non-zero status.\n"), PS_COMMAND);
378 return STATE_UNKNOWN;
379 }
380 if (chld_out.lines < 2) {
381 fprintf(stderr, _("some error occurred getting procs list.\n"));
382 return STATE_UNKNOWN;
383 }
384#ifdef PS_USES_PROCPCPU
385 qsort(chld_out.line + 1, chld_out.lines - 1, sizeof(char*), cmpstringp);
386#endif /* PS_USES_PROCPCPU */
387 int lines_to_show = chld_out.lines < (n_procs_to_show + 1)
388 ? chld_out.lines : n_procs_to_show + 1;
389 for (i = 0; i < lines_to_show; i += 1) {
390 printf("%s\n", chld_out.line[i]);
391 }
392 return OK;
336} 393}
diff --git a/plugins/check_mysql.c b/plugins/check_mysql.c
index 5773afd..0cba50e 100644
--- a/plugins/check_mysql.c
+++ b/plugins/check_mysql.c
@@ -379,6 +379,9 @@ process_arguments (int argc, char **argv)
379 if (is_host (optarg)) { 379 if (is_host (optarg)) {
380 db_host = optarg; 380 db_host = optarg;
381 } 381 }
382 else if (*optarg == '/') {
383 db_socket = optarg;
384 }
382 else { 385 else {
383 usage2 (_("Invalid hostname/address"), optarg); 386 usage2 (_("Invalid hostname/address"), optarg);
384 } 387 }
diff --git a/plugins/check_mysql_query.c b/plugins/check_mysql_query.c
index 49a14dd..ac2fb15 100644
--- a/plugins/check_mysql_query.c
+++ b/plugins/check_mysql_query.c
@@ -136,18 +136,18 @@ main (int argc, char **argv)
136 die (STATE_CRITICAL, "QUERY %s: Fetch row error - %s\n", _("CRITICAL"), error); 136 die (STATE_CRITICAL, "QUERY %s: Fetch row error - %s\n", _("CRITICAL"), error);
137 } 137 }
138 138
139 /* free the result */
140 mysql_free_result (res);
141
142 /* close the connection */
143 mysql_close (&mysql);
144
145 if (! is_numeric(row[0])) { 139 if (! is_numeric(row[0])) {
146 die (STATE_CRITICAL, "QUERY %s: %s - '%s'\n", _("CRITICAL"), _("Is not a numeric"), row[0]); 140 die (STATE_CRITICAL, "QUERY %s: %s - '%s'\n", _("CRITICAL"), _("Is not a numeric"), row[0]);
147 } 141 }
148 142
149 value = strtod(row[0], NULL); 143 value = strtod(row[0], NULL);
150 144
145 /* free the result */
146 mysql_free_result (res);
147
148 /* close the connection */
149 mysql_close (&mysql);
150
151 if (verbose >= 3) 151 if (verbose >= 3)
152 printf("mysql result: %f\n", value); 152 printf("mysql result: %f\n", value);
153 153
diff --git a/plugins/check_ntp.c b/plugins/check_ntp.c
index 75efc28..914b40c 100644
--- a/plugins/check_ntp.c
+++ b/plugins/check_ntp.c
@@ -297,7 +297,7 @@ void setup_request(ntp_message *p){
297 * this is done by filtering servers based on stratum, dispersion, and 297 * this is done by filtering servers based on stratum, dispersion, and
298 * finally round-trip delay. */ 298 * finally round-trip delay. */
299int best_offset_server(const ntp_server_results *slist, int nservers){ 299int best_offset_server(const ntp_server_results *slist, int nservers){
300 int i=0, cserver=0, best_server=-1; 300 int cserver=0, best_server=-1;
301 301
302 /* for each server */ 302 /* for each server */
303 for(cserver=0; cserver<nservers; cserver++){ 303 for(cserver=0; cserver<nservers; cserver++){
@@ -356,7 +356,7 @@ int best_offset_server(const ntp_server_results *slist, int nservers){
356 * we have to do it in a way that our lazy macros don't handle currently :( */ 356 * we have to do it in a way that our lazy macros don't handle currently :( */
357double offset_request(const char *host, int *status){ 357double offset_request(const char *host, int *status){
358 int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0; 358 int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0;
359 int servers_completed=0, one_written=0, one_read=0, servers_readable=0, best_index=-1; 359 int servers_completed=0, one_read=0, servers_readable=0, best_index=-1;
360 time_t now_time=0, start_ts=0; 360 time_t now_time=0, start_ts=0;
361 ntp_message *req=NULL; 361 ntp_message *req=NULL;
362 double avg_offset=0.; 362 double avg_offset=0.;
@@ -421,7 +421,6 @@ double offset_request(const char *host, int *status){
421 * been touched in the past second or so and is still lacking 421 * been touched in the past second or so and is still lacking
422 * some responses. for each of these servers, send a new request, 422 * some responses. for each of these servers, send a new request,
423 * and update the "waiting" timestamp with the current time. */ 423 * and update the "waiting" timestamp with the current time. */
424 one_written=0;
425 now_time=time(NULL); 424 now_time=time(NULL);
426 425
427 for(i=0; i<num_hosts; i++){ 426 for(i=0; i<num_hosts; i++){
@@ -431,7 +430,6 @@ double offset_request(const char *host, int *status){
431 setup_request(&req[i]); 430 setup_request(&req[i]);
432 write(socklist[i], &req[i], sizeof(ntp_message)); 431 write(socklist[i], &req[i], sizeof(ntp_message));
433 servers[i].waiting=now_time; 432 servers[i].waiting=now_time;
434 one_written=1;
435 break; 433 break;
436 } 434 }
437 } 435 }
@@ -550,7 +548,7 @@ double jitter_request(const char *host, int *status){
550 DBG(print_ntp_control_message(&req)); 548 DBG(print_ntp_control_message(&req));
551 /* Attempt to read the largest size packet possible */ 549 /* Attempt to read the largest size packet possible */
552 req.count=htons(MAX_CM_SIZE); 550 req.count=htons(MAX_CM_SIZE);
553 DBG(printf("recieving READSTAT response")) 551 DBG(printf("receiving READSTAT response"))
554 read(conn, &req, SIZEOF_NTPCM(req)); 552 read(conn, &req, SIZEOF_NTPCM(req));
555 DBG(print_ntp_control_message(&req)); 553 DBG(print_ntp_control_message(&req));
556 /* Each peer identifier is 4 bytes in the data section, which 554 /* Each peer identifier is 4 bytes in the data section, which
@@ -610,7 +608,7 @@ double jitter_request(const char *host, int *status){
610 DBG(print_ntp_control_message(&req)); 608 DBG(print_ntp_control_message(&req));
611 609
612 req.count = htons(MAX_CM_SIZE); 610 req.count = htons(MAX_CM_SIZE);
613 DBG(printf("recieving READVAR response...\n")); 611 DBG(printf("receiving READVAR response...\n"));
614 read(conn, &req, SIZEOF_NTPCM(req)); 612 read(conn, &req, SIZEOF_NTPCM(req));
615 DBG(print_ntp_control_message(&req)); 613 DBG(print_ntp_control_message(&req));
616 614
diff --git a/plugins/check_ntp_peer.c b/plugins/check_ntp_peer.c
index c656b0f..6842842 100644
--- a/plugins/check_ntp_peer.c
+++ b/plugins/check_ntp_peer.c
@@ -245,7 +245,7 @@ int ntp_request(const char *host, double *offset, int *offset_result, double *ji
245 do { 245 do {
246 /* Attempt to read the largest size packet possible */ 246 /* Attempt to read the largest size packet possible */
247 req.count=htons(MAX_CM_SIZE); 247 req.count=htons(MAX_CM_SIZE);
248 DBG(printf("recieving READSTAT response")) 248 DBG(printf("receiving READSTAT response"))
249 if(read(conn, &req, SIZEOF_NTPCM(req)) == -1) 249 if(read(conn, &req, SIZEOF_NTPCM(req)) == -1)
250 die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n"); 250 die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
251 DBG(print_ntp_control_message(&req)); 251 DBG(print_ntp_control_message(&req));
diff --git a/plugins/check_ntp_time.c b/plugins/check_ntp_time.c
index 295f86f..391b2df 100644
--- a/plugins/check_ntp_time.c
+++ b/plugins/check_ntp_time.c
@@ -244,7 +244,7 @@ void setup_request(ntp_message *p){
244 * this is done by filtering servers based on stratum, dispersion, and 244 * this is done by filtering servers based on stratum, dispersion, and
245 * finally round-trip delay. */ 245 * finally round-trip delay. */
246int best_offset_server(const ntp_server_results *slist, int nservers){ 246int best_offset_server(const ntp_server_results *slist, int nservers){
247 int i=0, cserver=0, best_server=-1; 247 int cserver=0, best_server=-1;
248 248
249 /* for each server */ 249 /* for each server */
250 for(cserver=0; cserver<nservers; cserver++){ 250 for(cserver=0; cserver<nservers; cserver++){
@@ -303,7 +303,7 @@ int best_offset_server(const ntp_server_results *slist, int nservers){
303 * we have to do it in a way that our lazy macros don't handle currently :( */ 303 * we have to do it in a way that our lazy macros don't handle currently :( */
304double offset_request(const char *host, int *status){ 304double offset_request(const char *host, int *status){
305 int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0; 305 int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0;
306 int servers_completed=0, one_written=0, one_read=0, servers_readable=0, best_index=-1; 306 int servers_completed=0, one_read=0, servers_readable=0, best_index=-1;
307 time_t now_time=0, start_ts=0; 307 time_t now_time=0, start_ts=0;
308 ntp_message *req=NULL; 308 ntp_message *req=NULL;
309 double avg_offset=0.; 309 double avg_offset=0.;
@@ -368,7 +368,6 @@ double offset_request(const char *host, int *status){
368 * been touched in the past second or so and is still lacking 368 * been touched in the past second or so and is still lacking
369 * some responses. For each of these servers, send a new request, 369 * some responses. For each of these servers, send a new request,
370 * and update the "waiting" timestamp with the current time. */ 370 * and update the "waiting" timestamp with the current time. */
371 one_written=0;
372 now_time=time(NULL); 371 now_time=time(NULL);
373 372
374 for(i=0; i<num_hosts; i++){ 373 for(i=0; i<num_hosts; i++){
@@ -378,7 +377,6 @@ double offset_request(const char *host, int *status){
378 setup_request(&req[i]); 377 setup_request(&req[i]);
379 write(socklist[i], &req[i], sizeof(ntp_message)); 378 write(socklist[i], &req[i], sizeof(ntp_message));
380 servers[i].waiting=now_time; 379 servers[i].waiting=now_time;
381 one_written=1;
382 break; 380 break;
383 } 381 }
384 } 382 }
@@ -635,7 +633,7 @@ void print_help(void){
635 printf("%s\n", _("Notes:")); 633 printf("%s\n", _("Notes:"));
636 printf(" %s\n", _("If you'd rather want to monitor an NTP server, please use")); 634 printf(" %s\n", _("If you'd rather want to monitor an NTP server, please use"));
637 printf(" %s\n", _("check_ntp_peer.")); 635 printf(" %s\n", _("check_ntp_peer."));
638 printf(" %s\n", _("--time-offset is usefull for compensating for servers with known")); 636 printf(" %s\n", _("--time-offset is useful for compensating for servers with known"));
639 printf(" %s\n", _("and expected clock skew.")); 637 printf(" %s\n", _("and expected clock skew."));
640 printf("\n"); 638 printf("\n");
641 printf(UT_THRESHOLDS_NOTES); 639 printf(UT_THRESHOLDS_NOTES);
diff --git a/plugins/check_pgsql.c b/plugins/check_pgsql.c
index 2eb699e..b8fc5f1 100644
--- a/plugins/check_pgsql.c
+++ b/plugins/check_pgsql.c
@@ -34,6 +34,7 @@ const char *email = "devel@monitoring-plugins.org";
34 34
35#include "common.h" 35#include "common.h"
36#include "utils.h" 36#include "utils.h"
37#include "utils_cmd.h"
37 38
38#include "netutils.h" 39#include "netutils.h"
39#include <libpq-fe.h> 40#include <libpq-fe.h>
@@ -346,7 +347,7 @@ process_arguments (int argc, char **argv)
346 if (!is_pg_dbname (optarg)) /* checks length and valid chars */ 347 if (!is_pg_dbname (optarg)) /* checks length and valid chars */
347 usage2 (_("Database name is not valid"), optarg); 348 usage2 (_("Database name is not valid"), optarg);
348 else /* we know length, and know optarg is terminated, so us strcpy */ 349 else /* we know length, and know optarg is terminated, so us strcpy */
349 strcpy (dbName, optarg); 350 snprintf(dbName, NAMEDATALEN, "%s", optarg);
350 break; 351 break;
351 case 'l': /* login name */ 352 case 'l': /* login name */
352 if (!is_pg_logname (optarg)) 353 if (!is_pg_logname (optarg))
@@ -565,7 +566,7 @@ print_help (void)
565 566
566 printf (" %s\n", _("Typically, the monitoring user (unless the --logname option is used) should be")); 567 printf (" %s\n", _("Typically, the monitoring user (unless the --logname option is used) should be"));
567 printf (" %s\n", _("able to connect to the database without a password. The plugin can also send")); 568 printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
568 printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password.")); 569 printf (" %s\n", _("a password, but no effort is made to obscure or encrypt the password."));
569 570
570 printf (UT_SUPPORT); 571 printf (UT_SUPPORT);
571} 572}
diff --git a/plugins/check_procs.c b/plugins/check_procs.c
index 4bcc56b..f7917c3 100644
--- a/plugins/check_procs.c
+++ b/plugins/check_procs.c
@@ -764,6 +764,11 @@ be the total number of running processes\n\n"));
764 printf (" %s\n", "check_procs -w 2:2 -c 2:1024 -C portsentry"); 764 printf (" %s\n", "check_procs -w 2:2 -c 2:1024 -C portsentry");
765 printf (" %s\n", _("Warning if not two processes with command name portsentry.")); 765 printf (" %s\n", _("Warning if not two processes with command name portsentry."));
766 printf (" %s\n\n", _("Critical if < 2 or > 1024 processes")); 766 printf (" %s\n\n", _("Critical if < 2 or > 1024 processes"));
767 printf (" %s\n", "check_procs -c 1: -C sshd");
768 printf (" %s\n", _("Critical if not at least 1 process with command sshd"));
769 printf (" %s\n", "check_procs -w 1024 -c 1: -C sshd");
770 printf (" %s\n", _("Warning if > 1024 processes with command name sshd."));
771 printf (" %s\n\n", _("Critical if < 1 processes with command name sshd."));
767 printf (" %s\n", "check_procs -w 10 -a '/usr/local/bin/perl' -u root"); 772 printf (" %s\n", "check_procs -w 10 -a '/usr/local/bin/perl' -u root");
768 printf (" %s\n", _("Warning alert if > 10 processes with command arguments containing")); 773 printf (" %s\n", _("Warning alert if > 10 processes with command arguments containing"));
769 printf (" %s\n\n", _("'/usr/local/bin/perl' and owned by root")); 774 printf (" %s\n\n", _("'/usr/local/bin/perl' and owned by root"));
diff --git a/plugins/check_radius.c b/plugins/check_radius.c
index 03cbb8b..be1001b 100644
--- a/plugins/check_radius.c
+++ b/plugins/check_radius.c
@@ -36,7 +36,9 @@ const char *email = "devel@monitoring-plugins.org";
36#include "utils.h" 36#include "utils.h"
37#include "netutils.h" 37#include "netutils.h"
38 38
39#if defined(HAVE_LIBFREERADIUS_CLIENT) 39#if defined(HAVE_LIBRADCLI)
40#include <radcli/radcli.h>
41#elif defined(HAVE_LIBFREERADIUS_CLIENT)
40#include <freeradius-client.h> 42#include <freeradius-client.h>
41#elif defined(HAVE_LIBRADIUSCLIENT_NG) 43#elif defined(HAVE_LIBRADIUSCLIENT_NG)
42#include <radiusclient-ng.h> 44#include <radiusclient-ng.h>
@@ -48,22 +50,24 @@ int process_arguments (int, char **);
48void print_help (void); 50void print_help (void);
49void print_usage (void); 51void print_usage (void);
50 52
51#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) 53#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) || defined(HAVE_LIBRADCLI)
52#define my_rc_conf_str(a) rc_conf_str(rch,a) 54#define my_rc_conf_str(a) rc_conf_str(rch,a)
55#if defined(HAVE_LIBRADCLI)
56#define my_rc_send_server(a,b) rc_send_server(rch,a,b,AUTH)
57#else
53#define my_rc_send_server(a,b) rc_send_server(rch,a,b) 58#define my_rc_send_server(a,b) rc_send_server(rch,a,b)
54#ifdef HAVE_LIBFREERADIUS_CLIENT 59#endif
60#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADCLI)
55#define my_rc_buildreq(a,b,c,d,e,f) rc_buildreq(rch,a,b,c,d,(a)->secret,e,f) 61#define my_rc_buildreq(a,b,c,d,e,f) rc_buildreq(rch,a,b,c,d,(a)->secret,e,f)
56#else 62#else
57#define my_rc_buildreq(a,b,c,d,e,f) rc_buildreq(rch,a,b,c,d,e,f) 63#define my_rc_buildreq(a,b,c,d,e,f) rc_buildreq(rch,a,b,c,d,e,f)
58#endif 64#endif
59#define my_rc_own_ipaddress() rc_own_ipaddress(rch)
60#define my_rc_avpair_add(a,b,c,d) rc_avpair_add(rch,a,b,c,-1,d) 65#define my_rc_avpair_add(a,b,c,d) rc_avpair_add(rch,a,b,c,-1,d)
61#define my_rc_read_dictionary(a) rc_read_dictionary(rch, a) 66#define my_rc_read_dictionary(a) rc_read_dictionary(rch, a)
62#else 67#else
63#define my_rc_conf_str(a) rc_conf_str(a) 68#define my_rc_conf_str(a) rc_conf_str(a)
64#define my_rc_send_server(a,b) rc_send_server(a, b) 69#define my_rc_send_server(a,b) rc_send_server(a, b)
65#define my_rc_buildreq(a,b,c,d,e,f) rc_buildreq(a,b,c,d,e,f) 70#define my_rc_buildreq(a,b,c,d,e,f) rc_buildreq(a,b,c,d,e,f)
66#define my_rc_own_ipaddress() rc_own_ipaddress()
67#define my_rc_avpair_add(a,b,c,d) rc_avpair_add(a, b, c, d) 71#define my_rc_avpair_add(a,b,c,d) rc_avpair_add(a, b, c, d)
68#define my_rc_read_dictionary(a) rc_read_dictionary(a) 72#define my_rc_read_dictionary(a) rc_read_dictionary(a)
69#endif 73#endif
@@ -76,7 +80,7 @@ void print_usage (void);
76 80
77int my_rc_read_config(char *); 81int my_rc_read_config(char *);
78 82
79#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) 83#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) || defined(HAVE_LIBRADCLI)
80rc_handle *rch = NULL; 84rc_handle *rch = NULL;
81#endif 85#endif
82 86
@@ -90,7 +94,6 @@ char *config_file = NULL;
90unsigned short port = PW_AUTH_UDP_PORT; 94unsigned short port = PW_AUTH_UDP_PORT;
91int retries = 1; 95int retries = 1;
92int verbose = FALSE; 96int verbose = FALSE;
93ENV *env = NULL;
94 97
95/****************************************************************************** 98/******************************************************************************
96 99
@@ -150,6 +153,8 @@ Please note that all tags must be lowercase to use the DocBook XML DTD.
150int 153int
151main (int argc, char **argv) 154main (int argc, char **argv)
152{ 155{
156 struct sockaddr_storage ss;
157 char name[HOST_NAME_MAX];
153 char msg[BUFFER_LEN]; 158 char msg[BUFFER_LEN];
154 SEND_DATA data; 159 SEND_DATA data;
155 int result = STATE_UNKNOWN; 160 int result = STATE_UNKNOWN;
@@ -185,15 +190,14 @@ main (int argc, char **argv)
185 die (STATE_UNKNOWN, _("Invalid NAS-Identifier\n")); 190 die (STATE_UNKNOWN, _("Invalid NAS-Identifier\n"));
186 } 191 }
187 192
188 if (nasipaddress != NULL) { 193 if (nasipaddress == NULL) {
189 if (rc_good_ipaddr (nasipaddress)) 194 if (gethostname (name, sizeof(name)) != 0)
190 die (STATE_UNKNOWN, _("Invalid NAS-IP-Address\n")); 195 die (STATE_UNKNOWN, _("gethostname() failed!\n"));
191 if ((client_id = rc_get_ipaddr(nasipaddress)) == 0) 196 nasipaddress = name;
192 die (STATE_UNKNOWN, _("Invalid NAS-IP-Address\n"));
193 } else {
194 if ((client_id = my_rc_own_ipaddress ()) == 0)
195 die (STATE_UNKNOWN, _("Can't find local IP for NAS-IP-Address\n"));
196 } 197 }
198 if (!dns_lookup (nasipaddress, &ss, AF_INET)) /* TODO: Support IPv6. */
199 die (STATE_UNKNOWN, _("Invalid NAS-IP-Address\n"));
200 client_id = ntohl (((struct sockaddr_in *)&ss)->sin_addr.s_addr);
197 if (my_rc_avpair_add (&(data.send_pairs), PW_NAS_IP_ADDRESS, &client_id, 0) == NULL) 201 if (my_rc_avpair_add (&(data.send_pairs), PW_NAS_IP_ADDRESS, &client_id, 0) == NULL)
198 die (STATE_UNKNOWN, _("Invalid NAS-IP-Address\n")); 202 die (STATE_UNKNOWN, _("Invalid NAS-IP-Address\n"));
199 203
@@ -274,7 +278,7 @@ process_arguments (int argc, char **argv)
274 break; 278 break;
275 case 'P': /* port */ 279 case 'P': /* port */
276 if (is_intnonneg (optarg)) 280 if (is_intnonneg (optarg))
277 port = atoi (optarg); 281 port = (unsigned short)atoi (optarg);
278 else 282 else
279 usage4 (_("Port must be a positive integer")); 283 usage4 (_("Port must be a positive integer"));
280 break; 284 break;
@@ -310,7 +314,7 @@ process_arguments (int argc, char **argv)
310 break; 314 break;
311 case 't': /* timeout */ 315 case 't': /* timeout */
312 if (is_intpos (optarg)) 316 if (is_intpos (optarg))
313 timeout_interval = atoi (optarg); 317 timeout_interval = (unsigned)atoi (optarg);
314 else 318 else
315 usage2 (_("Timeout interval must be a positive integer"), optarg); 319 usage2 (_("Timeout interval must be a positive integer"), optarg);
316 break; 320 break;
@@ -356,7 +360,7 @@ print_help (void)
356 printf (" %s\n", "-u, --username=STRING"); 360 printf (" %s\n", "-u, --username=STRING");
357 printf (" %s\n", _("The user to authenticate")); 361 printf (" %s\n", _("The user to authenticate"));
358 printf (" %s\n", "-p, --password=STRING"); 362 printf (" %s\n", "-p, --password=STRING");
359 printf (" %s\n", _("Password for autentication (SECURITY RISK)")); 363 printf (" %s\n", _("Password for authentication (SECURITY RISK)"));
360 printf (" %s\n", "-n, --nas-id=STRING"); 364 printf (" %s\n", "-n, --nas-id=STRING");
361 printf (" %s\n", _("NAS identifier")); 365 printf (" %s\n", _("NAS identifier"));
362 printf (" %s\n", "-N, --nas-ip-address=STRING"); 366 printf (" %s\n", "-N, --nas-ip-address=STRING");
@@ -399,7 +403,7 @@ print_usage (void)
399 403
400int my_rc_read_config(char * a) 404int my_rc_read_config(char * a)
401{ 405{
402#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) 406#if defined(HAVE_LIBFREERADIUS_CLIENT) || defined(HAVE_LIBRADIUSCLIENT_NG) || defined(HAVE_LIBRADCLI)
403 rch = rc_read_config(a); 407 rch = rc_read_config(a);
404 return (rch == NULL) ? 1 : 0; 408 return (rch == NULL) ? 1 : 0;
405#else 409#else
diff --git a/plugins/check_real.c b/plugins/check_real.c
index 6491e6e..0f1a1ba 100644
--- a/plugins/check_real.c
+++ b/plugins/check_real.c
@@ -438,7 +438,7 @@ print_help (void)
438 printf ("%s\n", _("This plugin will attempt to open an RTSP connection with the host.")); 438 printf ("%s\n", _("This plugin will attempt to open an RTSP connection with the host."));
439 printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return")); 439 printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return"));
440 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful connects,")); 440 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful connects,"));
441 printf ("%s\n", _("but incorrect reponse messages from the host result in STATE_WARNING return")); 441 printf ("%s\n", _("but incorrect response messages from the host result in STATE_WARNING return"));
442 printf ("%s\n", _("values.")); 442 printf ("%s\n", _("values."));
443 443
444 printf (UT_SUPPORT); 444 printf (UT_SUPPORT);
diff --git a/plugins/check_smtp.c b/plugins/check_smtp.c
index 1996c6d..d37c57c 100644
--- a/plugins/check_smtp.c
+++ b/plugins/check_smtp.c
@@ -59,10 +59,6 @@ enum {
59#define SMTP_STARTTLS "STARTTLS\r\n" 59#define SMTP_STARTTLS "STARTTLS\r\n"
60#define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n" 60#define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n"
61 61
62#ifndef HOST_MAX_BYTES
63#define HOST_MAX_BYTES 255
64#endif
65
66#define EHLO_SUPPORTS_STARTTLS 1 62#define EHLO_SUPPORTS_STARTTLS 1
67 63
68int process_arguments (int, char **); 64int process_arguments (int, char **);
@@ -128,6 +124,7 @@ main (int argc, char **argv)
128 char *cmd_str = NULL; 124 char *cmd_str = NULL;
129 char *helocmd = NULL; 125 char *helocmd = NULL;
130 char *error_msg = ""; 126 char *error_msg = "";
127 char *server_response = NULL;
131 struct timeval tv; 128 struct timeval tv;
132 129
133 /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */ 130 /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
@@ -189,21 +186,9 @@ main (int argc, char **argv)
189 printf (_("recv() failed\n")); 186 printf (_("recv() failed\n"));
190 return STATE_WARNING; 187 return STATE_WARNING;
191 } 188 }
192 else { 189
193 if (verbose) 190 /* save connect return (220 hostname ..) for later use */
194 printf ("%s", buffer); 191 xasprintf(&server_response, "%s", buffer);
195 /* strip the buffer of carriage returns */
196 strip (buffer);
197 /* make sure we find the response we are looking for */
198 if (!strstr (buffer, server_expect)) {
199 if (server_port == SMTP_PORT)
200 printf (_("Invalid SMTP response received from host: %s\n"), buffer);
201 else
202 printf (_("Invalid SMTP response received from host on port %d: %s\n"),
203 server_port, buffer);
204 return STATE_WARNING;
205 }
206 }
207 192
208 /* send the HELO/EHLO command */ 193 /* send the HELO/EHLO command */
209 send(sd, helocmd, strlen(helocmd), 0); 194 send(sd, helocmd, strlen(helocmd), 0);
@@ -239,8 +224,8 @@ main (int argc, char **argv)
239 result = np_net_ssl_init(sd); 224 result = np_net_ssl_init(sd);
240 if(result != STATE_OK) { 225 if(result != STATE_OK) {
241 printf (_("CRITICAL - Cannot create SSL context.\n")); 226 printf (_("CRITICAL - Cannot create SSL context.\n"));
242 np_net_ssl_cleanup();
243 close(sd); 227 close(sd);
228 np_net_ssl_cleanup();
244 return STATE_CRITICAL; 229 return STATE_CRITICAL;
245 } else { 230 } else {
246 ssl_established = 1; 231 ssl_established = 1;
@@ -284,12 +269,31 @@ main (int argc, char **argv)
284 } 269 }
285#endif 270#endif
286 271
272 if (verbose)
273 printf ("%s", buffer);
274
275 /* save buffer for later use */
276 xasprintf(&server_response, "%s%s", server_response, buffer);
277 /* strip the buffer of carriage returns */
278 strip (server_response);
279
280 /* make sure we find the droids we are looking for */
281 if (!strstr (server_response, server_expect)) {
282 if (server_port == SMTP_PORT)
283 printf (_("Invalid SMTP response received from host: %s\n"), server_response);
284 else
285 printf (_("Invalid SMTP response received from host on port %d: %s\n"),
286 server_port, server_response);
287 return STATE_WARNING;
288 }
289
287 if (send_mail_from) { 290 if (send_mail_from) {
288 my_send(cmd_str, strlen(cmd_str)); 291 my_send(cmd_str, strlen(cmd_str));
289 if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) 292 if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
290 printf("%s", buffer); 293 printf("%s", buffer);
291 } 294 }
292 295
296 n = 0;
293 while (n < ncommands) { 297 while (n < ncommands) {
294 xasprintf (&cmd_str, "%s%s", commands[n], "\r\n"); 298 xasprintf (&cmd_str, "%s%s", commands[n], "\r\n");
295 my_send(cmd_str, strlen(cmd_str)); 299 my_send(cmd_str, strlen(cmd_str));
@@ -764,10 +768,12 @@ recvlines(char *buf, size_t bufsize)
764int 768int
765my_close (void) 769my_close (void)
766{ 770{
771 int result;
772 result = close(sd);
767#ifdef HAVE_SSL 773#ifdef HAVE_SSL
768 np_net_ssl_cleanup(); 774 np_net_ssl_cleanup();
769#endif 775#endif
770 return close(sd); 776 return result;
771} 777}
772 778
773 779
@@ -830,7 +836,7 @@ print_help (void)
830 printf("\n"); 836 printf("\n");
831 printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return")); 837 printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return"));
832 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful")); 838 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
833 printf ("%s\n", _("connects, but incorrect reponse messages from the host result in")); 839 printf ("%s\n", _("connects, but incorrect response messages from the host result in"));
834 printf ("%s\n", _("STATE_WARNING return values.")); 840 printf ("%s\n", _("STATE_WARNING return values."));
835 841
836 printf (UT_SUPPORT); 842 printf (UT_SUPPORT);
diff --git a/plugins/check_snmp.c b/plugins/check_snmp.c
index 9839d6e..afc568b 100644
--- a/plugins/check_snmp.c
+++ b/plugins/check_snmp.c
@@ -152,7 +152,7 @@ state_data *previous_state;
152double *previous_value; 152double *previous_value;
153size_t previous_size = OID_COUNT_STEP; 153size_t previous_size = OID_COUNT_STEP;
154int perf_labels = 1; 154int perf_labels = 1;
155 155char* ip_version = "";
156 156
157static char *fix_snmp_range(char *th) 157static char *fix_snmp_range(char *th)
158{ 158{
@@ -576,6 +576,9 @@ main (int argc, char **argv)
576 len = sizeof(perfstr)-strlen(perfstr)-1; 576 len = sizeof(perfstr)-strlen(perfstr)-1;
577 strncat(perfstr, show, len>ptr-show ? ptr-show : len); 577 strncat(perfstr, show, len>ptr-show ? ptr-show : len);
578 578
579 if (type)
580 strncat(perfstr, type, sizeof(perfstr)-strlen(perfstr)-1);
581
579 if (warning_thresholds) { 582 if (warning_thresholds) {
580 strncat(perfstr, ";", sizeof(perfstr)-strlen(perfstr)-1); 583 strncat(perfstr, ";", sizeof(perfstr)-strlen(perfstr)-1);
581 strncat(perfstr, warning_thresholds, sizeof(perfstr)-strlen(perfstr)-1); 584 strncat(perfstr, warning_thresholds, sizeof(perfstr)-strlen(perfstr)-1);
@@ -588,8 +591,6 @@ main (int argc, char **argv)
588 strncat(perfstr, critical_thresholds, sizeof(perfstr)-strlen(perfstr)-1); 591 strncat(perfstr, critical_thresholds, sizeof(perfstr)-strlen(perfstr)-1);
589 } 592 }
590 593
591 if (type)
592 strncat(perfstr, type, sizeof(perfstr)-strlen(perfstr)-1);
593 strncat(perfstr, " ", sizeof(perfstr)-strlen(perfstr)-1); 594 strncat(perfstr, " ", sizeof(perfstr)-strlen(perfstr)-1);
594 } 595 }
595 } 596 }
@@ -680,6 +681,8 @@ process_arguments (int argc, char **argv)
680 {"offset", required_argument, 0, L_OFFSET}, 681 {"offset", required_argument, 0, L_OFFSET},
681 {"invert-search", no_argument, 0, L_INVERT_SEARCH}, 682 {"invert-search", no_argument, 0, L_INVERT_SEARCH},
682 {"perf-oids", no_argument, 0, 'O'}, 683 {"perf-oids", no_argument, 0, 'O'},
684 {"ipv4", no_argument, 0, '4'},
685 {"ipv6", no_argument, 0, '6'},
683 {0, 0, 0, 0} 686 {0, 0, 0, 0}
684 }; 687 };
685 688
@@ -697,7 +700,7 @@ process_arguments (int argc, char **argv)
697 } 700 }
698 701
699 while (1) { 702 while (1) {
700 c = getopt_long (argc, argv, "nhvVOt:c:w:H:C:o:e:E:d:D:s:t:R:r:l:u:p:m:P:N:L:U:a:x:A:X:", 703 c = getopt_long (argc, argv, "nhvVO46t:c:w:H:C:o:e:E:d:D:s:t:R:r:l:u:p:m:P:N:L:U:a:x:A:X:",
701 longopts, &option); 704 longopts, &option);
702 705
703 if (c == -1 || c == EOF) 706 if (c == -1 || c == EOF)
@@ -922,6 +925,13 @@ process_arguments (int argc, char **argv)
922 case 'O': 925 case 'O':
923 perf_labels=0; 926 perf_labels=0;
924 break; 927 break;
928 case '4':
929 break;
930 case '6':
931 xasprintf(&ip_version, "udp6:");
932 if(verbose>2)
933 printf("IPv6 detected! Will pass \"udp6:\" to snmpget.\n");
934 break;
925 } 935 }
926 } 936 }
927 937
@@ -1127,6 +1137,7 @@ print_help (void)
1127 1137
1128 printf (UT_HELP_VRSN); 1138 printf (UT_HELP_VRSN);
1129 printf (UT_EXTRA_OPTS); 1139 printf (UT_EXTRA_OPTS);
1140 printf (UT_IPv46);
1130 1141
1131 printf (UT_HOST_PORT, 'p', DEFAULT_PORT); 1142 printf (UT_HOST_PORT, 'p', DEFAULT_PORT);
1132 1143
@@ -1197,8 +1208,9 @@ print_help (void)
1197 printf (" %s\n", _("Separates output on multiple OID requests")); 1208 printf (" %s\n", _("Separates output on multiple OID requests"));
1198 1209
1199 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); 1210 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
1211 printf (" %s\n", _("NOTE the final timeout value is calculated using this formula: timeout_interval * retries + 5"));
1200 printf (" %s\n", "-e, --retries=INTEGER"); 1212 printf (" %s\n", "-e, --retries=INTEGER");
1201 printf (" %s\n", _("Number of retries to be used in the requests")); 1213 printf (" %s%i\n", _("Number of retries to be used in the requests, default: "), DEFAULT_RETRIES);
1202 1214
1203 printf (" %s\n", "-O, --perf-oids"); 1215 printf (" %s\n", "-O, --perf-oids");
1204 printf (" %s\n", _("Label performance data with OIDs instead of --label's")); 1216 printf (" %s\n", _("Label performance data with OIDs instead of --label's"));
@@ -1245,5 +1257,5 @@ print_usage (void)
1245 printf ("[-C community] [-s string] [-r regex] [-R regexi] [-t timeout] [-e retries]\n"); 1257 printf ("[-C community] [-s string] [-r regex] [-R regexi] [-t timeout] [-e retries]\n");
1246 printf ("[-l label] [-u units] [-p port-number] [-d delimiter] [-D output-delimiter]\n"); 1258 printf ("[-l label] [-u units] [-p port-number] [-d delimiter] [-D output-delimiter]\n");
1247 printf ("[-m miblist] [-P snmp version] [-N context] [-L seclevel] [-U secname]\n"); 1259 printf ("[-m miblist] [-P snmp version] [-N context] [-L seclevel] [-U secname]\n");
1248 printf ("[-a authproto] [-A authpasswd] [-x privproto] [-X privpasswd]\n"); 1260 printf ("[-a authproto] [-A authpasswd] [-x privproto] [-X privpasswd] [-4|6]\n");
1249} 1261}
diff --git a/plugins/check_swap.c b/plugins/check_swap.c
index 4d5a407..0ff0c77 100644
--- a/plugins/check_swap.c
+++ b/plugins/check_swap.c
@@ -51,7 +51,7 @@ const char *email = "devel@monitoring-plugins.org";
51# define SWAP_CONVERSION 1 51# define SWAP_CONVERSION 1
52#endif 52#endif
53 53
54int check_swap (int usp, float free_swap_mb); 54int check_swap (int usp, float free_swap_mb, float total_swap_mb);
55int process_arguments (int argc, char **argv); 55int process_arguments (int argc, char **argv);
56int validate_arguments (void); 56int validate_arguments (void);
57void print_usage (void); 57void print_usage (void);
@@ -128,7 +128,7 @@ main (int argc, char **argv)
128 percent=100.0; 128 percent=100.0;
129 else 129 else
130 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); 130 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
131 result = max_state (result, check_swap (percent, dskfree_mb)); 131 result = max_state (result, check_swap (percent, dskfree_mb, dsktotal_mb));
132 if (verbose) 132 if (verbose)
133 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent); 133 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
134 } 134 }
@@ -227,7 +227,7 @@ main (int argc, char **argv)
227 free_swap_mb += dskfree_mb; 227 free_swap_mb += dskfree_mb;
228 if (allswaps) { 228 if (allswaps) {
229 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); 229 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
230 result = max_state (result, check_swap (percent, dskfree_mb)); 230 result = max_state (result, check_swap (percent, dskfree_mb, dsktotal_mb));
231 if (verbose) 231 if (verbose)
232 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent); 232 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
233 } 233 }
@@ -289,7 +289,7 @@ main (int argc, char **argv)
289 289
290 if(allswaps && dsktotal_mb > 0){ 290 if(allswaps && dsktotal_mb > 0){
291 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); 291 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
292 result = max_state (result, check_swap (percent, dskfree_mb)); 292 result = max_state (result, check_swap (percent, dskfree_mb, dsktotal_mb));
293 if (verbose) { 293 if (verbose) {
294 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent); 294 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
295 } 295 }
@@ -328,7 +328,7 @@ main (int argc, char **argv)
328 328
329 if(allswaps && dsktotal_mb > 0){ 329 if(allswaps && dsktotal_mb > 0){
330 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); 330 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
331 result = max_state (result, check_swap (percent, dskfree_mb)); 331 result = max_state (result, check_swap (percent, dskfree_mb, dsktotal_mb));
332 if (verbose) { 332 if (verbose) {
333 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent); 333 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
334 } 334 }
@@ -355,7 +355,7 @@ main (int argc, char **argv)
355 status = "- Swap is either disabled, not present, or of zero size. "; 355 status = "- Swap is either disabled, not present, or of zero size. ";
356 } 356 }
357 357
358 result = max_state (result, check_swap (percent_used, free_swap_mb)); 358 result = max_state (result, check_swap (percent_used, free_swap_mb, total_swap_mb));
359 printf (_("SWAP %s - %d%% free (%d MB out of %d MB) %s|"), 359 printf (_("SWAP %s - %d%% free (%d MB out of %d MB) %s|"),
360 state_text (result), 360 state_text (result),
361 (100 - percent_used), (int) free_swap_mb, (int) total_swap_mb, status); 361 (100 - percent_used), (int) free_swap_mb, (int) total_swap_mb, status);
@@ -372,10 +372,10 @@ main (int argc, char **argv)
372 372
373 373
374int 374int
375check_swap (int usp, float free_swap_mb) 375check_swap (int usp, float free_swap_mb, float total_swap_mb)
376{ 376{
377 377
378 if (!free_swap_mb) return no_swap_state; 378 if (!total_swap_mb) return no_swap_state;
379 379
380 int result = STATE_UNKNOWN; 380 int result = STATE_UNKNOWN;
381 float free_swap = free_swap_mb * (1024 * 1024); /* Convert back to bytes as warn and crit specified in bytes */ 381 float free_swap = free_swap_mb * (1024 * 1024); /* Convert back to bytes as warn and crit specified in bytes */
diff --git a/plugins/check_tcp.c b/plugins/check_tcp.c
index 6dc9aa9..1365b9c 100644
--- a/plugins/check_tcp.c
+++ b/plugins/check_tcp.c
@@ -86,6 +86,11 @@ static char buffer[MAXBUF];
86static int expect_mismatch_state = STATE_WARNING; 86static int expect_mismatch_state = STATE_WARNING;
87static int match_flags = NP_MATCH_EXACT; 87static int match_flags = NP_MATCH_EXACT;
88 88
89#ifdef HAVE_SSL
90static char *sni = NULL;
91static int sni_specified = FALSE;
92#endif
93
89#define FLAG_SSL 0x01 94#define FLAG_SSL 0x01
90#define FLAG_VERBOSE 0x02 95#define FLAG_VERBOSE 0x02
91#define FLAG_TIME_WARN 0x04 96#define FLAG_TIME_WARN 0x04
@@ -241,14 +246,14 @@ main (int argc, char **argv)
241 246
242#ifdef HAVE_SSL 247#ifdef HAVE_SSL
243 if (flags & FLAG_SSL){ 248 if (flags & FLAG_SSL){
244 result = np_net_ssl_init(sd); 249 result = np_net_ssl_init_with_hostname(sd, (sni_specified ? sni : NULL));
245 if (result == STATE_OK && check_cert == TRUE) { 250 if (result == STATE_OK && check_cert == TRUE) {
246 result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); 251 result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
247 } 252 }
248 } 253 }
249 if(result != STATE_OK){ 254 if(result != STATE_OK){
250 np_net_ssl_cleanup();
251 if(sd) close(sd); 255 if(sd) close(sd);
256 np_net_ssl_cleanup();
252 return result; 257 return result;
253 } 258 }
254#endif /* HAVE_SSL */ 259#endif /* HAVE_SSL */
@@ -321,10 +326,10 @@ main (int argc, char **argv)
321 if (server_quit != NULL) { 326 if (server_quit != NULL) {
322 my_send(server_quit, strlen(server_quit)); 327 my_send(server_quit, strlen(server_quit));
323 } 328 }
329 if (sd) close (sd);
324#ifdef HAVE_SSL 330#ifdef HAVE_SSL
325 np_net_ssl_cleanup(); 331 np_net_ssl_cleanup();
326#endif 332#endif
327 if (sd) close (sd);
328 333
329 microsec = deltime (tv); 334 microsec = deltime (tv);
330 elapsed_time = (double)microsec / 1.0e6; 335 elapsed_time = (double)microsec / 1.0e6;
@@ -401,6 +406,10 @@ process_arguments (int argc, char **argv)
401 int escape = 0; 406 int escape = 0;
402 char *temp; 407 char *temp;
403 408
409 enum {
410 SNI_OPTION = CHAR_MAX + 1
411 };
412
404 int option = 0; 413 int option = 0;
405 static struct option longopts[] = { 414 static struct option longopts[] = {
406 {"hostname", required_argument, 0, 'H'}, 415 {"hostname", required_argument, 0, 'H'},
@@ -427,6 +436,7 @@ process_arguments (int argc, char **argv)
427 {"version", no_argument, 0, 'V'}, 436 {"version", no_argument, 0, 'V'},
428 {"help", no_argument, 0, 'h'}, 437 {"help", no_argument, 0, 'h'},
429 {"ssl", no_argument, 0, 'S'}, 438 {"ssl", no_argument, 0, 'S'},
439 {"sni", required_argument, 0, SNI_OPTION},
430 {"certificate", required_argument, 0, 'D'}, 440 {"certificate", required_argument, 0, 'D'},
431 {0, 0, 0, 0} 441 {0, 0, 0, 0}
432 }; 442 };
@@ -604,6 +614,15 @@ process_arguments (int argc, char **argv)
604 die (STATE_UNKNOWN, _("Invalid option - SSL is not available")); 614 die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
605#endif 615#endif
606 break; 616 break;
617 case SNI_OPTION:
618#ifdef HAVE_SSL
619 flags |= FLAG_SSL;
620 sni_specified = TRUE;
621 sni = optarg;
622#else
623 die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
624#endif
625 break;
607 case 'A': 626 case 'A':
608 match_flags |= NP_MATCH_ALL; 627 match_flags |= NP_MATCH_ALL;
609 break; 628 break;
@@ -671,6 +690,8 @@ print_help (void)
671 printf (" %s\n", _("1st is #days for warning, 2nd is critical (if not specified - 0).")); 690 printf (" %s\n", _("1st is #days for warning, 2nd is critical (if not specified - 0)."));
672 printf (" %s\n", "-S, --ssl"); 691 printf (" %s\n", "-S, --ssl");
673 printf (" %s\n", _("Use SSL for the connection.")); 692 printf (" %s\n", _("Use SSL for the connection."));
693 printf (" %s\n", "--sni=STRING");
694 printf (" %s\n", _("SSL server_name"));
674#endif 695#endif
675 696
676 printf (UT_WARN_CRIT); 697 printf (UT_WARN_CRIT);
diff --git a/plugins/check_users.c b/plugins/check_users.c
index 54415a4..f6f4b36 100644
--- a/plugins/check_users.c
+++ b/plugins/check_users.c
@@ -54,15 +54,15 @@ int process_arguments (int, char **);
54void print_help (void); 54void print_help (void);
55void print_usage (void); 55void print_usage (void);
56 56
57int wusers = -1; 57char *warning_range = NULL;
58int cusers = -1; 58char *critical_range = NULL;
59thresholds *thlds = NULL;
59 60
60int 61int
61main (int argc, char **argv) 62main (int argc, char **argv)
62{ 63{
63 int users = -1; 64 int users = -1;
64 int result = STATE_UNKNOWN; 65 int result = STATE_UNKNOWN;
65 char *perf;
66#if HAVE_WTSAPI32_H 66#if HAVE_WTSAPI32_H
67 WTS_SESSION_INFO *wtsinfo; 67 WTS_SESSION_INFO *wtsinfo;
68 DWORD wtscount; 68 DWORD wtscount;
@@ -77,8 +77,6 @@ main (int argc, char **argv)
77 bindtextdomain (PACKAGE, LOCALEDIR); 77 bindtextdomain (PACKAGE, LOCALEDIR);
78 textdomain (PACKAGE); 78 textdomain (PACKAGE);
79 79
80 perf = strdup ("");
81
82 /* Parse extra opts if any */ 80 /* Parse extra opts if any */
83 argv = np_extra_opts (&argc, argv, progname); 81 argv = np_extra_opts (&argc, argv, progname);
84 82
@@ -160,23 +158,15 @@ main (int argc, char **argv)
160#endif 158#endif
161 159
162 /* check the user count against warning and critical thresholds */ 160 /* check the user count against warning and critical thresholds */
163 if (users > cusers) 161 result = get_status((double)users, thlds);
164 result = STATE_CRITICAL;
165 else if (users > wusers)
166 result = STATE_WARNING;
167 else if (users >= 0)
168 result = STATE_OK;
169 162
170 if (result == STATE_UNKNOWN) 163 if (result == STATE_UNKNOWN)
171 printf ("%s\n", _("Unable to read output")); 164 printf ("%s\n", _("Unable to read output"));
172 else { 165 else {
173 xasprintf (&perf, "%s", perfdata ("users", users, "", 166 printf (_("USERS %s - %d users currently logged in |%s\n"),
174 TRUE, wusers, 167 state_text(result), users,
175 TRUE, cusers, 168 sperfdata_int("users", users, "", warning_range,
176 TRUE, 0, 169 critical_range, TRUE, 0, FALSE, 0));
177 FALSE, 0));
178 printf (_("USERS %s - %d users currently logged in |%s\n"), state_text (result),
179 users, perf);
180 } 170 }
181 171
182 return result; 172 return result;
@@ -215,33 +205,27 @@ process_arguments (int argc, char **argv)
215 print_revision (progname, NP_VERSION); 205 print_revision (progname, NP_VERSION);
216 exit (STATE_UNKNOWN); 206 exit (STATE_UNKNOWN);
217 case 'c': /* critical */ 207 case 'c': /* critical */
218 if (!is_intnonneg (optarg)) 208 critical_range = optarg;
219 usage4 (_("Critical threshold must be a positive integer"));
220 else
221 cusers = atoi (optarg);
222 break; 209 break;
223 case 'w': /* warning */ 210 case 'w': /* warning */
224 if (!is_intnonneg (optarg)) 211 warning_range = optarg;
225 usage4 (_("Warning threshold must be a positive integer"));
226 else
227 wusers = atoi (optarg);
228 break; 212 break;
229 } 213 }
230 } 214 }
231 215
232 c = optind; 216 c = optind;
233 if (wusers == -1 && argc > c) { 217 if (warning_range == NULL && argc > c)
234 if (is_intnonneg (argv[c]) == FALSE) 218 warning_range = argv[c++];
235 usage4 (_("Warning threshold must be a positive integer")); 219 if (critical_range == NULL && argc > c)
236 else 220 critical_range = argv[c++];
237 wusers = atoi (argv[c++]); 221
238 } 222 /* this will abort in case of invalid ranges */
239 if (cusers == -1 && argc > c) { 223 set_thresholds (&thlds, warning_range, critical_range);
240 if (is_intnonneg (argv[c]) == FALSE) 224
241 usage4 (_("Warning threshold must be a positive integer")); 225 if (thlds->warning->end < 0)
242 else 226 usage4 (_("Warning threshold must be a positive integer"));
243 cusers = atoi (argv[c]); 227 if (thlds->critical->end < 0)
244 } 228 usage4 (_("Critical threshold must be a positive integer"));
245 229
246 return OK; 230 return OK;
247} 231}
diff --git a/plugins/common.h b/plugins/common.h
index 01003b3..0f08e2f 100644
--- a/plugins/common.h
+++ b/plugins/common.h
@@ -161,12 +161,24 @@
161# endif 161# endif
162#endif 162#endif
163 163
164/* openssl 1.1 does not set OPENSSL_NO_SSL2 by default but ships without ssl2 */
165#ifdef OPENSSL_VERSION_NUMBER
166# if OPENSSL_VERSION_NUMBER >= 0x10100000
167# define OPENSSL_NO_SSL2
168# endif
169#endif
170
164/* 171/*
165 * 172 *
166 * Standard Values 173 * Standard Values
167 * 174 *
168 */ 175 */
169 176
177/* MariaDB 10.2 client does not set MYSQL_PORT */
178#ifndef MYSQL_PORT
179# define MYSQL_PORT 3306
180#endif
181
170enum { 182enum {
171 OK = 0, 183 OK = 0,
172 ERROR = -1 184 ERROR = -1
@@ -213,4 +225,18 @@ enum {
213# define __attribute__(x) /* do nothing */ 225# define __attribute__(x) /* do nothing */
214#endif 226#endif
215 227
228/* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
229 * If that fails and the macro isn't defined, we fall back to an educated
230 * guess. There's no guarantee that our guess is adequate and the program
231 * will die with SIGSEGV if it isn't and the upper boundary is breached. */
232#define DEFAULT_MAXFD 256 /* fallback value if no max open files value is set */
233#define MAXFD_LIMIT 8192 /* upper limit of open files */
234#ifdef _SC_OPEN_MAX
235static long maxfd = 0;
236#elif defined(OPEN_MAX)
237# define maxfd OPEN_MAX
238#else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
239# define maxfd DEFAULT_MAXFD
240#endif
241
216#endif /* _COMMON_H_ */ 242#endif /* _COMMON_H_ */
diff --git a/plugins/negate.c b/plugins/negate.c
index beaed1e..50f62d3 100644
--- a/plugins/negate.c
+++ b/plugins/negate.c
@@ -59,8 +59,8 @@ static int state[4] = {
59int 59int
60main (int argc, char **argv) 60main (int argc, char **argv)
61{ 61{
62 int found = 0, result = STATE_UNKNOWN; 62 int result = STATE_UNKNOWN;
63 char *buf, *sub; 63 char *sub;
64 char **command_line; 64 char **command_line;
65 output chld_out, chld_err; 65 output chld_out, chld_err;
66 int i; 66 int i;
@@ -86,11 +86,9 @@ main (int argc, char **argv)
86 result = cmd_run_array (command_line, &chld_out, &chld_err, 0); 86 result = cmd_run_array (command_line, &chld_out, &chld_err, 0);
87 } 87 }
88 if (chld_err.lines > 0) { 88 if (chld_err.lines > 0) {
89 printf ("Error output from command:\n");
90 for (i = 0; i < chld_err.lines; i++) { 89 for (i = 0; i < chld_err.lines; i++) {
91 printf ("%s\n", chld_err.line[i]); 90 fprintf (stderr, "%s\n", chld_err.line[i]);
92 } 91 }
93 exit (STATE_WARNING);
94 } 92 }
95 93
96 /* Return UNKNOWN or worse if no output is returned */ 94 /* Return UNKNOWN or worse if no output is returned */
diff --git a/plugins/netutils.c b/plugins/netutils.c
index 705aaf0..1bb4f07 100644
--- a/plugins/netutils.c
+++ b/plugins/netutils.c
@@ -359,20 +359,21 @@ is_addr (const char *address)
359} 359}
360 360
361int 361int
362resolve_host_or_addr (const char *address, int family) 362dns_lookup (const char *in, struct sockaddr_storage *ss, int family)
363{ 363{
364 struct addrinfo hints; 364 struct addrinfo hints;
365 struct addrinfo *res; 365 struct addrinfo *res;
366 int retval; 366 int retval;
367 367
368 memset (&hints, 0, sizeof (hints)); 368 memset (&hints, 0, sizeof(struct addrinfo));
369 hints.ai_family = family; 369 hints.ai_family = family;
370 retval = getaddrinfo (address, NULL, &hints, &res);
371 370
371 retval = getaddrinfo (in, NULL, &hints, &res);
372 if (retval != 0) 372 if (retval != 0)
373 return FALSE; 373 return FALSE;
374 else { 374
375 freeaddrinfo (res); 375 if (ss != NULL)
376 return TRUE; 376 memcpy (ss, res->ai_addr, res->ai_addrlen);
377 } 377 freeaddrinfo (res);
378 return TRUE;
378} 379}
diff --git a/plugins/netutils.h b/plugins/netutils.h
index 2766029..d7ee0dd 100644
--- a/plugins/netutils.h
+++ b/plugins/netutils.h
@@ -45,6 +45,10 @@
45# endif /* UNIX_PATH_MAX */ 45# endif /* UNIX_PATH_MAX */
46#endif /* HAVE_SYS_UN_H */ 46#endif /* HAVE_SYS_UN_H */
47 47
48#ifndef HOST_MAX_BYTES
49# define HOST_MAX_BYTES 255
50#endif
51
48/* process_request and wrapper macros */ 52/* process_request and wrapper macros */
49#define process_tcp_request(addr, port, sbuf, rbuf, rsize) \ 53#define process_tcp_request(addr, port, sbuf, rbuf, rsize) \
50 process_request(addr, port, IPPROTO_TCP, sbuf, rbuf, rsize) 54 process_request(addr, port, IPPROTO_TCP, sbuf, rbuf, rsize)
@@ -71,8 +75,9 @@ int send_request (int sd, int proto, const char *send_buffer, char *recv_buffer,
71/* "is_*" wrapper macros and functions */ 75/* "is_*" wrapper macros and functions */
72int is_host (const char *); 76int is_host (const char *);
73int is_addr (const char *); 77int is_addr (const char *);
74int resolve_host_or_addr (const char *, int); 78int dns_lookup (const char *, struct sockaddr_storage *, int);
75void host_or_die(const char *str); 79void host_or_die(const char *str);
80#define resolve_host_or_addr(addr, family) dns_lookup(addr, NULL, family)
76#define is_inet_addr(addr) resolve_host_or_addr(addr, AF_INET) 81#define is_inet_addr(addr) resolve_host_or_addr(addr, AF_INET)
77#ifdef USE_IPV6 82#ifdef USE_IPV6
78# define is_inet6_addr(addr) resolve_host_or_addr(addr, AF_INET6) 83# define is_inet6_addr(addr) resolve_host_or_addr(addr, AF_INET6)
diff --git a/plugins/picohttpparser/Makefile.am b/plugins/picohttpparser/Makefile.am
new file mode 100644
index 0000000..87e0531
--- /dev/null
+++ b/plugins/picohttpparser/Makefile.am
@@ -0,0 +1,3 @@
1noinst_LIBRARIES = libpicohttpparser.a
2
3libpicohttpparser_a_SOURCES = picohttpparser.c picohttpparser.h
diff --git a/plugins/picohttpparser/picohttpparser.c b/plugins/picohttpparser/picohttpparser.c
new file mode 100644
index 0000000..74ccc3e
--- /dev/null
+++ b/plugins/picohttpparser/picohttpparser.c
@@ -0,0 +1,645 @@
1/*
2 * Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase,
3 * Shigeo Mitsunari
4 *
5 * The software is licensed under either the MIT License (below) or the Perl
6 * license.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to
10 * deal in the Software without restriction, including without limitation the
11 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
12 * sell copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 * IN THE SOFTWARE.
25 */
26
27#include <assert.h>
28#include <stddef.h>
29#include <string.h>
30#ifdef __SSE4_2__
31#ifdef _MSC_VER
32#include <nmmintrin.h>
33#else
34#include <x86intrin.h>
35#endif
36#endif
37#include "picohttpparser.h"
38
39#if __GNUC__ >= 3
40#define likely(x) __builtin_expect(!!(x), 1)
41#define unlikely(x) __builtin_expect(!!(x), 0)
42#else
43#define likely(x) (x)
44#define unlikely(x) (x)
45#endif
46
47#ifdef _MSC_VER
48#define ALIGNED(n) _declspec(align(n))
49#else
50#define ALIGNED(n) __attribute__((aligned(n)))
51#endif
52
53#define IS_PRINTABLE_ASCII(c) ((unsigned char)(c)-040u < 0137u)
54
55#define CHECK_EOF() \
56 if (buf == buf_end) { \
57 *ret = -2; \
58 return NULL; \
59 }
60
61#define EXPECT_CHAR_NO_CHECK(ch) \
62 if (*buf++ != ch) { \
63 *ret = -1; \
64 return NULL; \
65 }
66
67#define EXPECT_CHAR(ch) \
68 CHECK_EOF(); \
69 EXPECT_CHAR_NO_CHECK(ch);
70
71#define ADVANCE_TOKEN(tok, toklen) \
72 do { \
73 const char *tok_start = buf; \
74 static const char ALIGNED(16) ranges2[16] = "\000\040\177\177"; \
75 int found2; \
76 buf = findchar_fast(buf, buf_end, ranges2, 4, &found2); \
77 if (!found2) { \
78 CHECK_EOF(); \
79 } \
80 while (1) { \
81 if (*buf == ' ') { \
82 break; \
83 } else if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { \
84 if ((unsigned char)*buf < '\040' || *buf == '\177') { \
85 *ret = -1; \
86 return NULL; \
87 } \
88 } \
89 ++buf; \
90 CHECK_EOF(); \
91 } \
92 tok = tok_start; \
93 toklen = buf - tok_start; \
94 } while (0)
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"
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"
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"
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"
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"
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"
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
105static const char *findchar_fast(const char *buf, const char *buf_end, const char *ranges, size_t ranges_size, int *found)
106{
107 *found = 0;
108#if __SSE4_2__
109 if (likely(buf_end - buf >= 16)) {
110 __m128i ranges16 = _mm_loadu_si128((const __m128i *)ranges);
111
112 size_t left = (buf_end - buf) & ~15;
113 do {
114 __m128i b16 = _mm_loadu_si128((const __m128i *)buf);
115 int r = _mm_cmpestri(ranges16, ranges_size, b16, 16, _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_RANGES | _SIDD_UBYTE_OPS);
116 if (unlikely(r != 16)) {
117 buf += r;
118 *found = 1;
119 break;
120 }
121 buf += 16;
122 left -= 16;
123 } while (likely(left != 0));
124 }
125#else
126 /* suppress unused parameter warning */
127 (void)buf_end;
128 (void)ranges;
129 (void)ranges_size;
130#endif
131 return buf;
132}
133
134static const char *get_token_to_eol(const char *buf, const char *buf_end, const char **token, size_t *token_len, int *ret)
135{
136 const char *token_start = buf;
137
138#ifdef __SSE4_2__
139 static const char ALIGNED(16) ranges1[16] = "\0\010" /* allow HT */
140 "\012\037" /* allow SP and up to but not including DEL */
141 "\177\177"; /* allow chars w. MSB set */
142 int found;
143 buf = findchar_fast(buf, buf_end, ranges1, 6, &found);
144 if (found)
145 goto FOUND_CTL;
146#else
147 /* find non-printable char within the next 8 bytes, this is the hottest code; manually inlined */
148 while (likely(buf_end - buf >= 8)) {
149#define DOIT() \
150 do { \
151 if (unlikely(!IS_PRINTABLE_ASCII(*buf))) \
152 goto NonPrintable; \
153 ++buf; \
154 } while (0)
155 DOIT();
156 DOIT();
157 DOIT();
158 DOIT();
159 DOIT();
160 DOIT();
161 DOIT();
162 DOIT();
163#undef DOIT
164 continue;
165 NonPrintable:
166 if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) {
167 goto FOUND_CTL;
168 }
169 ++buf;
170 }
171#endif
172 for (;; ++buf) {
173 CHECK_EOF();
174 if (unlikely(!IS_PRINTABLE_ASCII(*buf))) {
175 if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) {
176 goto FOUND_CTL;
177 }
178 }
179 }
180FOUND_CTL:
181 if (likely(*buf == '\015')) {
182 ++buf;
183 EXPECT_CHAR('\012');
184 *token_len = buf - 2 - token_start;
185 } else if (*buf == '\012') {
186 *token_len = buf - token_start;
187 ++buf;
188 } else {
189 *ret = -1;
190 return NULL;
191 }
192 *token = token_start;
193
194 return buf;
195}
196
197static const char *is_complete(const char *buf, const char *buf_end, size_t last_len, int *ret)
198{
199 int ret_cnt = 0;
200 buf = last_len < 3 ? buf : buf + last_len - 3;
201
202 while (1) {
203 CHECK_EOF();
204 if (*buf == '\015') {
205 ++buf;
206 CHECK_EOF();
207 EXPECT_CHAR('\012');
208 ++ret_cnt;
209 } else if (*buf == '\012') {
210 ++buf;
211 ++ret_cnt;
212 } else {
213 ++buf;
214 ret_cnt = 0;
215 }
216 if (ret_cnt == 2) {
217 return buf;
218 }
219 }
220
221 *ret = -2;
222 return NULL;
223}
224
225#define PARSE_INT(valp_, mul_) \
226 if (*buf < '0' || '9' < *buf) { \
227 buf++; \
228 *ret = -1; \
229 return NULL; \
230 } \
231 *(valp_) = (mul_) * (*buf++ - '0');
232
233#define PARSE_INT_3(valp_) \
234 do { \
235 int res_ = 0; \
236 PARSE_INT(&res_, 100) \
237 *valp_ = res_; \
238 PARSE_INT(&res_, 10) \
239 *valp_ += res_; \
240 PARSE_INT(&res_, 1) \
241 *valp_ += res_; \
242 } while (0)
243
244/* returned pointer is always within [buf, buf_end), or null */
245static const char *parse_http_version(const char *buf, const char *buf_end, int *minor_version, int *ret)
246{
247 /* we want at least [HTTP/1.<two chars>] to try to parse */
248 if (buf_end - buf < 9) {
249 *ret = -2;
250 return NULL;
251 }
252 EXPECT_CHAR_NO_CHECK('H');
253 EXPECT_CHAR_NO_CHECK('T');
254 EXPECT_CHAR_NO_CHECK('T');
255 EXPECT_CHAR_NO_CHECK('P');
256 EXPECT_CHAR_NO_CHECK('/');
257 EXPECT_CHAR_NO_CHECK('1');
258 EXPECT_CHAR_NO_CHECK('.');
259 PARSE_INT(minor_version, 1);
260 return buf;
261}
262
263static const char *parse_headers(const char *buf, const char *buf_end, struct phr_header *headers, size_t *num_headers,
264 size_t max_headers, int *ret)
265{
266 for (;; ++*num_headers) {
267 CHECK_EOF();
268 if (*buf == '\015') {
269 ++buf;
270 EXPECT_CHAR('\012');
271 break;
272 } else if (*buf == '\012') {
273 ++buf;
274 break;
275 }
276 if (*num_headers == max_headers) {
277 *ret = -1;
278 return NULL;
279 }
280 if (!(*num_headers != 0 && (*buf == ' ' || *buf == '\t'))) {
281 /* parsing name, but do not discard SP before colon, see
282 * http://www.mozilla.org/security/announce/2006/mfsa2006-33.html */
283 headers[*num_headers].name = buf;
284 static const char ALIGNED(16) ranges1[] = "\x00 " /* control chars and up to SP */
285 "\"\"" /* 0x22 */
286 "()" /* 0x28,0x29 */
287 ",," /* 0x2c */
288 "//" /* 0x2f */
289 ":@" /* 0x3a-0x40 */
290 "[]" /* 0x5b-0x5d */
291 "{\377"; /* 0x7b-0xff */
292 int found;
293 buf = findchar_fast(buf, buf_end, ranges1, sizeof(ranges1) - 1, &found);
294 if (!found) {
295 CHECK_EOF();
296 }
297 while (1) {
298 if (*buf == ':') {
299 break;
300 } else if (!token_char_map[(unsigned char)*buf]) {
301 *ret = -1;
302 return NULL;
303 }
304 ++buf;
305 CHECK_EOF();
306 }
307 if ((headers[*num_headers].name_len = buf - headers[*num_headers].name) == 0) {
308 *ret = -1;
309 return NULL;
310 }
311 ++buf;
312 for (;; ++buf) {
313 CHECK_EOF();
314 if (!(*buf == ' ' || *buf == '\t')) {
315 break;
316 }
317 }
318 } else {
319 headers[*num_headers].name = NULL;
320 headers[*num_headers].name_len = 0;
321 }
322 const char *value;
323 size_t value_len;
324 if ((buf = get_token_to_eol(buf, buf_end, &value, &value_len, ret)) == NULL) {
325 return NULL;
326 }
327 /* remove trailing SPs and HTABs */
328 const char *value_end = value + value_len;
329 for (; value_end != value; --value_end) {
330 const char c = *(value_end - 1);
331 if (!(c == ' ' || c == '\t')) {
332 break;
333 }
334 }
335 headers[*num_headers].value = value;
336 headers[*num_headers].value_len = value_end - value;
337 }
338 return buf;
339}
340
341static const char *parse_request(const char *buf, const char *buf_end, const char **method, size_t *method_len, const char **path,
342 size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers,
343 size_t max_headers, int *ret)
344{
345 /* skip first empty line (some clients add CRLF after POST content) */
346 CHECK_EOF();
347 if (*buf == '\015') {
348 ++buf;
349 EXPECT_CHAR('\012');
350 } else if (*buf == '\012') {
351 ++buf;
352 }
353
354 /* parse request line */
355 ADVANCE_TOKEN(*method, *method_len);
356 do {
357 ++buf;
358 } while (*buf == ' ');
359 ADVANCE_TOKEN(*path, *path_len);
360 do {
361 ++buf;
362 } while (*buf == ' ');
363 if (*method_len == 0 || *path_len == 0) {
364 *ret = -1;
365 return NULL;
366 }
367 if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) {
368 return NULL;
369 }
370 if (*buf == '\015') {
371 ++buf;
372 EXPECT_CHAR('\012');
373 } else if (*buf == '\012') {
374 ++buf;
375 } else {
376 *ret = -1;
377 return NULL;
378 }
379
380 return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret);
381}
382
383int phr_parse_request(const char *buf_start, size_t len, const char **method, size_t *method_len, const char **path,
384 size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len)
385{
386 const char *buf = buf_start, *buf_end = buf_start + len;
387 size_t max_headers = *num_headers;
388 int r;
389
390 *method = NULL;
391 *method_len = 0;
392 *path = NULL;
393 *path_len = 0;
394 *minor_version = -1;
395 *num_headers = 0;
396
397 /* if last_len != 0, check if the request is complete (a fast countermeasure
398 againt slowloris */
399 if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) {
400 return r;
401 }
402
403 if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, minor_version, headers, num_headers, max_headers,
404 &r)) == NULL) {
405 return r;
406 }
407
408 return (int)(buf - buf_start);
409}
410
411static const char *parse_response(const char *buf, const char *buf_end, int *minor_version, int *status, const char **msg,
412 size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret)
413{
414 /* parse "HTTP/1.x" */
415 if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) {
416 return NULL;
417 }
418 /* skip space */
419 if (*buf != ' ') {
420 *ret = -1;
421 return NULL;
422 }
423 do {
424 ++buf;
425 } while (*buf == ' ');
426 /* parse status code, we want at least [:digit:][:digit:][:digit:]<other char> to try to parse */
427 if (buf_end - buf < 4) {
428 *ret = -2;
429 return NULL;
430 }
431 PARSE_INT_3(status);
432
433 /* get message includig preceding space */
434 if ((buf = get_token_to_eol(buf, buf_end, msg, msg_len, ret)) == NULL) {
435 return NULL;
436 }
437 if (*msg_len == 0) {
438 /* ok */
439 } else if (**msg == ' ') {
440 /* remove preceding space */
441 do {
442 ++*msg;
443 --*msg_len;
444 } while (**msg == ' ');
445 } else {
446 /* garbage found after status code */
447 *ret = -1;
448 return NULL;
449 }
450
451 return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret);
452}
453
454int phr_parse_response(const char *buf_start, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len,
455 struct phr_header *headers, size_t *num_headers, size_t last_len)
456{
457 const char *buf = buf_start, *buf_end = buf + len;
458 size_t max_headers = *num_headers;
459 int r;
460
461 *minor_version = -1;
462 *status = 0;
463 *msg = NULL;
464 *msg_len = 0;
465 *num_headers = 0;
466
467 /* if last_len != 0, check if the response is complete (a fast countermeasure
468 against slowloris */
469 if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) {
470 return r;
471 }
472
473 if ((buf = parse_response(buf, buf_end, minor_version, status, msg, msg_len, headers, num_headers, max_headers, &r)) == NULL) {
474 return r;
475 }
476
477 return (int)(buf - buf_start);
478}
479
480int phr_parse_headers(const char *buf_start, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len)
481{
482 const char *buf = buf_start, *buf_end = buf + len;
483 size_t max_headers = *num_headers;
484 int r;
485
486 *num_headers = 0;
487
488 /* if last_len != 0, check if the response is complete (a fast countermeasure
489 against slowloris */
490 if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) {
491 return r;
492 }
493
494 if ((buf = parse_headers(buf, buf_end, headers, num_headers, max_headers, &r)) == NULL) {
495 return r;
496 }
497
498 return (int)(buf - buf_start);
499}
500
501enum {
502 CHUNKED_IN_CHUNK_SIZE,
503 CHUNKED_IN_CHUNK_EXT,
504 CHUNKED_IN_CHUNK_DATA,
505 CHUNKED_IN_CHUNK_CRLF,
506 CHUNKED_IN_TRAILERS_LINE_HEAD,
507 CHUNKED_IN_TRAILERS_LINE_MIDDLE
508};
509
510static int decode_hex(int ch)
511{
512 if ('0' <= ch && ch <= '9') {
513 return ch - '0';
514 } else if ('A' <= ch && ch <= 'F') {
515 return ch - 'A' + 0xa;
516 } else if ('a' <= ch && ch <= 'f') {
517 return ch - 'a' + 0xa;
518 } else {
519 return -1;
520 }
521}
522
523ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *_bufsz)
524{
525 size_t dst = 0, src = 0, bufsz = *_bufsz;
526 ssize_t ret = -2; /* incomplete */
527
528 while (1) {
529 switch (decoder->_state) {
530 case CHUNKED_IN_CHUNK_SIZE:
531 for (;; ++src) {
532 int v;
533 if (src == bufsz)
534 goto Exit;
535 if ((v = decode_hex(buf[src])) == -1) {
536 if (decoder->_hex_count == 0) {
537 ret = -1;
538 goto Exit;
539 }
540 break;
541 }
542 if (decoder->_hex_count == sizeof(size_t) * 2) {
543 ret = -1;
544 goto Exit;
545 }
546 decoder->bytes_left_in_chunk = decoder->bytes_left_in_chunk * 16 + v;
547 ++decoder->_hex_count;
548 }
549 decoder->_hex_count = 0;
550 decoder->_state = CHUNKED_IN_CHUNK_EXT;
551 /* fallthru */
552 case CHUNKED_IN_CHUNK_EXT:
553 /* RFC 7230 A.2 "Line folding in chunk extensions is disallowed" */
554 for (;; ++src) {
555 if (src == bufsz)
556 goto Exit;
557 if (buf[src] == '\012')
558 break;
559 }
560 ++src;
561 if (decoder->bytes_left_in_chunk == 0) {
562 if (decoder->consume_trailer) {
563 decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD;
564 break;
565 } else {
566 goto Complete;
567 }
568 }
569 decoder->_state = CHUNKED_IN_CHUNK_DATA;
570 /* fallthru */
571 case CHUNKED_IN_CHUNK_DATA: {
572 size_t avail = bufsz - src;
573 if (avail < decoder->bytes_left_in_chunk) {
574 if (dst != src)
575 memmove(buf + dst, buf + src, avail);
576 src += avail;
577 dst += avail;
578 decoder->bytes_left_in_chunk -= avail;
579 goto Exit;
580 }
581 if (dst != src)
582 memmove(buf + dst, buf + src, decoder->bytes_left_in_chunk);
583 src += decoder->bytes_left_in_chunk;
584 dst += decoder->bytes_left_in_chunk;
585 decoder->bytes_left_in_chunk = 0;
586 decoder->_state = CHUNKED_IN_CHUNK_CRLF;
587 }
588 /* fallthru */
589 case CHUNKED_IN_CHUNK_CRLF:
590 for (;; ++src) {
591 if (src == bufsz)
592 goto Exit;
593 if (buf[src] != '\015')
594 break;
595 }
596 if (buf[src] != '\012') {
597 ret = -1;
598 goto Exit;
599 }
600 ++src;
601 decoder->_state = CHUNKED_IN_CHUNK_SIZE;
602 break;
603 case CHUNKED_IN_TRAILERS_LINE_HEAD:
604 for (;; ++src) {
605 if (src == bufsz)
606 goto Exit;
607 if (buf[src] != '\015')
608 break;
609 }
610 if (buf[src++] == '\012')
611 goto Complete;
612 decoder->_state = CHUNKED_IN_TRAILERS_LINE_MIDDLE;
613 /* fallthru */
614 case CHUNKED_IN_TRAILERS_LINE_MIDDLE:
615 for (;; ++src) {
616 if (src == bufsz)
617 goto Exit;
618 if (buf[src] == '\012')
619 break;
620 }
621 ++src;
622 decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD;
623 break;
624 default:
625 assert(!"decoder is corrupt");
626 }
627 }
628
629Complete:
630 ret = bufsz - src;
631Exit:
632 if (dst != src)
633 memmove(buf + dst, buf + src, bufsz - src);
634 *_bufsz = dst;
635 return ret;
636}
637
638int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder)
639{
640 return decoder->_state == CHUNKED_IN_CHUNK_DATA;
641}
642
643#undef CHECK_EOF
644#undef EXPECT_CHAR
645#undef ADVANCE_TOKEN
diff --git a/plugins/picohttpparser/picohttpparser.h b/plugins/picohttpparser/picohttpparser.h
new file mode 100644
index 0000000..0849f84
--- /dev/null
+++ b/plugins/picohttpparser/picohttpparser.h
@@ -0,0 +1,87 @@
1/*
2 * Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase,
3 * Shigeo Mitsunari
4 *
5 * The software is licensed under either the MIT License (below) or the Perl
6 * license.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to
10 * deal in the Software without restriction, including without limitation the
11 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
12 * sell copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 * IN THE SOFTWARE.
25 */
26
27#ifndef picohttpparser_h
28#define picohttpparser_h
29
30#include <sys/types.h>
31
32#ifdef _MSC_VER
33#define ssize_t intptr_t
34#endif
35
36#ifdef __cplusplus
37extern "C" {
38#endif
39
40/* contains name and value of a header (name == NULL if is a continuing line
41 * of a multiline header */
42struct phr_header {
43 const char *name;
44 size_t name_len;
45 const char *value;
46 size_t value_len;
47};
48
49/* returns number of bytes consumed if successful, -2 if request is partial,
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,
52 int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len);
53
54/* ditto */
55int phr_parse_response(const char *_buf, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len,
56 struct phr_header *headers, size_t *num_headers, size_t last_len);
57
58/* ditto */
59int phr_parse_headers(const char *buf, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len);
60
61/* should be zero-filled before start */
62struct phr_chunked_decoder {
63 size_t bytes_left_in_chunk; /* number of bytes left in current chunk */
64 char consume_trailer; /* if trailing headers should be consumed */
65 char _hex_count;
66 char _state;
67};
68
69/* the function rewrites the buffer given as (buf, bufsz) removing the chunked-
70 * encoding headers. When the function returns without an error, bufsz is
71 * updated to the length of the decoded data available. Applications should
72 * repeatedly call the function while it returns -2 (incomplete) every time
73 * supplying newly arrived data. If the end of the chunked-encoded data is
74 * found, the function returns a non-negative number indicating the number of
75 * octets left undecoded at the tail of the supplied buffer. Returns -1 on
76 * error.
77 */
78ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *bufsz);
79
80/* returns if the chunked decoder is in middle of chunked data */
81int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder);
82
83#ifdef __cplusplus
84}
85#endif
86
87#endif
diff --git a/plugins/popen.c b/plugins/popen.c
index 592263f..9eb49b6 100644
--- a/plugins/popen.c
+++ b/plugins/popen.c
@@ -39,9 +39,9 @@
39*****************************************************************************/ 39*****************************************************************************/
40 40
41#include "common.h" 41#include "common.h"
42#include "utils.h"
42 43
43/* extern so plugin has pid to kill exec'd process on timeouts */ 44/* extern so plugin has pid to kill exec'd process on timeouts */
44extern int timeout_interval;
45extern pid_t *childpid; 45extern pid_t *childpid;
46extern int *child_stderr_array; 46extern int *child_stderr_array;
47extern FILE *child_process; 47extern FILE *child_process;
@@ -76,18 +76,9 @@ RETSIGTYPE popen_timeout_alarm_handler (int);
76#define SIG_ERR ((Sigfunc *)-1) 76#define SIG_ERR ((Sigfunc *)-1)
77#endif 77#endif
78 78
79#define min(a,b) ((a) < (b) ? (a) : (b))
80#define max(a,b) ((a) > (b) ? (a) : (b))
81int open_max (void); /* {Prog openmax} */
82static void err_sys (const char *, ...) __attribute__((noreturn,format(printf, 1, 2)));
83char *rtrim (char *, const char *);
84 79
85char *pname = NULL; /* caller can set this from argv[0] */ 80char *pname = NULL; /* caller can set this from argv[0] */
86 81
87/*int *childerr = NULL;*//* ptr to array allocated at run-time */
88/*extern pid_t *childpid = NULL; *//* ptr to array allocated at run-time */
89static int maxfd; /* from our open_max(), {Prog openmax} */
90
91#ifdef REDHAT_SPOPEN_ERROR 82#ifdef REDHAT_SPOPEN_ERROR
92static volatile int childtermd = 0; 83static volatile int childtermd = 0;
93#endif 84#endif
@@ -186,14 +177,15 @@ spopen (const char *cmdstring)
186 } 177 }
187 argv[i] = NULL; 178 argv[i] = NULL;
188 179
180 if(maxfd == 0)
181 maxfd = open_max();
182
189 if (childpid == NULL) { /* first time through */ 183 if (childpid == NULL) { /* first time through */
190 maxfd = open_max (); /* allocate zeroed out array for child pids */
191 if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL) 184 if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
192 return (NULL); 185 return (NULL);
193 } 186 }
194 187
195 if (child_stderr_array == NULL) { /* first time through */ 188 if (child_stderr_array == NULL) { /* first time through */
196 maxfd = open_max (); /* allocate zeroed out array for child pids */
197 if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL) 189 if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
198 return (NULL); 190 return (NULL);
199 } 191 }
@@ -273,15 +265,6 @@ spclose (FILE * fp)
273 return (1); 265 return (1);
274} 266}
275 267
276#ifdef OPEN_MAX
277static int openmax = OPEN_MAX;
278#else
279static int openmax = 0;
280#endif
281
282#define OPEN_MAX_GUESS 256 /* if OPEN_MAX is indeterminate */
283 /* no guarantee this is adequate */
284
285#ifdef REDHAT_SPOPEN_ERROR 268#ifdef REDHAT_SPOPEN_ERROR
286RETSIGTYPE 269RETSIGTYPE
287popen_sigchld_handler (int signo) 270popen_sigchld_handler (int signo)
@@ -309,63 +292,3 @@ popen_timeout_alarm_handler (int signo)
309 exit (STATE_CRITICAL); 292 exit (STATE_CRITICAL);
310 } 293 }
311} 294}
312
313
314int
315open_max (void)
316{
317 if (openmax == 0) { /* first time through */
318 errno = 0;
319 if ((openmax = sysconf (_SC_OPEN_MAX)) < 0) {
320 if (errno == 0)
321 openmax = OPEN_MAX_GUESS; /* it's indeterminate */
322 else
323 err_sys (_("sysconf error for _SC_OPEN_MAX"));
324 }
325 }
326 return (openmax);
327}
328
329
330/* Fatal error related to a system call.
331 * Print a message and die. */
332
333#define MAXLINE 2048
334static void
335err_sys (const char *fmt, ...)
336{
337 int errnoflag = 1;
338 int errno_save;
339 char buf[MAXLINE];
340
341 va_list ap;
342
343 va_start (ap, fmt);
344 /* err_doit (1, fmt, ap); */
345 errno_save = errno; /* value caller might want printed */
346 vsprintf (buf, fmt, ap);
347 if (errnoflag)
348 sprintf (buf + strlen (buf), ": %s", strerror (errno_save));
349 strcat (buf, "\n");
350 fflush (stdout); /* in case stdout and stderr are the same */
351 fputs (buf, stderr);
352 fflush (NULL); /* flushes all stdio output streams */
353 va_end (ap);
354 exit (1);
355}
356
357char *
358rtrim (char *str, const char *tok)
359{
360 int i = 0;
361 int j = sizeof (str);
362
363 while (str != NULL && i < j) {
364 if (*(str + i) == *tok) {
365 sprintf (str + i, "%s", "\0");
366 return str;
367 }
368 i++;
369 }
370 return str;
371}
diff --git a/plugins/popen.h b/plugins/popen.h
index fc7e78e..a5dd8fa 100644
--- a/plugins/popen.h
+++ b/plugins/popen.h
@@ -7,7 +7,6 @@ FILE *spopen (const char *);
7int spclose (FILE *); 7int spclose (FILE *);
8RETSIGTYPE popen_timeout_alarm_handler (int); 8RETSIGTYPE popen_timeout_alarm_handler (int);
9 9
10extern unsigned int timeout_interval;
11pid_t *childpid=NULL; 10pid_t *childpid=NULL;
12int *child_stderr_array=NULL; 11int *child_stderr_array=NULL;
13FILE *child_process=NULL; 12FILE *child_process=NULL;
diff --git a/plugins/runcmd.c b/plugins/runcmd.c
index 1a7c904..a7155d2 100644
--- a/plugins/runcmd.c
+++ b/plugins/runcmd.c
@@ -67,19 +67,6 @@
67 * occur in any number of threads simultaneously. */ 67 * occur in any number of threads simultaneously. */
68static pid_t *np_pids = NULL; 68static pid_t *np_pids = NULL;
69 69
70/* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
71 * If that fails and the macro isn't defined, we fall back to an educated
72 * guess. There's no guarantee that our guess is adequate and the program
73 * will die with SIGSEGV if it isn't and the upper boundary is breached. */
74#ifdef _SC_OPEN_MAX
75static long maxfd = 0;
76#elif defined(OPEN_MAX)
77# define maxfd OPEN_MAX
78#else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
79# define maxfd 256
80#endif
81
82
83/** prototypes **/ 70/** prototypes **/
84static int np_runcmd_open(const char *, int *, int *) 71static int np_runcmd_open(const char *, int *, int *)
85 __attribute__((__nonnull__(1, 2, 3))); 72 __attribute__((__nonnull__(1, 2, 3)));
@@ -99,14 +86,8 @@ extern void die (int, const char *, ...)
99 * through this api and thus achieve async-safeness throughout the api */ 86 * through this api and thus achieve async-safeness throughout the api */
100void np_runcmd_init(void) 87void np_runcmd_init(void)
101{ 88{
102#ifndef maxfd 89 if(maxfd == 0)
103 if(!maxfd && (maxfd = sysconf(_SC_OPEN_MAX)) < 0) { 90 maxfd = open_max();
104 /* possibly log or emit a warning here, since there's no
105 * guarantee that our guess at maxfd will be adequate */
106 maxfd = 256;
107 }
108#endif
109
110 if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t)); 91 if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t));
111} 92}
112 93
diff --git a/plugins/sslutils.c b/plugins/sslutils.c
index 4f9c793..14f6579 100644
--- a/plugins/sslutils.c
+++ b/plugins/sslutils.c
@@ -1,29 +1,29 @@
1/***************************************************************************** 1/*****************************************************************************
2* 2*
3* Monitoring Plugins SSL utilities 3* Monitoring Plugins SSL utilities
4* 4*
5* License: GPL 5* License: GPL
6* Copyright (c) 2005-2010 Monitoring Plugins Development Team 6* Copyright (c) 2005-2010 Monitoring Plugins Development Team
7* 7*
8* Description: 8* Description:
9* 9*
10* This file contains common functions for plugins that require SSL. 10* This file contains common functions for plugins that require SSL.
11* 11*
12* 12*
13* This program is free software: you can redistribute it and/or modify 13* This program is free software: you can redistribute it and/or modify
14* it under the terms of the GNU General Public License as published by 14* it under the terms of the GNU General Public License as published by
15* the Free Software Foundation, either version 3 of the License, or 15* the Free Software Foundation, either version 3 of the License, or
16* (at your option) any later version. 16* (at your option) any later version.
17* 17*
18* This program is distributed in the hope that it will be useful, 18* This program is distributed in the hope that it will be useful,
19* but WITHOUT ANY WARRANTY; without even the implied warranty of 19* but WITHOUT ANY WARRANTY; without even the implied warranty of
20* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21* GNU General Public License for more details. 21* GNU General Public License for more details.
22* 22*
23* You should have received a copy of the GNU General Public License 23* You should have received a copy of the GNU General Public License
24* along with this program. If not, see <http://www.gnu.org/licenses/>. 24* along with this program. If not, see <http://www.gnu.org/licenses/>.
25* 25*
26* 26*
27*****************************************************************************/ 27*****************************************************************************/
28 28
29#define MAX_CN_LENGTH 256 29#define MAX_CN_LENGTH 256
@@ -48,7 +48,7 @@ int np_net_ssl_init_with_hostname_and_version(int sd, char *host_name, int versi
48} 48}
49 49
50int np_net_ssl_init_with_hostname_version_and_cert(int sd, char *host_name, int version, char *cert, char *privkey) { 50int np_net_ssl_init_with_hostname_version_and_cert(int sd, char *host_name, int version, char *cert, char *privkey) {
51 SSL_METHOD *method = NULL; 51 const SSL_METHOD *method = NULL;
52 long options = 0; 52 long options = 0;
53 53
54 switch (version) { 54 switch (version) {
@@ -193,11 +193,22 @@ int np_net_ssl_read(void *buf, int num) {
193 193
194int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){ 194int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){
195# ifdef USE_OPENSSL 195# ifdef USE_OPENSSL
196 X509 *certificate=NULL; 196 X509 *certificate = NULL;
197 certificate=SSL_get_peer_certificate(s);
198 return(np_net_ssl_check_certificate(certificate, days_till_exp_warn, days_till_exp_crit));
199# else /* ifndef USE_OPENSSL */
200 printf("%s\n", _("WARNING - Plugin does not support checking certificates."));
201 return STATE_WARNING;
202# endif /* USE_OPENSSL */
203}
204
205int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit){
206# ifdef USE_OPENSSL
197 X509_NAME *subj=NULL; 207 X509_NAME *subj=NULL;
198 char timestamp[50] = ""; 208 char timestamp[50] = "";
199 char cn[MAX_CN_LENGTH]= ""; 209 char cn[MAX_CN_LENGTH]= "";
200 210 char *tz;
211
201 int cnlen =-1; 212 int cnlen =-1;
202 int status=STATE_UNKNOWN; 213 int status=STATE_UNKNOWN;
203 214
@@ -209,7 +220,6 @@ int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){
209 int time_remaining; 220 int time_remaining;
210 time_t tm_t; 221 time_t tm_t;
211 222
212 certificate=SSL_get_peer_certificate(s);
213 if (!certificate) { 223 if (!certificate) {
214 printf("%s\n",_("CRITICAL - Cannot retrieve server certificate.")); 224 printf("%s\n",_("CRITICAL - Cannot retrieve server certificate."));
215 return STATE_CRITICAL; 225 return STATE_CRITICAL;
@@ -264,10 +274,18 @@ int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){
264 (tm->data[10 + offset] - '0') * 10 + (tm->data[11 + offset] - '0'); 274 (tm->data[10 + offset] - '0') * 10 + (tm->data[11 + offset] - '0');
265 stamp.tm_isdst = -1; 275 stamp.tm_isdst = -1;
266 276
267 time_left = difftime(timegm(&stamp), time(NULL)); 277 tm_t = timegm(&stamp);
278 time_left = difftime(tm_t, time(NULL));
268 days_left = time_left / 86400; 279 days_left = time_left / 86400;
269 tm_t = mktime (&stamp); 280 tz = getenv("TZ");
270 strftime(timestamp, 50, "%c", localtime(&tm_t)); 281 setenv("TZ", "GMT", 1);
282 tzset();
283 strftime(timestamp, 50, "%c %z", localtime(&tm_t));
284 if (tz)
285 setenv("TZ", tz, 1);
286 else
287 unsetenv("TZ");
288 tzset();
271 289
272 if (days_left > 0 && days_left <= days_till_exp_warn) { 290 if (days_left > 0 && days_left <= days_till_exp_warn) {
273 printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", cn, days_left, timestamp); 291 printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", cn, days_left, timestamp);
diff --git a/plugins/t/NPTest.cache.travis b/plugins/t/NPTest.cache.travis
deleted file mode 100644
index fe8aabd..0000000
--- a/plugins/t/NPTest.cache.travis
+++ /dev/null
@@ -1,58 +0,0 @@
1{
2 'MYSQL_LOGIN_DETAILS' => '-u root -d test',
3 'NP_ALLOW_SUDO' => 'yes',
4 'NP_DNS_SERVER' => '8.8.8.8',
5 'NP_GOOD_NTP_SERVICE' => '',
6 'NP_HOSTNAME_INVALID' => 'nosuchhost',
7 'NP_HOSTNAME_VALID' => 'monitoringplugins.org',
8 'NP_HOSTNAME_VALID_IP' => '130.133.8.40',
9 'NP_HOSTNAME_VALID_REVERSE' => 'orwell.monitoring-plugins.org.',
10 'NP_HOST_DHCP_RESPONSIVE' => '',
11 'NP_HOST_NONRESPONSIVE' => '10.0.0.1',
12 'NP_HOST_RESPONSIVE' => 'localhost',
13 'NP_HOST_SMB' => '',
14 'NP_HOST_SNMP' => '',
15 'NP_HOST_TCP_FTP' => '',
16 'NP_HOST_TCP_HPJD' => '',
17 'NP_HOST_HPJD_PORT_INVALID' => '161',
18 'NP_HOST_HPJD_PORT_VALID' => '',
19 'NP_HOST_TCP_HTTP' => 'localhost',
20 'NP_HOST_TCP_HTTP2' => 'test.monitoring-plugins.org',
21 'NP_HOST_TCP_IMAP' => 'imap.web.de',
22 'NP_HOST_TCP_LDAP' => 'localhost',
23 'NP_HOST_TCP_POP' => 'pop.web.de',
24 'NP_HOST_TCP_SMTP' => 'localhost',
25 'NP_HOST_TCP_SMTP_NOTLS' => '',
26 'NP_HOST_TCP_SMTP_TLS' => '',
27 'NP_INTERNET_ACCESS' => 'yes',
28 'NP_LDAP_BASE_DN' => 'cn=admin,dc=nodomain',
29 'NP_MOUNTPOINT2_VALID' => '',
30 'NP_MOUNTPOINT_VALID' => '/',
31 'NP_MYSQL_SERVER' => 'localhost',
32 'NP_HOST_UDP_TIME' => 'localhost',
33 'NP_MYSQL_SOCKET' => '/var/run/mysqld/mysqld.sock',
34 'NP_MYSQL_WITH_SLAVE' => '',
35 'NP_MYSQL_WITH_SLAVE_LOGIN' => '',
36 'NP_NO_NTP_SERVICE' => 'localhost',
37 'NP_SMB_SHARE' => '',
38 'NP_SMB_SHARE_DENY' => '',
39 'NP_SMB_SHARE_SPC' => '',
40 'NP_SMB_VALID_USER' => '',
41 'NP_SMB_VALID_USER_PASS' => '',
42 'NP_SNMP_COMMUNITY' => '',
43 'NP_SSH_CONFIGFILE' => '~/.ssh/config',
44 'NP_SSH_HOST' => 'localhost',
45 'NP_SSH_IDENTITY' => '~/.ssh/id_dsa',
46 'NP_HOST_TCP_JABBER' => 'jabber.org',
47 'host_nonresponsive' => '10.0.0.1',
48 'host_responsive' => 'localhost',
49 'host_snmp' => '',
50 'host_tcp_ftp' => '',
51 'host_tcp_http' => 'localhost',
52 'host_tcp_imap' => 'imap.nierlein.de',
53 'host_tcp_smtp' => 'localhost',
54 'hostname_invalid' => 'nosuchhost',
55 'snmp_community' => '',
56 'user_snmp' => '',
57 'host_udp_time' => 'none',
58}
diff --git a/plugins/t/check_apt.t b/plugins/t/check_apt.t
index 9ba0ff8..430eb53 100644
--- a/plugins/t/check_apt.t
+++ b/plugins/t/check_apt.t
@@ -23,7 +23,7 @@ sub make_result_regexp {
23} 23}
24 24
25if (-x "./check_apt") { 25if (-x "./check_apt") {
26 plan tests => 28; 26 plan tests => 36;
27} else { 27} else {
28 plan skip_all => "No check_apt compiled"; 28 plan skip_all => "No check_apt compiled";
29} 29}
@@ -40,10 +40,18 @@ $result = NPTest->testCmd( sprintf($testfile_command, "", "debian2") );
40is( $result->return_code, 1, "Debian apt output, warning" ); 40is( $result->return_code, 1, "Debian apt output, warning" );
41like( $result->output, make_result_regexp(13, 0), "Output correct" ); 41like( $result->output, make_result_regexp(13, 0), "Output correct" );
42 42
43$result = NPTest->testCmd( sprintf($testfile_command, "-o", "debian2") );
44is( $result->return_code, 0, "Debian apt output, no critical" );
45like( $result->output, make_result_regexp(13, 0), "Output correct" );
46
43$result = NPTest->testCmd( sprintf($testfile_command, "", "debian3") ); 47$result = NPTest->testCmd( sprintf($testfile_command, "", "debian3") );
44is( $result->return_code, 2, "Debian apt output, some critical" ); 48is( $result->return_code, 2, "Debian apt output, some critical" );
45like( $result->output, make_result_regexp(19, 4), "Output correct" ); 49like( $result->output, make_result_regexp(19, 4), "Output correct" );
46 50
51$result = NPTest->testCmd( sprintf($testfile_command, "-o", "debian3") );
52is( $result->return_code, 2, "Debian apt output, some critical" );
53like( $result->output, make_result_regexp(19, 4), "Output correct" );
54
47$result = NPTest->testCmd( sprintf($testfile_command, "-c '^[^\\(]*\\(.* (Debian-Security:|Ubuntu:[^/]*/[^-]*-security)'", "debian3") ); 55$result = NPTest->testCmd( sprintf($testfile_command, "-c '^[^\\(]*\\(.* (Debian-Security:|Ubuntu:[^/]*/[^-]*-security)'", "debian3") );
48is( $result->return_code, 2, "Debian apt output - should have same result when default security regexp specified via -c" ); 56is( $result->return_code, 2, "Debian apt output - should have same result when default security regexp specified via -c" );
49like( $result->output, make_result_regexp(19, 4), "Output correct" ); 57like( $result->output, make_result_regexp(19, 4), "Output correct" );
@@ -52,6 +60,10 @@ $result = NPTest->testCmd( sprintf($testfile_command, "-i libc6", "debian3") );
52is( $result->return_code, 1, "Debian apt output, filter for libc6" ); 60is( $result->return_code, 1, "Debian apt output, filter for libc6" );
53like( $result->output, make_result_regexp(3, 0), "Output correct" ); 61like( $result->output, make_result_regexp(3, 0), "Output correct" );
54 62
63$result = NPTest->testCmd( sprintf($testfile_command, "-i libc6", "debian3") );
64is( $result->return_code, 1, "Debian apt output, filter for libc6, not critical" );
65like( $result->output, make_result_regexp(3, 0), "Output correct" );
66
55$result = NPTest->testCmd( sprintf($testfile_command, "-i libc6 -i xen", "debian3") ); 67$result = NPTest->testCmd( sprintf($testfile_command, "-i libc6 -i xen", "debian3") );
56is( $result->return_code, 2, "Debian apt output, filter for libc6 and xen" ); 68is( $result->return_code, 2, "Debian apt output, filter for libc6 and xen" );
57like( $result->output, make_result_regexp(9, 4), "Output correct" ); 69like( $result->output, make_result_regexp(9, 4), "Output correct" );
@@ -64,6 +76,10 @@ $result = NPTest->testCmd( sprintf($testfile_command, "-e libc6", "debian3") );
64is( $result->return_code, 2, "Debian apt output, filter out libc6" ); 76is( $result->return_code, 2, "Debian apt output, filter out libc6" );
65like( $result->output, make_result_regexp(16, 4), "Output correct" ); 77like( $result->output, make_result_regexp(16, 4), "Output correct" );
66 78
79$result = NPTest->testCmd( sprintf($testfile_command, "-e libc6 -o", "debian3") );
80is( $result->return_code, 2, "Debian apt output, filter out libc6, critical" );
81like( $result->output, make_result_regexp(16, 4), "Output correct" );
82
67$result = NPTest->testCmd( sprintf($testfile_command, "-e libc6 -e xen", "debian3") ); 83$result = NPTest->testCmd( sprintf($testfile_command, "-e libc6 -e xen", "debian3") );
68is( $result->return_code, 1, "Debian apt output, filter out libc6 and xen" ); 84is( $result->return_code, 1, "Debian apt output, filter out libc6 and xen" );
69like( $result->output, make_result_regexp(10, 0), "Output correct" ); 85like( $result->output, make_result_regexp(10, 0), "Output correct" );
diff --git a/plugins/t/check_by_ssh.t b/plugins/t/check_by_ssh.t
index 4797390..1d2939e 100644
--- a/plugins/t/check_by_ssh.t
+++ b/plugins/t/check_by_ssh.t
@@ -9,17 +9,9 @@ use Test::More;
9use NPTest; 9use NPTest;
10 10
11# Required parameters 11# Required parameters
12my $ssh_service = getTestParameter( "NP_SSH_HOST", 12my $ssh_service = getTestParameter("NP_SSH_HOST", "A host providing SSH service", "localhost");
13 "A host providing SSH service", 13my $ssh_key = getTestParameter("NP_SSH_IDENTITY", "A key allowing access to NP_SSH_HOST", "~/.ssh/id_dsa");
14 "localhost"); 14my $ssh_conf = getTestParameter( "NP_SSH_CONFIGFILE", "A config file with ssh settings", "~/.ssh/config");
15
16my $ssh_key = getTestParameter( "NP_SSH_IDENTITY",
17 "A key allowing access to NP_SSH_HOST",
18 "~/.ssh/id_dsa");
19
20my $ssh_conf = getTestParameter( "NP_SSH_CONFIGFILE",
21 "A config file with ssh settings",
22 "~/.ssh/config");
23 15
24 16
25plan skip_all => "SSH_HOST and SSH_IDENTITY must be defined" unless ($ssh_service && $ssh_key); 17plan skip_all => "SSH_HOST and SSH_IDENTITY must be defined" unless ($ssh_service && $ssh_key);
diff --git a/plugins/t/check_curl.t b/plugins/t/check_curl.t
new file mode 100644
index 0000000..45ee533
--- /dev/null
+++ b/plugins/t/check_curl.t
@@ -0,0 +1,201 @@
1#! /usr/bin/perl -w -I ..
2#
3# HyperText Transfer Protocol (HTTP) Test via check_http
4#
5#
6
7use strict;
8use Test::More;
9use POSIX qw/mktime strftime/;
10use NPTest;
11
12plan tests => 58;
13
14my $successOutput = '/OK.*HTTP.*second/';
15
16my $res;
17my $plugin = 'check_http';
18$plugin = 'check_curl' if $0 =~ m/check_curl/mx;
19
20my $host_tcp_http = getTestParameter("NP_HOST_TCP_HTTP", "A host providing the HTTP Service (a web server)", "localhost");
21my $host_tls_http = getTestParameter("NP_HOST_TLS_HTTP", "A host providing the HTTPS Service (a tls web server)", "localhost");
22my $host_tls_cert = getTestParameter("NP_HOST_TLS_CERT", "the common name of the certificate.", "localhost");
23my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1");
24my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost");
25my $internet_access = getTestParameter("NP_INTERNET_ACCESS", "Is this system directly connected to the internet?", "yes");
26my $host_tcp_http2 = getTestParameter("NP_HOST_TCP_HTTP2", "A host providing an index page containing the string 'monitoring'", "test.monitoring-plugins.org");
27my $host_tcp_proxy = getTestParameter("NP_HOST_TCP_PROXY", "A host providing a HTTP proxy with CONNECT support", "localhost");
28my $port_tcp_proxy = getTestParameter("NP_PORT_TCP_PROXY", "Port of the proxy with HTTP and CONNECT support", "3128");
29
30my $faketime = -x '/usr/bin/faketime' ? 1 : 0;
31
32
33$res = NPTest->testCmd(
34 "./$plugin $host_tcp_http -wt 300 -ct 600"
35 );
36cmp_ok( $res->return_code, '==', 0, "Webserver $host_tcp_http responded" );
37like( $res->output, $successOutput, "Output OK" );
38
39$res = NPTest->testCmd(
40 "./$plugin $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there' -k 'carl:frown'"
41 );
42like( $res->output, '/bob:there\r\ncarl:frown\r\n/', "Got headers with multiple -k options" );
43
44$res = NPTest->testCmd(
45 "./$plugin $host_nonresponsive -wt 1 -ct 2 -t 3"
46 );
47cmp_ok( $res->return_code, '==', 2, "Webserver $host_nonresponsive not responding" );
48# was CRITICAL only, but both check_curl and check_http print HTTP CRITICAL (puzzle?!)
49like( $res->output, "/HTTP CRITICAL - Invalid HTTP response received from host on port 80: cURL returned 28 - Connection timed out after/", "Output OK");
50
51$res = NPTest->testCmd(
52 "./$plugin $hostname_invalid -wt 1 -ct 2"
53 );
54cmp_ok( $res->return_code, '==', 2, "Webserver $hostname_invalid not valid" );
55# The first part of the message comes from the OS catalogue, so cannot check this.
56# On Debian, it is Name or service not known, on Darwin, it is No address associated with nodename
57# Is also possible to get a socket timeout if DNS is not responding fast enough
58# cURL gives us consistent strings from it's own 'lib/strerror.c'
59like( $res->output, "/cURL returned 6 - Could not resolve host:/", "Output OK");
60
61# host header checks
62$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http");
63like( $res->output, '/^Host: '.$host_tcp_http.'\s*$/ms', "Host Header OK" );
64like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" );
65
66$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http -p 80");
67like( $res->output, '/^Host: '.$host_tcp_http.'\s*$/ms', "Host Header OK" );
68like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" );
69
70$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http:8080 -p 80");
71like( $res->output, '/^Host: '.$host_tcp_http.':8080\s*$/ms', "Host Header OK" );
72like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" );
73
74$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http:8080 -p 80");
75like( $res->output, '/^Host: '.$host_tcp_http.':8080\s*$/ms', "Host Header OK" );
76like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" );
77
78$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http:8080 -p 80 -k 'Host: testhost:8001'");
79like( $res->output, '/^Host: testhost:8001\s*$/ms', "Host Header OK" );
80like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" );
81
82$res = NPTest->testCmd("./$plugin -v -I $host_tcp_http -p 80 -k 'Host: testhost:8001'");
83like( $res->output, '/^Host: testhost:8001\s*$/ms', "Host Header OK" );
84like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" );
85
86SKIP: {
87 skip "No internet access", 4 if $internet_access eq "no";
88
89 $res = NPTest->testCmd("./$plugin -v -H $host_tls_http -S");
90 like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" );
91
92 $res = NPTest->testCmd("./$plugin -v -H $host_tls_http:8080 -S -p 443");
93 like( $res->output, '/^Host: '.$host_tls_http.':8080\s*$/ms', "Host Header OK" );
94
95 $res = NPTest->testCmd("./$plugin -v -H $host_tls_http:443 -S -p 443");
96 like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" );
97
98 $res = NPTest->testCmd("./$plugin -v -H $host_tls_http -D -p 443");
99 like( $res->output, '/(^Host: '.$host_tls_http.'\s*$)|(cURL returned 60)/ms', "Host Header OK" );
100};
101
102SKIP: {
103 skip "No host serving monitoring in index file", 7 unless $host_tcp_http2;
104
105 $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'monitoring'" );
106 cmp_ok( $res->return_code, "==", 0, "Got a reference to 'monitoring'");
107
108 $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'mONiTORing'" );
109 cmp_ok( $res->return_code, "==", 2, "Not got 'mONiTORing'");
110 like ( $res->output, "/pattern not found/", "Error message says 'pattern not found'");
111
112 $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -R 'mONiTORing'" );
113 cmp_ok( $res->return_code, "==", 0, "But case insensitive doesn't mind 'mONiTORing'");
114
115 $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'monitoring' --invert-regex" );
116 cmp_ok( $res->return_code, "==", 2, "Invert results work when found");
117 like ( $res->output, "/pattern found/", "Error message says 'pattern found'");
118
119 $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'mONiTORing' --invert-regex" );
120 cmp_ok( $res->return_code, "==", 0, "And also when not found");
121}
122SKIP: {
123 skip "No internet access", 28 if $internet_access eq "no";
124
125 $res = NPTest->testCmd(
126 "./$plugin --ssl $host_tls_http"
127 );
128 cmp_ok( $res->return_code, '==', 0, "Can read https for $host_tls_http" );
129
130 $res = NPTest->testCmd( "./$plugin -C 1 --ssl $host_tls_http" );
131 cmp_ok( $res->return_code, '==', 0, "Checking certificate for $host_tls_http");
132 like ( $res->output, "/Certificate '$host_tls_cert' will expire on/", "Output OK" );
133 my $saved_cert_output = $res->output;
134
135 $res = NPTest->testCmd( "./$plugin -C 8000,1 --ssl $host_tls_http" );
136 cmp_ok( $res->return_code, '==', 1, "Checking certificate for $host_tls_http");
137 like ( $res->output, qr/WARNING - Certificate '$host_tls_cert' expires in \d+ day/, "Output Warning" );
138
139 $res = NPTest->testCmd( "./$plugin $host_tls_http -C 1" );
140 is( $res->return_code, 0, "Old syntax for cert checking okay" );
141 is( $res->output, $saved_cert_output, "Same output as new syntax" );
142
143 $res = NPTest->testCmd( "./$plugin -H $host_tls_http -C 1" );
144 is( $res->return_code, 0, "Updated syntax for cert checking okay" );
145 is( $res->output, $saved_cert_output, "Same output as new syntax" );
146
147 $res = NPTest->testCmd( "./$plugin -C 1 $host_tls_http" );
148 cmp_ok( $res->output, 'eq', $saved_cert_output, "--ssl option automatically added");
149
150 $res = NPTest->testCmd( "./$plugin $host_tls_http -C 1" );
151 cmp_ok( $res->output, 'eq', $saved_cert_output, "Old syntax for cert checking still works");
152
153 # run some certificate checks with faketime
154 SKIP: {
155 skip "No faketime binary found", 12 if !$faketime;
156 $res = NPTest->testCmd("LC_TIME=C TZ=UTC ./$plugin -C 1 $host_tls_http");
157 like($res->output, qr/OK - Certificate '$host_tls_cert' will expire on/, "Catch cert output");
158 is( $res->return_code, 0, "Catch cert output exit code" );
159 my($mon,$day,$hour,$min,$sec,$year) = ($res->output =~ /(\w+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\d+)/);
160 if(!defined $year) {
161 die("parsing date failed from: ".$res->output);
162 }
163 my $months = {'Jan' => 0, 'Feb' => 1, 'Mar' => 2, 'Apr' => 3, 'May' => 4, 'Jun' => 5, 'Jul' => 6, 'Aug' => 7, 'Sep' => 8, 'Oct' => 9, 'Nov' => 10, 'Dec' => 11};
164 my $ts = mktime($sec, $min, $hour, $day, $months->{$mon}, $year-1900);
165 my $time = strftime("%Y-%m-%d %H:%M:%S", localtime($ts));
166 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts))."' ./$plugin -C 1 $host_tls_http");
167 like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' just expired/, "Output on expire date");
168 is( $res->return_code, 2, "Output on expire date" );
169
170 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-1))."' ./$plugin -C 1 $host_tls_http");
171 like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 0 minutes/, "cert expires in 1 second output");
172 is( $res->return_code, 2, "cert expires in 1 second exit code" );
173
174 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-120))."' ./$plugin -C 1 $host_tls_http");
175 like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 2 minutes/, "cert expires in 2 minutes output");
176 is( $res->return_code, 2, "cert expires in 2 minutes exit code" );
177
178 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-7200))."' ./$plugin -C 1 $host_tls_http");
179 like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 2 hours/, "cert expires in 2 hours output");
180 is( $res->return_code, 2, "cert expires in 2 hours exit code" );
181
182 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts+1))."' ./$plugin -C 1 $host_tls_http");
183 like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expired on/, "Certificate expired output");
184 is( $res->return_code, 2, "Certificate expired exit code" );
185 };
186
187 $res = NPTest->testCmd( "./$plugin --ssl $host_tls_http -E" );
188 like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' );
189 like ( $res->output, '/time_ssl=[\d\.]+/', 'Extended Performance Data SSL Output OK' );
190
191 $res = NPTest->testCmd(
192 "./$plugin --ssl -H www.e-paycobalt.com"
193 );
194 cmp_ok( $res->return_code, "==", 0, "Can read https for www.e-paycobalt.com (uses AES certificate)" );
195
196 $res = NPTest->testCmd( "./$plugin -H www.mozilla.com -u /firefox -f curl" );
197 is( $res->return_code, 0, "Redirection based on location is okay");
198
199 $res = NPTest->testCmd( "./$plugin -H www.mozilla.com --extended-perfdata" );
200 like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' );
201}
diff --git a/plugins/t/check_disk.t b/plugins/t/check_disk.t
index 7e0f74b..fdd8769 100644
--- a/plugins/t/check_disk.t
+++ b/plugins/t/check_disk.t
@@ -248,11 +248,11 @@ $result = NPTest->testCmd( "./check_disk -w 100% -c 100% ".${mountpoint_valid} )
248cmp_ok( $result->return_code, "==", 2, "100% empty" ); 248cmp_ok( $result->return_code, "==", 2, "100% empty" );
249like( $result->output, $failureOutput, "Right output" ); 249like( $result->output, $failureOutput, "Right output" );
250 250
251$result = NPTest->testCmd( "./check_disk -w 100000 -c 100000 $mountpoint_valid" ); 251$result = NPTest->testCmd( "./check_disk -w 100000000 -c 100000000 $mountpoint_valid" );
252cmp_ok( $result->return_code, '==', 2, "Check for 100GB free" ); 252cmp_ok( $result->return_code, '==', 2, "Check for 100TB free" );
253 253
254$result = NPTest->testCmd( "./check_disk -w 100 -c 100 -u GB ".${mountpoint_valid} ); # 100 GB empty 254$result = NPTest->testCmd( "./check_disk -w 100 -c 100 -u TB ".${mountpoint_valid} ); # 100 TB empty
255cmp_ok( $result->return_code, "==", 2, "100 GB empty" ); 255cmp_ok( $result->return_code, "==", 2, "100 TB empty" );
256 256
257 257
258# Checking old syntax of check_disk warn crit [fs], with warn/crit at USED% thresholds 258# Checking old syntax of check_disk warn crit [fs], with warn/crit at USED% thresholds
diff --git a/plugins/t/check_dns.t b/plugins/t/check_dns.t
index 035e768..cdfbe60 100644
--- a/plugins/t/check_dns.t
+++ b/plugins/t/check_dns.t
@@ -10,26 +10,38 @@ use NPTest;
10 10
11plan skip_all => "check_dns not compiled" unless (-x "check_dns"); 11plan skip_all => "check_dns not compiled" unless (-x "check_dns");
12 12
13plan tests => 16; 13plan tests => 19;
14 14
15my $successOutput = '/DNS OK: [\.0-9]+ seconds? response time/'; 15my $successOutput = '/DNS OK: [\.0-9]+ seconds? response time/';
16 16
17my $hostname_valid = getTestParameter( 17my $hostname_valid = getTestParameter(
18 "NP_HOSTNAME_VALID", 18 "NP_HOSTNAME_VALID",
19 "A valid (known to DNS) hostname", 19 "A valid (known to DNS) hostname",
20 "monitoring-plugins.org" 20 "monitoring-plugins.org",
21 ); 21 );
22 22
23my $hostname_valid_ip = getTestParameter( 23my $hostname_valid_ip = getTestParameter(
24 "NP_HOSTNAME_VALID_IP", 24 "NP_HOSTNAME_VALID_IP",
25 "The IP address of the valid hostname $hostname_valid", 25 "The IP address of the valid hostname $hostname_valid",
26 "66.118.156.50", 26 "130.133.8.40",
27 );
28
29my $hostname_valid_cidr = getTestParameter(
30 "NP_HOSTNAME_VALID_CIDR",
31 "An valid CIDR range containing $hostname_valid_ip",
32 "130.133.8.41/30",
33 );
34
35my $hostname_invalid_cidr = getTestParameter(
36 "NP_HOSTNAME_INVALID_CIDR",
37 "An (valid) CIDR range NOT containing $hostname_valid_ip",
38 "130.133.8.39/30",
27 ); 39 );
28 40
29my $hostname_valid_reverse = getTestParameter( 41my $hostname_valid_reverse = getTestParameter(
30 "NP_HOSTNAME_VALID_REVERSE", 42 "NP_HOSTNAME_VALID_REVERSE",
31 "The hostname of $hostname_valid_ip", 43 "The hostname of $hostname_valid_ip",
32 "66-118-156-50.static.sagonet.net.", 44 "orwell.monitoring-plugins.org.",
33 ); 45 );
34 46
35my $hostname_invalid = getTestParameter( 47my $hostname_invalid = getTestParameter(
@@ -87,3 +99,9 @@ $res = NPTest->testCmd("./check_dns -H $hostname_valid_ip -a $hostname_valid_rev
87cmp_ok( $res->return_code, '==', 0, "Got expected fqdn"); 99cmp_ok( $res->return_code, '==', 0, "Got expected fqdn");
88like ( $res->output, $successOutput, "Output OK"); 100like ( $res->output, $successOutput, "Output OK");
89 101
102$res = NPTest->testCmd("./check_dns -H $hostname_valid -a $hostname_valid_cidr -t 5");
103cmp_ok( $res->return_code, '==', 0, "Got expected address");
104
105$res = NPTest->testCmd("./check_dns -H $hostname_valid -a $hostname_invalid_cidr -t 5");
106cmp_ok( $res->return_code, '==', 2, "Got wrong address");
107like ( $res->output, "/^DNS CRITICAL.*expected '$hostname_invalid_cidr' but got '$hostname_valid_ip'".'$/', "Output OK");
diff --git a/plugins/t/check_fping.t b/plugins/t/check_fping.t
index 08692e4..67b357b 100644
--- a/plugins/t/check_fping.t
+++ b/plugins/t/check_fping.t
@@ -5,40 +5,30 @@
5# 5#
6 6
7use strict; 7use strict;
8use Test; 8use Test::More;
9use NPTest; 9use NPTest;
10 10
11use vars qw($tests); 11my $host_responsive = getTestParameter("NP_HOST_RESPONSIVE", "The hostname of system responsive to network requests", "localhost");
12my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1");
13my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost");
12 14
13BEGIN {$tests = 4; plan tests => $tests} 15my $res;
14
15my $successOutput = '/^FPING OK - /';
16my $failureOutput = '/^FPING CRITICAL - /';
17
18my $host_responsive = getTestParameter( "host_responsive", "NP_HOST_RESPONSIVE", "localhost",
19 "The hostname of system responsive to network requests" );
20
21my $host_nonresponsive = getTestParameter( "host_nonresponsive", "NP_HOST_NONRESPONSIVE", "10.0.0.1",
22 "The hostname of system not responsive to network requests" );
23
24my $hostname_invalid = getTestParameter( "hostname_invalid", "NP_HOSTNAME_INVALID", "nosuchhost",
25 "An invalid (not known to DNS) hostname" );
26
27
28my $t;
29 16
30my $fping = qx(which fping 2> /dev/null); 17my $fping = qx(which fping 2> /dev/null);
31chomp($fping); 18chomp($fping);
32if( ! -x "./check_fping") { 19if( ! -x "./check_fping") {
33 $t += skipMissingCmd( "./check_fping", $tests ); 20 plan skip_all => "check_fping not found, skipping tests";
34} 21}
35elsif ( $> != 0 && (!$fping || ! -u $fping)) { 22elsif ( !$fping || !-x $fping ) {
36 $t += skipMsg( "./check_fping", $tests ); 23 plan skip_all => "fping not found or cannot be executed, skipping tests";
37} else { 24} else {
38 $t += checkCmd( "./check_fping $host_responsive", 0, $successOutput ); 25 plan tests => 3;
39 $t += checkCmd( "./check_fping $host_nonresponsive", [ 1, 2 ] ); 26 $res = NPTest->testCmd( "./check_fping $host_responsive" );
40 $t += checkCmd( "./check_fping $hostname_invalid", [ 1, 2 ] ); 27 cmp_ok( $res->return_code, '==', 0, "Responsive host returns OK");
41}
42 28
43exit(0) if defined($Test::Harness::VERSION); 29 $res = NPTest->testCmd( "./check_fping $host_nonresponsive" );
44exit($tests - $t); 30 cmp_ok( $res->return_code, '==', 2, "Non-Responsive host returns Critical");
31
32 $res = NPTest->testCmd( "./check_fping $hostname_invalid" );
33 cmp_ok( $res->return_code, '==', 3, "Invalid host returns Unknown");
34}
diff --git a/plugins/t/check_ftp.t b/plugins/t/check_ftp.t
index de6831b..93a7d7c 100644
--- a/plugins/t/check_ftp.t
+++ b/plugins/t/check_ftp.t
@@ -11,14 +11,9 @@ use NPTest;
11use vars qw($tests); 11use vars qw($tests);
12BEGIN {$tests = 4; plan tests => $tests} 12BEGIN {$tests = 4; plan tests => $tests}
13 13
14my $host_tcp_ftp = getTestParameter( "host_tcp_ftp", "NP_HOST_TCP_FTP", "localhost", 14my $host_tcp_ftp = getTestParameter("NP_HOST_TCP_FTP", "A host providing the FTP Service (an FTP server)", "localhost");
15 "A host providing the FTP Service (an FTP server)"); 15my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1");
16 16my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost");
17my $host_nonresponsive = getTestParameter( "host_nonresponsive", "NP_HOST_NONRESPONSIVE", "10.0.0.1",
18 "The hostname of system not responsive to network requests" );
19
20my $hostname_invalid = getTestParameter( "hostname_invalid", "NP_HOSTNAME_INVALID", "nosuchhost",
21 "An invalid (not known to DNS) hostname" );
22 17
23my $successOutput = '/FTP OK -\s+[0-9]?\.?[0-9]+ second response time/'; 18my $successOutput = '/FTP OK -\s+[0-9]?\.?[0-9]+ second response time/';
24 19
diff --git a/plugins/t/check_http.t b/plugins/t/check_http.t
index c2caec6..c137f7b 100644
--- a/plugins/t/check_http.t
+++ b/plugins/t/check_http.t
@@ -9,54 +9,46 @@ use Test::More;
9use POSIX qw/mktime strftime/; 9use POSIX qw/mktime strftime/;
10use NPTest; 10use NPTest;
11 11
12plan tests => 42; 12plan tests => 50;
13 13
14my $successOutput = '/OK.*HTTP.*second/'; 14my $successOutput = '/OK.*HTTP.*second/';
15 15
16my $res; 16my $res;
17 17my $plugin = 'check_http';
18my $host_tcp_http = getTestParameter( "NP_HOST_TCP_HTTP", 18$plugin = 'check_curl' if $0 =~ m/check_curl/mx;
19 "A host providing the HTTP Service (a web server)", 19
20 "localhost" ); 20my $host_tcp_http = getTestParameter("NP_HOST_TCP_HTTP", "A host providing the HTTP Service (a web server)", "localhost");
21 21my $host_tls_http = getTestParameter("NP_HOST_TLS_HTTP", "A host providing the HTTPS Service (a tls web server)", "localhost");
22my $host_nonresponsive = getTestParameter( "NP_HOST_NONRESPONSIVE", 22my $host_tls_cert = getTestParameter("NP_HOST_TLS_CERT", "the common name of the certificate.", "localhost");
23 "The hostname of system not responsive to network requests", 23my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1");
24 "10.0.0.1" ); 24my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost");
25 25my $internet_access = getTestParameter("NP_INTERNET_ACCESS", "Is this system directly connected to the internet?", "yes");
26my $hostname_invalid = getTestParameter( "NP_HOSTNAME_INVALID", 26my $host_tcp_http2 = getTestParameter("NP_HOST_TCP_HTTP2", "A host providing an index page containing the string 'monitoring'", "test.monitoring-plugins.org");
27 "An invalid (not known to DNS) hostname", 27my $host_tcp_proxy = getTestParameter("NP_HOST_TCP_PROXY", "A host providing a HTTP proxy with CONNECT support", "localhost");
28 "nosuchhost"); 28my $port_tcp_proxy = getTestParameter("NP_PORT_TCP_PROXY", "Port of the proxy with HTTP and CONNECT support", "3128");
29
30my $internet_access = getTestParameter( "NP_INTERNET_ACCESS",
31 "Is this system directly connected to the internet?",
32 "yes");
33
34my $host_tcp_http2 = getTestParameter( "NP_HOST_TCP_HTTP2",
35 "A host providing an index page containing the string 'monitoring'",
36 "test.monitoring-plugins.org" );
37 29
38my $faketime = -x '/usr/bin/faketime' ? 1 : 0; 30my $faketime = -x '/usr/bin/faketime' ? 1 : 0;
39 31
40 32
41$res = NPTest->testCmd( 33$res = NPTest->testCmd(
42 "./check_http $host_tcp_http -wt 300 -ct 600" 34 "./$plugin $host_tcp_http -wt 300 -ct 600"
43 ); 35 );
44cmp_ok( $res->return_code, '==', 0, "Webserver $host_tcp_http responded" ); 36cmp_ok( $res->return_code, '==', 0, "Webserver $host_tcp_http responded" );
45like( $res->output, $successOutput, "Output OK" ); 37like( $res->output, $successOutput, "Output OK" );
46 38
47$res = NPTest->testCmd( 39$res = NPTest->testCmd(
48 "./check_http $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there' -k 'carl:frown'" 40 "./$plugin $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there' -k 'carl:frown'"
49 ); 41 );
50like( $res->output, '/bob:there\r\ncarl:frown\r\n/', "Got headers with multiple -k options" ); 42like( $res->output, '/bob:there\r\ncarl:frown\r\n/', "Got headers with multiple -k options" );
51 43
52$res = NPTest->testCmd( 44$res = NPTest->testCmd(
53 "./check_http $host_nonresponsive -wt 1 -ct 2 -t 3" 45 "./$plugin $host_nonresponsive -wt 1 -ct 2 -t 3"
54 ); 46 );
55cmp_ok( $res->return_code, '==', 2, "Webserver $host_nonresponsive not responding" ); 47cmp_ok( $res->return_code, '==', 2, "Webserver $host_nonresponsive not responding" );
56cmp_ok( $res->output, 'eq', "CRITICAL - Socket timeout after 3 seconds", "Output OK"); 48cmp_ok( $res->output, 'eq', "CRITICAL - Socket timeout after 3 seconds", "Output OK");
57 49
58$res = NPTest->testCmd( 50$res = NPTest->testCmd(
59 "./check_http $hostname_invalid -wt 1 -ct 2" 51 "./$plugin $hostname_invalid -wt 1 -ct 2"
60 ); 52 );
61cmp_ok( $res->return_code, '==', 2, "Webserver $hostname_invalid not valid" ); 53cmp_ok( $res->return_code, '==', 2, "Webserver $hostname_invalid not valid" );
62# The first part of the message comes from the OS catalogue, so cannot check this. 54# The first part of the message comes from the OS catalogue, so cannot check this.
@@ -64,104 +56,141 @@ cmp_ok( $res->return_code, '==', 2, "Webserver $hostname_invalid not valid" );
64# Is also possible to get a socket timeout if DNS is not responding fast enough 56# Is also possible to get a socket timeout if DNS is not responding fast enough
65like( $res->output, "/Unable to open TCP socket|Socket timeout after/", "Output OK"); 57like( $res->output, "/Unable to open TCP socket|Socket timeout after/", "Output OK");
66 58
59# host header checks
60$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http");
61like( $res->output, '/^Host: '.$host_tcp_http.'\s*$/ms', "Host Header OK" );
62
63$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http -p 80");
64like( $res->output, '/^Host: '.$host_tcp_http.'\s*$/ms', "Host Header OK" );
65
66$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http:8080 -p 80");
67like( $res->output, '/^Host: '.$host_tcp_http.':8080\s*$/ms', "Host Header OK" );
68
69$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http:8080 -p 80");
70like( $res->output, '/^Host: '.$host_tcp_http.':8080\s*$/ms', "Host Header OK" );
71
72SKIP: {
73 skip "No internet access", 3 if $internet_access eq "no";
74
75 $res = NPTest->testCmd("./$plugin -v -H $host_tls_http -S");
76 like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" );
77
78 $res = NPTest->testCmd("./$plugin -v -H $host_tls_http:8080 -S -p 443");
79 like( $res->output, '/^Host: '.$host_tls_http.':8080\s*$/ms', "Host Header OK" );
80
81 $res = NPTest->testCmd("./$plugin -v -H $host_tls_http:443 -S -p 443");
82 like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" );
83};
84
67SKIP: { 85SKIP: {
68 skip "No host serving monitoring in index file", 7 unless $host_tcp_http2; 86 skip "No host serving monitoring in index file", 7 unless $host_tcp_http2;
69 87
70 $res = NPTest->testCmd( "./check_http -H $host_tcp_http2 -r 'monitoring'" ); 88 $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'monitoring'" );
71 cmp_ok( $res->return_code, "==", 0, "Got a reference to 'monitoring'"); 89 cmp_ok( $res->return_code, "==", 0, "Got a reference to 'monitoring'");
72 90
73 $res = NPTest->testCmd( "./check_http -H $host_tcp_http2 -r 'mONiTORing'" ); 91 $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'mONiTORing'" );
74 cmp_ok( $res->return_code, "==", 2, "Not got 'mONiTORing'"); 92 cmp_ok( $res->return_code, "==", 2, "Not got 'mONiTORing'");
75 like ( $res->output, "/pattern not found/", "Error message says 'pattern not found'"); 93 like ( $res->output, "/pattern not found/", "Error message says 'pattern not found'");
76 94
77 $res = NPTest->testCmd( "./check_http -H $host_tcp_http2 -R 'mONiTORing'" ); 95 $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -R 'mONiTORing'" );
78 cmp_ok( $res->return_code, "==", 0, "But case insensitive doesn't mind 'mONiTORing'"); 96 cmp_ok( $res->return_code, "==", 0, "But case insensitive doesn't mind 'mONiTORing'");
79 97
80 $res = NPTest->testCmd( "./check_http -H $host_tcp_http2 -r 'monitoring' --invert-regex" ); 98 $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'monitoring' --invert-regex" );
81 cmp_ok( $res->return_code, "==", 2, "Invert results work when found"); 99 cmp_ok( $res->return_code, "==", 2, "Invert results work when found");
82 like ( $res->output, "/pattern found/", "Error message says 'pattern found'"); 100 like ( $res->output, "/pattern found/", "Error message says 'pattern found'");
83 101
84 $res = NPTest->testCmd( "./check_http -H $host_tcp_http2 -r 'mONiTORing' --invert-regex" ); 102 $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'mONiTORing' --invert-regex" );
85 cmp_ok( $res->return_code, "==", 0, "And also when not found"); 103 cmp_ok( $res->return_code, "==", 0, "And also when not found");
86} 104}
87SKIP: { 105SKIP: {
88 skip "No internet access", 16 if $internet_access eq "no"; 106 skip "No internet access", 23 if $internet_access eq "no";
89 107
90 $res = NPTest->testCmd( 108 $res = NPTest->testCmd(
91 "./check_http --ssl www.verisign.com" 109 "./$plugin --ssl $host_tls_http"
92 ); 110 );
93 cmp_ok( $res->return_code, '==', 0, "Can read https for www.verisign.com" ); 111 cmp_ok( $res->return_code, '==', 0, "Can read https for $host_tls_http" );
94 112
95 $res = NPTest->testCmd( "./check_http -C 1 --ssl www.verisign.com" ); 113 $res = NPTest->testCmd( "./$plugin -C 1 --ssl $host_tls_http" );
96 cmp_ok( $res->return_code, '==', 0, "Checking certificate for www.verisign.com"); 114 cmp_ok( $res->return_code, '==', 0, "Checking certificate for $host_tls_http");
97 like ( $res->output, "/Certificate 'www.verisign.com' will expire on/", "Output OK" ); 115 like ( $res->output, "/Certificate '$host_tls_cert' will expire on/", "Output OK" );
98 my $saved_cert_output = $res->output; 116 my $saved_cert_output = $res->output;
99 117
100 $res = NPTest->testCmd( "./check_http -C 8000,1 --ssl www.verisign.com" ); 118 $res = NPTest->testCmd( "./$plugin -C 8000,1 --ssl $host_tls_http" );
101 cmp_ok( $res->return_code, '==', 1, "Checking certificate for www.verisign.com"); 119 cmp_ok( $res->return_code, '==', 1, "Checking certificate for $host_tls_http");
102 like ( $res->output, qr/WARNING - Certificate 'www.verisign.com' expires in \d+ day/, "Output Warning" ); 120 like ( $res->output, qr/WARNING - Certificate '$host_tls_cert' expires in \d+ day/, "Output Warning" );
103 121
104 $res = NPTest->testCmd( "./check_http www.verisign.com -C 1" ); 122 $res = NPTest->testCmd( "./$plugin $host_tls_http -C 1" );
105 is( $res->return_code, 0, "Old syntax for cert checking okay" ); 123 is( $res->return_code, 0, "Old syntax for cert checking okay" );
106 is( $res->output, $saved_cert_output, "Same output as new syntax" ); 124 is( $res->output, $saved_cert_output, "Same output as new syntax" );
107 125
108 $res = NPTest->testCmd( "./check_http -H www.verisign.com -C 1" ); 126 $res = NPTest->testCmd( "./$plugin -H $host_tls_http -C 1" );
109 is( $res->return_code, 0, "Updated syntax for cert checking okay" ); 127 is( $res->return_code, 0, "Updated syntax for cert checking okay" );
110 is( $res->output, $saved_cert_output, "Same output as new syntax" ); 128 is( $res->output, $saved_cert_output, "Same output as new syntax" );
111 129
112 $res = NPTest->testCmd( "./check_http -C 1 www.verisign.com" ); 130 $res = NPTest->testCmd( "./$plugin -C 1 $host_tls_http" );
113 cmp_ok( $res->output, 'eq', $saved_cert_output, "--ssl option automatically added"); 131 cmp_ok( $res->output, 'eq', $saved_cert_output, "--ssl option automatically added");
114 132
115 $res = NPTest->testCmd( "./check_http www.verisign.com -C 1" ); 133 $res = NPTest->testCmd( "./$plugin $host_tls_http -C 1" );
116 cmp_ok( $res->output, 'eq', $saved_cert_output, "Old syntax for cert checking still works"); 134 cmp_ok( $res->output, 'eq', $saved_cert_output, "Old syntax for cert checking still works");
117 135
118 # run some certificate checks with faketime 136 # run some certificate checks with faketime
119 SKIP: { 137 SKIP: {
120 skip "No faketime binary found", 12 if !$faketime; 138 skip "No faketime binary found", 7 if !$faketime;
121 $res = NPTest->testCmd("LC_TIME=C TZ=UTC ./check_http -C 1 www.verisign.com"); 139 $res = NPTest->testCmd("LC_TIME=C TZ=UTC ./$plugin -C 1 $host_tls_http");
122 like($res->output, qr/OK - Certificate 'www.verisign.com' will expire on/, "Catch cert output"); 140 like($res->output, qr/OK - Certificate '$host_tls_cert' will expire on/, "Catch cert output");
123 is( $res->return_code, 0, "Catch cert output exit code" ); 141 is( $res->return_code, 0, "Catch cert output exit code" );
124 my($mon,$day,$hour,$min,$sec,$year) = ($res->output =~ /(\w+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\d+)\./); 142 my($mon,$day,$hour,$min,$sec,$year) = ($res->output =~ /(\w+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\d+)/);
125 if(!defined $year) { 143 if(!defined $year) {
126 die("parsing date failed from: ".$res); 144 die("parsing date failed from: ".$res->output);
127 } 145 }
128 my $months = {'Jan' => 0, 'Feb' => 1, 'Mar' => 2, 'Apr' => 3, 'May' => 4, 'Jun' => 5, 'Jul' => 6, 'Aug' => 7, 'Sep' => 8, 'Oct' => 9, 'Nov' => 10, 'Dec' => 11}; 146 my $months = {'Jan' => 0, 'Feb' => 1, 'Mar' => 2, 'Apr' => 3, 'May' => 4, 'Jun' => 5, 'Jul' => 6, 'Aug' => 7, 'Sep' => 8, 'Oct' => 9, 'Nov' => 10, 'Dec' => 11};
129 my $ts = mktime($sec, $min, $hour, $day, $months->{$mon}, $year-1900); 147 my $ts = mktime($sec, $min, $hour, $day, $months->{$mon}, $year-1900);
130 my $time = strftime("%Y-%m-%d %H:%M:%S", localtime($ts)); 148 my $time = strftime("%Y-%m-%d %H:%M:%S", localtime($ts));
131 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts))."' ./check_http -C 1 www.verisign.com"); 149 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts))."' ./$plugin -C 1 $host_tls_http");
132 like($res->output, qr/CRITICAL - Certificate 'www.verisign.com' just expired/, "Output on expire date"); 150 like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' just expired/, "Output on expire date");
133 is( $res->return_code, 2, "Output on expire date" );
134 151
135 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-1))."' ./check_http -C 1 www.verisign.com"); 152 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-1))."' ./$plugin -C 1 $host_tls_http");
136 like($res->output, qr/CRITICAL - Certificate 'www.verisign.com' expires in 0 minutes/, "cert expires in 1 second output"); 153 like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 0 minutes/, "cert expires in 1 second output");
137 is( $res->return_code, 2, "cert expires in 1 second exit code" );
138 154
139 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-120))."' ./check_http -C 1 www.verisign.com"); 155 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-120))."' ./$plugin -C 1 $host_tls_http");
140 like($res->output, qr/CRITICAL - Certificate 'www.verisign.com' expires in 2 minutes/, "cert expires in 2 minutes output"); 156 like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 2 minutes/, "cert expires in 2 minutes output");
141 is( $res->return_code, 2, "cert expires in 2 minutes exit code" );
142 157
143 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-7200))."' ./check_http -C 1 www.verisign.com"); 158 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-7200))."' ./$plugin -C 1 $host_tls_http");
144 like($res->output, qr/CRITICAL - Certificate 'www.verisign.com' expires in 2 hours/, "cert expires in 2 hours output"); 159 like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 2 hours/, "cert expires in 2 hours output");
145 is( $res->return_code, 2, "cert expires in 2 hours exit code" );
146 160
147 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts+1))."' ./check_http -C 1 www.verisign.com"); 161 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts+1))."' ./$plugin -C 1 $host_tls_http");
148 like($res->output, qr/CRITICAL - Certificate 'www.verisign.com' expired on/, "Certificate expired output"); 162 like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expired on/, "Certificate expired output");
149 is( $res->return_code, 2, "Certificate expired exit code" );
150 }; 163 };
151 164
152 $res = NPTest->testCmd( "./check_http --ssl www.verisign.com -E" ); 165 $res = NPTest->testCmd( "./$plugin --ssl $host_tls_http -E" );
153 like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' ); 166 like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' );
154 like ( $res->output, '/time_ssl=[\d\.]+/', 'Extended Performance Data SSL Output OK' ); 167 like ( $res->output, '/time_ssl=[\d\.]+/', 'Extended Performance Data SSL Output OK' );
155 168
156 $res = NPTest->testCmd( 169 $res = NPTest->testCmd(
157 "./check_http --ssl www.e-paycobalt.com" 170 "./$plugin --ssl -H www.e-paycobalt.com"
158 ); 171 );
159 cmp_ok( $res->return_code, "==", 0, "Can read https for www.e-paycobalt.com (uses AES certificate)" ); 172 cmp_ok( $res->return_code, "==", 0, "Can read https for www.e-paycobalt.com (uses AES certificate)" );
160 173
161 174
162 $res = NPTest->testCmd( "./check_http -H www.mozilla.com -u /firefox -f follow" ); 175 $res = NPTest->testCmd( "./$plugin -H www.mozilla.com -u /firefox -f follow" );
163 is( $res->return_code, 0, "Redirection based on location is okay"); 176 is( $res->return_code, 0, "Redirection based on location is okay");
164 177
165 $res = NPTest->testCmd( "./check_http -H www.mozilla.com --extended-perfdata" ); 178 $res = NPTest->testCmd( "./$plugin -H www.mozilla.com --extended-perfdata" );
166 like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' ); 179 like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' );
167} 180}
181
182SKIP: {
183 skip "No internet access or proxy configured", 6 if $internet_access eq "no" or ! $host_tcp_proxy;
184
185 $res = NPTest->testCmd( "./$plugin -I $host_tcp_proxy -p $port_tcp_proxy -u http://$host_tcp_http -e 200,301,302");
186 is( $res->return_code, 0, "Proxy HTTP works");
187 like($res->output, qr/OK: Status line output matched/, "Proxy HTTP Output is sufficent");
188
189 $res = NPTest->testCmd( "./$plugin -I $host_tcp_proxy -p $port_tcp_proxy -H $host_tls_http -S -j CONNECT");
190 is( $res->return_code, 0, "Proxy HTTP CONNECT works");
191 like($res->output, qr/HTTP OK:/, "Proxy HTTP CONNECT output sufficent");
192
193 $res = NPTest->testCmd( "./$plugin -I $host_tcp_proxy -p $port_tcp_proxy -H $host_tls_http -S -j CONNECT:HEAD");
194 is( $res->return_code, 0, "Proxy HTTP CONNECT works with override method");
195 like($res->output, qr/HTTP OK:/, "Proxy HTTP CONNECT output sufficent");
196}
diff --git a/plugins/t/check_imap.t b/plugins/t/check_imap.t
index 9c6eae1..7c74e56 100644
--- a/plugins/t/check_imap.t
+++ b/plugins/t/check_imap.t
@@ -8,17 +8,10 @@ use strict;
8use Test::More tests => 7; 8use Test::More tests => 7;
9use NPTest; 9use NPTest;
10 10
11my $host_tcp_smtp = getTestParameter( "host_tcp_smtp", "NP_HOST_TCP_SMTP", "mailhost", 11my $host_tcp_smtp = getTestParameter("NP_HOST_TCP_SMTP", "A host providing an STMP Service (a mail server)", "mailhost");
12 "A host providing an STMP Service (a mail server)"); 12my $host_tcp_imap = getTestParameter("NP_HOST_TCP_IMAP", "A host providing an IMAP Service (a mail server)", $host_tcp_smtp);
13 13my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1");
14my $host_tcp_imap = getTestParameter( "host_tcp_imap", "NP_HOST_TCP_IMAP", $host_tcp_smtp, 14my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost");
15 "A host providing an IMAP Service (a mail server)");
16
17my $host_nonresponsive = getTestParameter( "host_nonresponsive", "NP_HOST_NONRESPONSIVE", "10.0.0.1",
18 "The hostname of system not responsive to network requests" );
19
20my $hostname_invalid = getTestParameter( "hostname_invalid", "NP_HOSTNAME_INVALID", "nosuchhost",
21 "An invalid (not known to DNS) hostname" );
22 15
23my $t; 16my $t;
24 17
diff --git a/plugins/t/check_jabber.t b/plugins/t/check_jabber.t
index 7a708d5..fcdae17 100644
--- a/plugins/t/check_jabber.t
+++ b/plugins/t/check_jabber.t
@@ -10,23 +10,9 @@ use NPTest;
10 10
11plan tests => 10; 11plan tests => 10;
12 12
13my $host_tcp_jabber = getTestParameter( 13my $host_tcp_jabber = getTestParameter("NP_HOST_TCP_JABBER", "A host providing the Jabber Service", "jabber.de");
14 "NP_HOST_TCP_JABBER", 14my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1");
15 "A host providing the Jabber Service", 15my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost");
16 "jabber.org"
17 );
18
19my $host_nonresponsive = getTestParameter(
20 "NP_HOST_NONRESPONSIVE",
21 "The hostname of system not responsive to network requests",
22 "10.0.0.1",
23 );
24
25my $hostname_invalid = getTestParameter(
26 "NP_HOSTNAME_INVALID",
27 "An invalid (not known to DNS) hostname",
28 "nosuchhost",
29 );
30 16
31 17
32my $jabberOK = '/JABBER OK\s-\s\d+\.\d+\ssecond response time on '.$host_tcp_jabber.' port 5222/'; 18my $jabberOK = '/JABBER OK\s-\s\d+\.\d+\ssecond response time on '.$host_tcp_jabber.' port 5222/';
diff --git a/plugins/t/check_ldap.t b/plugins/t/check_ldap.t
index b8944d4..b8a4a76 100644
--- a/plugins/t/check_ldap.t
+++ b/plugins/t/check_ldap.t
@@ -9,19 +9,10 @@ use warnings;
9use Test::More; 9use Test::More;
10use NPTest; 10use NPTest;
11 11
12my $host_tcp_ldap = getTestParameter("NP_HOST_TCP_LDAP", 12my $host_tcp_ldap = getTestParameter("NP_HOST_TCP_LDAP", "A host providing the LDAP Service", "localhost");
13 "A host providing the LDAP Service", 13my $ldap_base_dn = getTestParameter("NP_LDAP_BASE_DN", "A base dn for the LDAP Service", "cn=admin");
14 "localhost" ); 14my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1");
15 15my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost");
16my $ldap_base_dn = getTestParameter("NP_LDAP_BASE_DN",
17 "A base dn for the LDAP Service",
18 "cn=admin" );
19
20my $host_nonresponsive = getTestParameter("host_nonresponsive", "NP_HOST_NONRESPONSIVE", "10.0.0.1",
21 "The hostname of system not responsive to network requests" );
22
23my $hostname_invalid = getTestParameter("hostname_invalid", "NP_HOSTNAME_INVALID", "nosuchhost",
24 "An invalid (not known to DNS) hostname" );
25 16
26my($result, $cmd); 17my($result, $cmd);
27my $command = './check_ldap'; 18my $command = './check_ldap';
diff --git a/plugins/t/check_mysql.t b/plugins/t/check_mysql.t
index 28cd4cd..e426bf5 100644
--- a/plugins/t/check_mysql.t
+++ b/plugins/t/check_mysql.t
@@ -21,30 +21,11 @@ plan skip_all => "check_mysql not compiled" unless (-x "check_mysql");
21plan tests => 15; 21plan tests => 15;
22 22
23my $bad_login_output = '/Access denied for user /'; 23my $bad_login_output = '/Access denied for user /';
24my $mysqlserver = getTestParameter( 24my $mysqlserver = getTestParameter("NP_MYSQL_SERVER", "A MySQL Server hostname or IP with no slaves setup");
25 "NP_MYSQL_SERVER", 25my $mysqlsocket = getTestParameter("NP_MYSQL_SOCKET", "Full path to a MySQL Server socket with no slaves setup");
26 "A MySQL Server hostname or IP with no slaves setup" 26my $mysql_login_details = getTestParameter("NP_MYSQL_LOGIN_DETAILS", "Command line parameters to specify login access (requires REPLICATION CLIENT privleges)", "-u test -ptest");
27 ); 27my $with_slave = getTestParameter("NP_MYSQL_WITH_SLAVE", "MySQL server with slaves setup");
28my $mysqlsocket = getTestParameter( 28my $with_slave_login = getTestParameter("NP_MYSQL_WITH_SLAVE_LOGIN", "Login details for server with slave (requires REPLICATION CLIENT privleges)", $mysql_login_details || "-u test -ptest");
29 "NP_MYSQL_SOCKET",
30 "Full path to a MySQL Server socket with no slaves setup"
31 );
32my $mysql_login_details = getTestParameter(
33 "MYSQL_LOGIN_DETAILS",
34 "Command line parameters to specify login access (requires " .
35 "REPLICATION CLIENT privleges)",
36 "-u test -ptest",
37 );
38my $with_slave = getTestParameter(
39 "NP_MYSQL_WITH_SLAVE",
40 "MySQL server with slaves setup"
41 );
42my $with_slave_login = getTestParameter(
43 "NP_MYSQL_WITH_SLAVE_LOGIN",
44 "Login details for server with slave (requires REPLICATION CLIENT " .
45 "privleges)",
46 $mysql_login_details || "-u test -ptest"
47 );
48 29
49my $result; 30my $result;
50 31
diff --git a/plugins/t/check_mysql_query.t b/plugins/t/check_mysql_query.t
index 407af88..96899ac 100644
--- a/plugins/t/check_mysql_query.t
+++ b/plugins/t/check_mysql_query.t
@@ -17,15 +17,8 @@ use vars qw($tests);
17 17
18plan skip_all => "check_mysql_query not compiled" unless (-x "check_mysql_query"); 18plan skip_all => "check_mysql_query not compiled" unless (-x "check_mysql_query");
19 19
20my $mysqlserver = getTestParameter( 20my $mysqlserver = getTestParameter("NP_MYSQL_SERVER", "A MySQL Server with no slaves setup");
21 "NP_MYSQL_SERVER", 21my $mysql_login_details = getTestParameter("NP_MYSQL_LOGIN_DETAILS", "Command line parameters to specify login access", "-u user -ppw -d db");
22 "A MySQL Server with no slaves setup"
23 );
24my $mysql_login_details = getTestParameter(
25 "MYSQL_LOGIN_DETAILS",
26 "Command line parameters to specify login access",
27 "-u user -ppw -d db",
28 );
29my $result; 22my $result;
30 23
31if (! $mysqlserver) { 24if (! $mysqlserver) {
diff --git a/plugins/t/check_snmp.t b/plugins/t/check_snmp.t
index aefd872..f2f218f 100644
--- a/plugins/t/check_snmp.t
+++ b/plugins/t/check_snmp.t
@@ -10,23 +10,17 @@ use NPTest;
10 10
11BEGIN { 11BEGIN {
12 plan skip_all => 'check_snmp is not compiled' unless -x "./check_snmp"; 12 plan skip_all => 'check_snmp is not compiled' unless -x "./check_snmp";
13 plan tests => 61; 13 plan tests => 63;
14} 14}
15 15
16my $res; 16my $res;
17 17
18my $host_snmp = getTestParameter( "host_snmp", "NP_HOST_SNMP", "localhost", 18my $host_snmp = getTestParameter("NP_HOST_SNMP", "A host providing an SNMP Service", "localhost");
19 "A host providing an SNMP Service"); 19my $snmp_community = getTestParameter("NP_SNMP_COMMUNITY", "The SNMP Community string for SNMP Testing (assumes snmp v1)", "public");
20my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1");
21my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost");
22my $user_snmp = getTestParameter("NP_SNMP_USER", "An SNMP user", "auth_md5");
20 23
21my $snmp_community = getTestParameter( "snmp_community", "NP_SNMP_COMMUNITY", "public",
22 "The SNMP Community string for SNMP Testing (assumes snmp v1)" );
23
24my $host_nonresponsive = getTestParameter( "host_nonresponsive", "NP_HOST_NONRESPONSIVE", "10.0.0.1",
25 "The hostname of system not responsive to network requests" );
26
27my $hostname_invalid = getTestParameter( "hostname_invalid", "NP_HOSTNAME_INVALID", "nosuchhost",
28 "An invalid (not known to DNS) hostname" );
29my $user_snmp = getTestParameter( "user_snmp", "NP_SNMP_USER", "auth_md5", "An SNMP user");
30 24
31$res = NPTest->testCmd( "./check_snmp -t 1" ); 25$res = NPTest->testCmd( "./check_snmp -t 1" );
32is( $res->return_code, 3, "No host name" ); 26is( $res->return_code, 3, "No host name" );
@@ -45,7 +39,7 @@ is( $res->return_code, 3, "Invalid protocol" );
45like( $res->output, "/check_snmp: Invalid SNMP version - 3c/" ); 39like( $res->output, "/check_snmp: Invalid SNMP version - 3c/" );
46 40
47SKIP: { 41SKIP: {
48 skip "no snmp host defined", 48 if ( ! $host_snmp ); 42 skip "no snmp host defined", 50 if ( ! $host_snmp );
49 43
50 $res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -w 1: -c 1:"); 44 $res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0 -w 1: -c 1:");
51 cmp_ok( $res->return_code, '==', 0, "Exit OK when querying uptime" ); 45 cmp_ok( $res->return_code, '==', 0, "Exit OK when querying uptime" );
@@ -153,6 +147,10 @@ SKIP: {
153 $res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0"); 147 $res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o system.sysUpTime.0");
154 cmp_ok( $res->return_code, '==', 0, "Timetick used as a string"); 148 cmp_ok( $res->return_code, '==', 0, "Timetick used as a string");
155 like($res->output, '/^SNMP OK - Timeticks:\s\(\d+\)\s+(?:\d+ days?,\s+)?\d+:\d+:\d+\.\d+\s.*$/', "Timetick used as a string, result printed rather than parsed"); 149 like($res->output, '/^SNMP OK - Timeticks:\s\(\d+\)\s+(?:\d+ days?,\s+)?\d+:\d+:\d+\.\d+\s.*$/', "Timetick used as a string, result printed rather than parsed");
150
151 $res = NPTest->testCmd( "./check_snmp -H $host_snmp -C $snmp_community -o HOST-RESOURCES-MIB::hrSWRunName.1");
152 cmp_ok( $res->return_code, '==', 0, "snmp response without datatype");
153 like( $res->output, '/^SNMP OK - "(systemd|init)" \| $/', "snmp response without datatype" );
156} 154}
157 155
158SKIP: { 156SKIP: {
diff --git a/plugins/t/check_ssh.t b/plugins/t/check_ssh.t
index 8008349..a5cd23c 100644
--- a/plugins/t/check_ssh.t
+++ b/plugins/t/check_ssh.t
@@ -9,17 +9,9 @@ use Test::More;
9use NPTest; 9use NPTest;
10 10
11# Required parameters 11# Required parameters
12my $ssh_host = getTestParameter("NP_SSH_HOST", 12my $ssh_host = getTestParameter("NP_SSH_HOST", "A host providing SSH service", "localhost");
13 "A host providing SSH service", 13my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1" );
14 "localhost"); 14my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost" );
15
16my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE",
17 "The hostname of system not responsive to network requests",
18 "10.0.0.1" );
19
20my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID",
21 "An invalid (not known to DNS) hostname",
22 "nosuchhost" );
23 15
24 16
25plan skip_all => "SSH_HOST must be defined" unless $ssh_host; 17plan skip_all => "SSH_HOST must be defined" unless $ssh_host;
diff --git a/plugins/t/check_tcp.t b/plugins/t/check_tcp.t
index f996685..cb4de53 100644
--- a/plugins/t/check_tcp.t
+++ b/plugins/t/check_tcp.t
@@ -15,18 +15,11 @@ BEGIN {
15} 15}
16 16
17 17
18my $host_tcp_http = getTestParameter( "host_tcp_http", "NP_HOST_TCP_HTTP", "localhost", 18my $host_tcp_http = getTestParameter("NP_HOST_TCP_HTTP", "A host providing the HTTP Service (a web server)", "localhost");
19 "A host providing the HTTP Service (a web server)" ); 19my $host_tls_http = getTestParameter("NP_HOST_TLS_HTTP", "A host providing the HTTPS Service (a tls web server)", "localhost");
20 20my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1");
21my $host_nonresponsive = getTestParameter( "host_nonresponsive", "NP_HOST_NONRESPONSIVE", "10.0.0.1", 21my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost");
22 "The hostname of system not responsive to network requests" ); 22my $internet_access = getTestParameter("NP_INTERNET_ACCESS", "Is this system directly connected to the internet?", "yes");
23
24my $hostname_invalid = getTestParameter( "hostname_invalid", "NP_HOSTNAME_INVALID", "nosuchhost",
25 "An invalid (not known to DNS) hostname" );
26
27my $internet_access = getTestParameter( "NP_INTERNET_ACCESS",
28 "Is this system directly connected to the internet?",
29 "yes");
30 23
31my $successOutput = '/^TCP OK\s-\s+[0-9]?\.?[0-9]+ second response time on port [0-9]+/'; 24my $successOutput = '/^TCP OK\s-\s+[0-9]?\.?[0-9]+ second response time on port [0-9]+/';
32 25
@@ -42,10 +35,10 @@ $t += checkCmd( "./check_tcp $host_tcp_http -p 81 -wt 0 -ct 0 -to 1", 2
42$t += checkCmd( "./check_tcp $host_nonresponsive -p 80 -wt 0 -ct 0 -to 1", 2 ); 35$t += checkCmd( "./check_tcp $host_nonresponsive -p 80 -wt 0 -ct 0 -to 1", 2 );
43$t += checkCmd( "./check_tcp $hostname_invalid -p 80 -wt 0 -ct 0 -to 1", 2 ); 36$t += checkCmd( "./check_tcp $hostname_invalid -p 80 -wt 0 -ct 0 -to 1", 2 );
44if($internet_access ne "no") { 37if($internet_access ne "no") {
45 $t += checkCmd( "./check_tcp -S -D 1 -H www.verisign.com -p 443", 0 ); 38 $t += checkCmd( "./check_tcp -S -D 1 -H $host_tls_http -p 443", 0 );
46 $t += checkCmd( "./check_tcp -S -D 9000,1 -H www.verisign.com -p 443", 1 ); 39 $t += checkCmd( "./check_tcp -S -D 9000,1 -H $host_tls_http -p 443", 1 );
47 $t += checkCmd( "./check_tcp -S -D 9000 -H www.verisign.com -p 443", 1 ); 40 $t += checkCmd( "./check_tcp -S -D 9000 -H $host_tls_http -p 443", 1 );
48 $t += checkCmd( "./check_tcp -S -D 9000,8999 -H www.verisign.com -p 443", 2 ); 41 $t += checkCmd( "./check_tcp -S -D 9000,8999 -H $host_tls_http -p 443", 2 );
49} 42}
50 43
51# Need the \r\n to make it more standards compliant with web servers. Need the various quotes 44# Need the \r\n to make it more standards compliant with web servers. Need the various quotes
diff --git a/plugins/t/check_time.t b/plugins/t/check_time.t
index 961f56e..92c2f89 100644
--- a/plugins/t/check_time.t
+++ b/plugins/t/check_time.t
@@ -11,14 +11,9 @@ use NPTest;
11use vars qw($tests); 11use vars qw($tests);
12BEGIN {$tests = 8; plan tests => $tests} 12BEGIN {$tests = 8; plan tests => $tests}
13 13
14my $host_udp_time = getTestParameter( "host_udp_time", "NP_HOST_UDP_TIME", "localhost", 14my $host_udp_time = getTestParameter("NP_HOST_UDP_TIME", "A host providing the UDP Time Service", "localhost");
15 "A host providing the UDP Time Service" ); 15my $host_nonresponsive = getTestParameter("NP_HOST_NONRESPONSIVE", "The hostname of system not responsive to network requests", "10.0.0.1");
16 16my $hostname_invalid = getTestParameter("NP_HOSTNAME_INVALID", "An invalid (not known to DNS) hostname", "nosuchhost");
17my $host_nonresponsive = getTestParameter( "host_nonresponsive", "NP_HOST_NONRESPONSIVE", "10.0.0.1",
18 "The hostname of system not responsive to network requests" );
19
20my $hostname_invalid = getTestParameter( "hostname_invalid", "NP_HOSTNAME_INVALID", "nosuchhost",
21 "An invalid (not known to DNS) hostname" );
22 17
23my $successOutput = '/^TIME OK - [0-9]+ second time difference/'; 18my $successOutput = '/^TIME OK - [0-9]+ second time difference/';
24 19
diff --git a/plugins/t/check_udp.t b/plugins/t/check_udp.t
index 1f6fee7..6c47d09 100644
--- a/plugins/t/check_udp.t
+++ b/plugins/t/check_udp.t
@@ -34,12 +34,12 @@ my $nc;
34if(system("which nc.traditional >/dev/null 2>&1") == 0) { 34if(system("which nc.traditional >/dev/null 2>&1") == 0) {
35 $nc = 'nc.traditional -w 3 -l -u -p 3333'; 35 $nc = 'nc.traditional -w 3 -l -u -p 3333';
36} 36}
37elsif(system("which netcat >/dev/null 2>&1") == 0) {
38 $nc = 'netcat -w 3 -l -u -p 3333';
39}
40elsif(system("which nc >/dev/null 2>&1") == 0) { 37elsif(system("which nc >/dev/null 2>&1") == 0) {
41 $nc = 'nc -w 3 -l -u -4 localhost 3333'; 38 $nc = 'nc -w 3 -l -u -4 localhost 3333';
42} 39}
40elsif(system("which netcat >/dev/null 2>&1") == 0) {
41 $nc = 'netcat -w 3 -l -u -p 3333';
42}
43 43
44SKIP: { 44SKIP: {
45 skip "solaris netcat does not listen to udp", 6 if $^O eq 'solaris'; 45 skip "solaris netcat does not listen to udp", 6 if $^O eq 'solaris';
diff --git a/plugins/t/check_users.t b/plugins/t/check_users.t
index 39044bb..088f3b5 100644
--- a/plugins/t/check_users.t
+++ b/plugins/t/check_users.t
@@ -13,7 +13,7 @@ use Test;
13use NPTest; 13use NPTest;
14 14
15use vars qw($tests); 15use vars qw($tests);
16BEGIN {$tests = 4; plan tests => $tests} 16BEGIN {$tests = 8; plan tests => $tests}
17 17
18my $successOutput = '/^USERS OK - [0-9]+ users currently logged in/'; 18my $successOutput = '/^USERS OK - [0-9]+ users currently logged in/';
19my $failureOutput = '/^USERS CRITICAL - [0-9]+ users currently logged in/'; 19my $failureOutput = '/^USERS CRITICAL - [0-9]+ users currently logged in/';
@@ -22,6 +22,8 @@ my $t;
22 22
23$t += checkCmd( "./check_users 1000 1000", 0, $successOutput ); 23$t += checkCmd( "./check_users 1000 1000", 0, $successOutput );
24$t += checkCmd( "./check_users 0 0", 2, $failureOutput ); 24$t += checkCmd( "./check_users 0 0", 2, $failureOutput );
25$t += checkCmd( "./check_users -w 0:1000 -c 0:1000", 0, $successOutput );
26$t += checkCmd( "./check_users -w 0:0 -c 0:0", 2, $failureOutput );
25 27
26exit(0) if defined($Test::Harness::VERSION); 28exit(0) if defined($Test::Harness::VERSION);
27exit($tests - $t); 29exit($tests - $t);
diff --git a/plugins/tests/certs/expired-cert.pem b/plugins/tests/certs/expired-cert.pem
index 40324cf..77a9166 100644
--- a/plugins/tests/certs/expired-cert.pem
+++ b/plugins/tests/certs/expired-cert.pem
@@ -1,21 +1,24 @@
1-----BEGIN CERTIFICATE----- 1-----BEGIN CERTIFICATE-----
2MIIDYzCCAsygAwIBAgIJAJISzcX71f5pMA0GCSqGSIb3DQEBBAUAMH8xCzAJBgNV 2MIIEETCCAvmgAwIBAgIUFDsP6WnV/uqeQMpD/DYSqouE13kwDQYJKoZIhvcNAQEL
3BAYTAlVLMRMwEQYDVQQIEwpEZXJieXNoaXJlMQ8wDQYDVQQHEwZCZWxwZXIxFzAV 3BQAwgZcxCzAJBgNVBAYTAkRFMRAwDgYDVQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZN
4BgNVBAoTDk5hZ2lvcyBQbHVnaW5zMREwDwYDVQQDEwhUb24gVm9vbjEeMBwGCSqG 4dW5pY2gxGzAZBgNVBAoMEk1vbml0b3JpbmcgUGx1Z2luczEbMBkGA1UEAwwSTW9u
5SIb3DQEJARYPdG9udm9vbkBtYWMuY29tMB4XDTA5MDMwNjAwMTMxNVoXDTA5MDMw 5aXRvcmluZyBQbHVnaW5zMSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9yaW5n
6NTAwMTMxNlowfzELMAkGA1UEBhMCVUsxEzARBgNVBAgTCkRlcmJ5c2hpcmUxDzAN 6LXBsdWdpbnMub3JnMB4XDTA4MDEwMTExMDAyNloXDTA4MDEwMjExMDAyNlowgZcx
7BgNVBAcTBkJlbHBlcjEXMBUGA1UEChMOTmFnaW9zIFBsdWdpbnMxETAPBgNVBAMT 7CzAJBgNVBAYTAkRFMRAwDgYDVQQIDAdCYXZhcmlhMQ8wDQYDVQQHDAZNdW5pY2gx
8CFRvbiBWb29uMR4wHAYJKoZIhvcNAQkBFg90b252b29uQG1hYy5jb20wgZ8wDQYJ 8GzAZBgNVBAoMEk1vbml0b3JpbmcgUGx1Z2luczEbMBkGA1UEAwwSTW9uaXRvcmlu
9KoZIhvcNAQEBBQADgY0AMIGJAoGBAOQHP4JnzACi4q6quXAiK+gTSffG6yyjEV+K 9ZyBQbHVnaW5zMSswKQYJKoZIhvcNAQkBFhxkZXZlbEBtb25pdG9yaW5nLXBsdWdp
10iyutRgBF2MdF03X5ls0wENw/5fnMTrHynl4XoGoV/rD4CR2hGT0m7dv7Vu0MRLlP 10bnMub3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyeHKwKFjJWUX
11J1SCiFeMuQS30zzLMJr0A7IW869qRlKQmzxs1JT6XDbSoNQuF154zoxwNsKlMjoX 11YHKsisypUf9dHlIPQAISyGP1BX6UL26ZLvE6kKbx3LFQ9W2POGoQWlzFiB1soGeV
12tJSHN2YpAgMBAAGjgeYwgeMwHQYDVR0OBBYEFHWjM9OQldrDLMcAfPnUVfGxlzOp 12WDd0U0JtWdCKmOXWdcXpupQlTSUtRCMDQkfqLN8GR5TBTd73rezp5mz08nMfLwu0
13MIGzBgNVHSMEgaswgaiAFHWjM9OQldrDLMcAfPnUVfGxlzOpoYGEpIGBMH8xCzAJ 13p5VQ191Ui8JHFgrAOalAn8Uw5De8vj4VmTXmU5NJ2UFoC0ddU/Th/lwRCayHc1cn
14BgNVBAYTAlVLMRMwEQYDVQQIEwpEZXJieXNoaXJlMQ8wDQYDVQQHEwZCZWxwZXIx 14MVq2F7c/uhMUUQYNBmJy0pxoHawp+j9NKl/xIYsjgQNgahQyNuswuGHjaEwhPu+7
15FzAVBgNVBAoTDk5hZ2lvcyBQbHVnaW5zMREwDwYDVQQDEwhUb24gVm9vbjEeMBwG 15G03XsW4ehu+H1898M/MkSln6LQAU1syoJ8ypPM8tV+zgx4uwj7udnZ2hceN95uW7
16CSqGSIb3DQEJARYPdG9udm9vbkBtYWMuY29tggkAkhLNxfvV/mkwDAYDVR0TBAUw 160PWg5DQyUwIDAQABo1MwUTAdBgNVHQ4EFgQUt9ps3KJ1XiMuy/ijFBjMzf6jgwkw
17AwEB/zANBgkqhkiG9w0BAQQFAAOBgQDHjoXoGwBamCiNplTt93jH/TO08RATdZP5 17HwYDVR0jBBgwFoAUt9ps3KJ1XiMuy/ijFBjMzf6jgwkwDwYDVR0TAQH/BAUwAwEB
1845hlxv2+PKCjjTiFa2mjAvopFiqmYsr40XYEmpeYMiaOzOW5rBjtqBAT/JJWyfda 18/zANBgkqhkiG9w0BAQsFAAOCAQEAVPBZwMHbrnHFbmhbcPuvYd5cxk0uSVNAUzsl
19SCmj3swqyKus63rv/iuokIhZzBdhbB+eOJJrmwT2SEc5KdRaipH0QAGF1nZAAGzo 192biCq5P+ZHo10VHGygXtdV4utqk/IrAt2u5qSxycWPStCtAgTd3Q8ncfjOkaHM4z
206xW7hkzYog== 202bxTkhLyQeU8NWPuDBqDszo2GOaFTv+lm36LEKiAfqB1tjQVePSkycdrWIhkamBV
21EgMe6uHLdU7QQk1ajQfrBdakN1beqki/dKieA6gm+XF/QS4SSYINmsHB/2X5cT9U
22b/KMB8xurCnuJQuk1P4VsSkJCOSeHjWZgK9pKNdsIJZr4wDVfhjQgU0XT6xakSf7
23eCaHtO0VKsbLZoiTmpxidjsdYiXyeKYIQNtUpTjyJ5V/cZsq9w==
21-----END CERTIFICATE----- 24-----END CERTIFICATE-----
diff --git a/plugins/tests/certs/expired-key.pem b/plugins/tests/certs/expired-key.pem
index af0e24d..c1510b2 100644
--- a/plugins/tests/certs/expired-key.pem
+++ b/plugins/tests/certs/expired-key.pem
@@ -1,15 +1,28 @@
1-----BEGIN RSA PRIVATE KEY----- 1-----BEGIN PRIVATE KEY-----
2MIICXAIBAAKBgQDkBz+CZ8wAouKuqrlwIivoE0n3xussoxFfiosrrUYARdjHRdN1 2MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDJ4crAoWMlZRdg
3+ZbNMBDcP+X5zE6x8p5eF6BqFf6w+AkdoRk9Ju3b+1btDES5TydUgohXjLkEt9M8 3cqyKzKlR/10eUg9AAhLIY/UFfpQvbpku8TqQpvHcsVD1bY84ahBaXMWIHWygZ5VY
4yzCa9AOyFvOvakZSkJs8bNSU+lw20qDULhdeeM6McDbCpTI6F7SUhzdmKQIDAQAB 4N3RTQm1Z0IqY5dZ1xem6lCVNJS1EIwNCR+os3wZHlMFN3vet7OnmbPTycx8vC7Sn
5AoGARgI3rHjjuDpKMGg4IMZNBqaNaiZHY9/44IVvrww21rSbFqtIfgsQEpU0R/rS 5lVDX3VSLwkcWCsA5qUCfxTDkN7y+PhWZNeZTk0nZQWgLR11T9OH+XBEJrIdzVycx
6R7xDWPztRGQqmwd/t6OfYNpqHbjO1MWzasVBVnzue5P59Y1xy1h0LZF8+a9GY++0 6WrYXtz+6ExRRBg0GYnLSnGgdrCn6P00qX/EhiyOBA2BqFDI26zC4YeNoTCE+77sb
7uAGUC24jsXSmypNVzoX+ZKyinA3oYV/etdPYx1W8Ms5XIzUCQQD7xwhMuLok6Kbq 7Tdexbh6G74fXz3wz8yRKWfotABTWzKgnzKk8zy1X7ODHi7CPu52dnaFx433m5bvQ
8UEgiSfBTbx+haP3IiqqMF14z8QoEyD3jchydNaXEYdQxN8jEl2aPrMqTc6x8Jq4/ 89aDkNDJTAgMBAAECggEACrLFfNnQmD24NGs/S4e2/VpsA9xTZI/3kNkDNgxULANP
9ai0OkB+fAkEA59pAmN81HylV7+CsVjLOSbJqzau7NDxSs2uutxhHZRwz0e25wVer 9aNZtxRajwI9A/BCXQ2UTgsZhzWnJxOJYXrlpl7PweY78mUesysb3MOUC6QisUm0M
10fA03l08u0ebC/TDHkmHV6ikCryM5HU2FNwJAVZJFzd2S1myEHmr+uTisB49jDrbi 10kimfdktHWOnAKLFFLNleN9DUVjjVkTeslijqhNX80f80py1grG2UuCLKCX4OqYIm
11WkBWypo+mCS6JPnxntXvx7auClq9haTSBY73eqldiFPuMZvr6P2rJqHxPQJBAOTM 11qACE8TMmSZLz42AO96TndNtKplQ8LuGLEmByW95wEfhx3Gm4ckkL7qII/U3DnQXr
12quaxjti7kATy8N73sD9mBKQGju1TgkFxSK+DFCGhnTnToXY9MAtxd6SoDYoyccYu 120T+3xLaj+eNJzYDpIFZiw4sNzOuAyCz+4Cc4sPDuMnzquXF+enpkemoycC1RmEpG
13dyPrzJAR/IYc+mYCdC0CQDKlZuMPVXEgvGaQapzMQ++5yJRvMZF4tWvONBs0OCE9 13KIDTwmFsc8TrbGV0qifC6fsCrDivdYLqL7R/q3IBQQKBgQDmfvO3VYTEKY8NA+AT
14QYarsTi5M20cymMBXHOLZIjqwsni4G/C9kqJSvC75Vg= 145s6+7NTxRsXxJUCEhCNBWimSH3EzmBAvrodLY6A0oYg8i81bgNX1I9GPVXJZ/QA7
15-----END RSA PRIVATE KEY----- 15ukd84HUIQoGS5Usmo4rp+kz4P6KkLXDemZtWPU5GXxicfajHRQlkbW6St6SpV7IS
16ibJcDADeoiaPL1xvue1ToP/LoQKBgQDgOFHjYpep00gabvjXfYW7vhrg1vVwaKUM
17rf0+UW8Exk4nbBw0eEC2YjxIwzdktlkdbzGaXYULnhg8GnfxYesMOpCLPw1JdB8o
18ixETAFpW5bKrUsjEFRUGhzWnsCSFIQ4smpmtGLTxOQ8AkoDdORY5Z+Wv7JtFF6Do
19PSoblckZcwKBgB3TD3YJesRnHDty5OuuUdIikuslXTd2uoJrFqS+JeLibqNeabnB
20u3/lxDULMbWj4U6VvRmbKOKDC+jY887Gq7lc0cff0yROxwqY3sCnwo3crg7QUmp7
21Nb5S8G3qoCSfndcq96wm/Me/O28uCbycVJfUdchY8uRUHIHYbP0FOBQBAoGBAMgh
22fPX4imaKr1DovDObVkK87EDDnU84GBm5MtDs3qrkVd3aIVK0Aw7HoAdSN58tI12i
23YiPmVVqJQhhjh6tsOuAvZdTj8ngdrbICbrsHFZt6an+A5LIgHyQ0iy+hiPdLCdvG
24ImTeKKMmyr04Bs1upueWVO0xw2VoMbcY4Py+NUEBAoGASQqedfCSKGLT+5lLZrhP
25CbFVMmswEPjBcRb1trcuA09vfExn9FfUNFnnw3i9miprED5kufvAjb+6nduXizKg
267HQYHCwVvakgtXgbiDMaNgYZcjWm+MdnfiwLJjJTO3DfI1JF2PJ8y9R95DPlAkDm
27xH3OV8KV4UiTEVxS7ksmGzY=
28-----END PRIVATE KEY-----
diff --git a/plugins/tests/certs/server-cert.pem b/plugins/tests/certs/server-cert.pem
index 549e4f7..b84b91d 100644
--- a/plugins/tests/certs/server-cert.pem
+++ b/plugins/tests/certs/server-cert.pem
@@ -1,21 +1,24 @@
1-----BEGIN CERTIFICATE----- 1-----BEGIN CERTIFICATE-----
2MIIDYzCCAsygAwIBAgIJAL8LkpNwzYdxMA0GCSqGSIb3DQEBBAUAMH8xCzAJBgNV 2MIIEBjCCAu6gAwIBAgIJANbQ5QQrKhUGMA0GCSqGSIb3DQEBCwUAMIGXMQswCQYD
3BAYTAlVLMRMwEQYDVQQIEwpEZXJieXNoaXJlMQ8wDQYDVQQHEwZCZWxwZXIxFzAV 3VQQGEwJERTEQMA4GA1UECAwHQmF2YXJpYTEPMA0GA1UEBwwGTXVuaWNoMRswGQYD
4BgNVBAoTDk5hZ2lvcyBQbHVnaW5zMREwDwYDVQQDEwhUb24gVm9vbjEeMBwGCSqG 4VQQKDBJNb25pdG9yaW5nIFBsdWdpbnMxGzAZBgNVBAMMEk1vbml0b3JpbmcgUGx1
5SIb3DQEJARYPdG9udm9vbkBtYWMuY29tMB4XDTA5MDMwNTIxNDEyOFoXDTE5MDMw 5Z2luczErMCkGCSqGSIb3DQEJARYcZGV2ZWxAbW9uaXRvcmluZy1wbHVnaW5zLm9y
6MzIxNDEyOFowfzELMAkGA1UEBhMCVUsxEzARBgNVBAgTCkRlcmJ5c2hpcmUxDzAN 6ZzAeFw0xOTAyMTkxNTMxNDRaFw0yOTAyMTYxNTMxNDRaMIGXMQswCQYDVQQGEwJE
7BgNVBAcTBkJlbHBlcjEXMBUGA1UEChMOTmFnaW9zIFBsdWdpbnMxETAPBgNVBAMT 7RTEQMA4GA1UECAwHQmF2YXJpYTEPMA0GA1UEBwwGTXVuaWNoMRswGQYDVQQKDBJN
8CFRvbiBWb29uMR4wHAYJKoZIhvcNAQkBFg90b252b29uQG1hYy5jb20wgZ8wDQYJ 8b25pdG9yaW5nIFBsdWdpbnMxGzAZBgNVBAMMEk1vbml0b3JpbmcgUGx1Z2luczEr
9KoZIhvcNAQEBBQADgY0AMIGJAoGBAKcWMBtNtfY8vZXk0SN6/EYTVN/LOvaOSegy 9MCkGCSqGSIb3DQEJARYcZGV2ZWxAbW9uaXRvcmluZy1wbHVnaW5zLm9yZzCCASIw
10oVdLoGwuwjagk+XmCzvCqHZRp8lnCLay7AO8AQI7TSN02ihCcSrgGA9OT+HciIJ1 10DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKgV2yp8pQvJuN+aJGdAe6Hd0tja
11l5/kEYUAuA1PR6YKK/T713zUAlMzy2tsugx5+xSsSEwsXkmne52jJiG/wuE5CLT0 11uteCPcNIcM92WLOF69TLTSYon1XDon4tHTh4Z5d4lD8bfsGzFVBmDSgWidhAUf+v
129pF8HQqHAgMBAAGjgeYwgeMwHQYDVR0OBBYEFGioSPQ/rdE19+zaeY2YvHTXlUDI 12EqEXwbp293ej/Frc0pXCvmrz6kI1tWrLtQhL/VdbxFYxhV7JjKb+PY3SxGFpSLPe
13MIGzBgNVHSMEgaswgaiAFGioSPQ/rdE19+zaeY2YvHTXlUDIoYGEpIGBMH8xCzAJ 13PQ/5SwVndv7rZIwcjseL22K5Uy2TIrkgzzm2pRs/IvoxRybYr/+LGoHyrtJC6AO8
14BgNVBAYTAlVLMRMwEQYDVQQIEwpEZXJieXNoaXJlMQ8wDQYDVQQHEwZCZWxwZXIx 14ylp8A/etL0gwtUvRnrnZeTQ2pA1uZ5QN3anTL8JP/ZRZYNegIkaawqMtTKbhM6pi
15FzAVBgNVBAoTDk5hZ2lvcyBQbHVnaW5zMREwDwYDVQQDEwhUb24gVm9vbjEeMBwG 15u3/4a3Uppvt0y7vmGfQlYejxCpICnMrvHMpw8L58zv/98AbCGjDU3UwCt6MCAwEA
16CSqGSIb3DQEJARYPdG9udm9vbkBtYWMuY29tggkAvwuSk3DNh3EwDAYDVR0TBAUw 16AaNTMFEwHQYDVR0OBBYEFG/UH6nGYPlVcM75UXzXBF5GZyrcMB8GA1UdIwQYMBaA
17AwEB/zANBgkqhkiG9w0BAQQFAAOBgQCdqasaIO6JiV5ONFG6Tr1++85UfEdZKMUX 17FG/UH6nGYPlVcM75UXzXBF5GZyrcMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN
18N2NHiNNUunolIZEYR+dW99ezKmHlDiQ/tMgoLVYpl2Ubho2pAkLGQR+W0ZASgWQ1 18AQELBQADggEBAGwitJPOnlIKLndNf+iCLMIs0dxsl8kAaejFcjoT0n4ja7Y6Zrqz
19NjfV27Rv0y6lYQMTA0lVAU93L1x9reo3FMedmL5+H+lIEpLCxEPtAJNISrJOneZB 19VSIidzz9vQWvy24xKJpAOdj/iLRHCUOG+Pf5fA6+/FiuqXr6gE2/lm0eC58BNONr
20W5jDadwkoQ== 20E5OzjQ/VoQ8RX4hDntgu6FYbaVa/vhwn16igt9qmdNGGZXf2/+DM3JADwyaA4EK8
21vm7KdofX9zkxXecHPNvf3jiVLPiDDt6tkGpHPEsyP/yc+RUdltUeZvHfliV0cCuC
22jJX+Fm9ysjSpHIFFr+jUMuMHibWoOD8iy3eYxfCDoWsH488pCbj8MNuAq6vd6DBk
23bOZxDz43vjWuYMkwXJTxJQh7Pne6kK0vE1g=
21-----END CERTIFICATE----- 24-----END CERTIFICATE-----
diff --git a/plugins/tests/certs/server-key.pem b/plugins/tests/certs/server-key.pem
index eacaeaa..1194755 100644
--- a/plugins/tests/certs/server-key.pem
+++ b/plugins/tests/certs/server-key.pem
@@ -1,15 +1,28 @@
1-----BEGIN RSA PRIVATE KEY----- 1-----BEGIN PRIVATE KEY-----
2MIICWwIBAAKBgQCnFjAbTbX2PL2V5NEjevxGE1Tfyzr2jknoMqFXS6BsLsI2oJPl 2MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCoFdsqfKULybjf
35gs7wqh2UafJZwi2suwDvAECO00jdNooQnEq4BgPTk/h3IiCdZef5BGFALgNT0em 3miRnQHuh3dLY2rrXgj3DSHDPdlizhevUy00mKJ9Vw6J+LR04eGeXeJQ/G37BsxVQ
4Civ0+9d81AJTM8trbLoMefsUrEhMLF5Jp3udoyYhv8LhOQi09PaRfB0KhwIDAQAB 4Zg0oFonYQFH/rxKhF8G6dvd3o/xa3NKVwr5q8+pCNbVqy7UIS/1XW8RWMYVeyYym
5AoGAfpxclcP8N3vteXErXURrd7pcXT0GECDgNjhvc9PV20RPXM+vYs1AA+fMeeQE 5/j2N0sRhaUiz3j0P+UsFZ3b+62SMHI7Hi9tiuVMtkyK5IM85tqUbPyL6MUcm2K//
6TaRqwO6x016aMRO4rz5ztYArecTBznkds1k59pkN/Ne/nsueU4tvGK8MNyS2o986 6ixqB8q7SQugDvMpafAP3rS9IMLVL0Z652Xk0NqQNbmeUDd2p0y/CT/2UWWDXoCJG
7Voohqkaq4Lcy1bcHJb9su1ELjegEr1R76Mz452Hsy+uTbAECQQDcg/tZWKVeh5CQ 7msKjLUym4TOqYrt/+Gt1Kab7dMu75hn0JWHo8QqSApzK7xzKcPC+fM7//fAGwhow
8dOEB3YWHwfn0NDgfPm/X2i2kAZ7n7URaUy/ffdlfsrr1mBtHCfedLoOxmmlNfEpM 81N1MArejAgMBAAECggEANuvdTwanTzC8jaNqHaq+OuemS2E9B8nwsGxtH/zFgvNR
9hXAAurSHAkEAwfk7fEb0iN0Sj9gTozO7c6Ky10KwePZyjVzqSQIiJq3NX8BEaIeb 9WZiMPtmrJnTkFWJcV+VPw/iMSAqN4nDHmBugVOb4Z4asxGTKK4T9shXJSnh0rqPU
1051TXxE5VxaLjjMLRkA0hWTYXClgERFZ6AQJAN7ChPqwzf08PRFwwIw911JY5cOHr 1000ZsvbmxY6z0+E5TesCJqQ+9GYTY1V357V7JchvaOxIRxWPqg9urHbru8OCtW/I5
11NoDHMCUql5vNLNdwBruxgGjBB/kUXEfgw60RusFvgt/zLh1wiii844JDawJAGQBF 11Fh5HPUZlgCvlMpjlhyjydIf/oXyVA3RNsXlwe8+2cKuGIrjEzm2j9o3VF0sctTX0
12sYP3urg7zzx7c3qUe5gJ0wLuefjR1PSX4ecbfb7DDMdcSdjIuG1QDiZGmd2f1KG7 12ItP8A9qDmDQN7GIWX0MW6gncojpS1omC2wcFsdjj/xfPyiDal1X4aq/2YqG8351c
13nwSCOtxk5dloW2KGAQJAQh/iBn0QhfKLFAP5eZBVk8E8XlZuw+S2DLy5SnBlIiYJ 13YlM/+6Va0u9WWE/i64gASTAVqpMV4Yg8y0gGycuA0QKBgQDbgI2QeLd3FvMcURiU
14GB5I2OClgtudXMv1labFrcST8O9eFrtsrhU1iUGUOw== 14l3w9qJgw/Jp3jaNC/9LkVGGz4f4lKKB67lPZvI4noMK8GqO/LcXgqP/RY1oJojoA
15-----END RSA PRIVATE KEY----- 15/6JKVvzYGASZ7VgMoG9bk1AneP1PGdibuTUEwimGlcObxnDFIC/yjwPFu3jIdqdS
16zZi1RZzyqAogN5y3SBEypSmn9wKBgQDECKsqqlcizmCl8v5aVk875AzGN+DOHZqx
17bkmztlnLO/2e2Fmk3G5Vvnui0FYisf8Eq19tUTQCF6lSfJlGQeFAT119wkFZhLu+
18FfLGqoEMH0ijJg/8PpdpFRK3I94YcISoTNN6yxMvE6xdDGfKCt5a+IX5bwQi9Zdc
19B242gEc6tQKBgA6tM8n7KFlAIZU9HuWgk2AUC8kKutFPmSD7tgAqXDYI4FNfugs+
20MEEYyHCB4UNujJBV4Ss6YZCAkh6eyD4U2aca1eElCfm40vBVMdzvpqZdAqLtWXxg
21D9l3mgszrFaYGCY2Fr6jLV9lP5g3xsxUjudf9jSLY9HvpfzjRrMaNATVAoGBALTl
22/vYfPMucwKlC5B7++J0e4/7iv6vUu9SyHocdZh1anb9AjPDKjXLIlZT4RhQ8R0XK
230wOw5JpttU2uN08TKkbLNk3/vYhbKVjPLjrQSseh8sjDLgsqw1QwIxYnniLVakVY
24p+rvjSNrNyqicQCMKQavwgocvSd5lJRTMwxOMezlAoGBAKWj71BX+0CK00/2S6lC
25TcNcuUPG0d8y1czZ4q6tUlG4htwq1FMOpaghATXjkdsOGTLS+H1aA0Kt7Ai9zDhc
26/bzOJEJ+jvBXV4Gcs7jl1r/HTKv0tT9ZSI5Vzkida0rfqxDGzcMVlLuCdH0cb8Iu
27N0wdmCAqlQwHR13+F1zrAD7V
28-----END PRIVATE KEY-----
diff --git a/plugins/tests/check_curl.t b/plugins/tests/check_curl.t
new file mode 100755
index 0000000..29cb03f
--- /dev/null
+++ b/plugins/tests/check_curl.t
@@ -0,0 +1,509 @@
1#! /usr/bin/perl -w -I ..
2#
3# Test check_http by having an actual HTTP server running
4#
5# To create the https server certificate:
6# openssl req -new -x509 -keyout server-key.pem -out server-cert.pem -days 3650 -nodes
7# to create a new expired certificate:
8# faketime '2008-01-01 12:00:00' openssl req -new -x509 -keyout expired-key.pem -out expired-cert.pem -days 1 -nodes
9# Country Name (2 letter code) [AU]:DE
10# State or Province Name (full name) [Some-State]:Bavaria
11# Locality Name (eg, city) []:Munich
12# Organization Name (eg, company) [Internet Widgits Pty Ltd]:Monitoring Plugins
13# Organizational Unit Name (eg, section) []:
14# Common Name (e.g. server FQDN or YOUR name) []:Monitoring Plugins
15# Email Address []:devel@monitoring-plugins.org
16
17use strict;
18use Test::More;
19use NPTest;
20use FindBin qw($Bin);
21
22$ENV{'LC_TIME'} = "C";
23
24my $common_tests = 72;
25my $ssl_only_tests = 8;
26# Check that all dependent modules are available
27eval "use HTTP::Daemon 6.01;";
28plan skip_all => 'HTTP::Daemon >= 6.01 required' if $@;
29eval {
30 require HTTP::Status;
31 require HTTP::Response;
32};
33
34my $plugin = 'check_http';
35$plugin = 'check_curl' if $0 =~ m/check_curl/mx;
36
37# look for libcurl version to see if some advanced checks are possible (>= 7.49.0)
38my $advanced_checks = 12;
39my $use_advanced_checks = 0;
40my $required_version = '7.49.0';
41my $virtual_host = 'www.somefunnyhost.com';
42my $virtual_port = 42;
43my $curl_version = '';
44open (my $fh, '-|', "./$plugin --version") or die;
45while (<$fh>) {
46 if (m{libcurl/([\d.]+)\s}) {
47 $curl_version = $1;
48 last;
49 }
50}
51close ($fh);
52if ($curl_version) {
53 my ($major, $minor, $release) = split (/\./, $curl_version);
54 my ($req_major, $req_minor, $req_release) = split (/\./, $required_version);
55 my $check = ($major <=> $req_major or $minor <=> $req_minor or $release <=> $req_release);
56 if ($check >= 0) {
57 $use_advanced_checks = 1;
58 print "Found libcurl $major.$minor.$release. Using advanced checks\n";
59 }
60}
61
62if ($@) {
63 plan skip_all => "Missing required module for test: $@";
64} else {
65 if (-x "./$plugin") {
66 plan tests => $common_tests * 2 + $ssl_only_tests + $advanced_checks;
67 } else {
68 plan skip_all => "No $plugin compiled";
69 }
70}
71
72my $servers = { http => 0 }; # HTTP::Daemon should always be available
73eval { require HTTP::Daemon::SSL };
74if ($@) {
75 diag "Cannot load HTTP::Daemon::SSL: $@";
76} else {
77 $servers->{https} = 0;
78}
79
80# set a fixed version, so the header size doesn't vary
81$HTTP::Daemon::VERSION = "1.00";
82
83my $port_http = 50000 + int(rand(1000));
84my $port_https = $port_http + 1;
85my $port_https_expired = $port_http + 2;
86
87# This array keeps sockets around for implementing timeouts
88my @persist;
89
90# Start up all servers
91my @pids;
92my $pid = fork();
93if ($pid) {
94 # Parent
95 push @pids, $pid;
96 if (exists $servers->{https}) {
97 # Fork a normal HTTPS server
98 $pid = fork();
99 if ($pid) {
100 # Parent
101 push @pids, $pid;
102 # Fork an expired cert server
103 $pid = fork();
104 if ($pid) {
105 push @pids, $pid;
106 } else {
107 my $d = HTTP::Daemon::SSL->new(
108 LocalPort => $port_https_expired,
109 LocalAddr => "127.0.0.1",
110 SSL_cert_file => "$Bin/certs/expired-cert.pem",
111 SSL_key_file => "$Bin/certs/expired-key.pem",
112 ) || die;
113 print "Please contact https expired at: <URL:", $d->url, ">\n";
114 run_server( $d );
115 exit;
116 }
117 } else {
118 my $d = HTTP::Daemon::SSL->new(
119 LocalPort => $port_https,
120 LocalAddr => "127.0.0.1",
121 SSL_cert_file => "$Bin/certs/server-cert.pem",
122 SSL_key_file => "$Bin/certs/server-key.pem",
123 ) || die;
124 print "Please contact https at: <URL:", $d->url, ">\n";
125 run_server( $d );
126 exit;
127 }
128 }
129} else {
130 # Child
131 #print "child\n";
132 my $d = HTTP::Daemon->new(
133 LocalPort => $port_http,
134 LocalAddr => "127.0.0.1",
135 ) || die;
136 print "Please contact http at: <URL:", $d->url, ">\n";
137 run_server( $d );
138 exit;
139}
140
141# give our webservers some time to startup
142sleep(3);
143
144# Run the same server on http and https
145sub run_server {
146 my $d = shift;
147 MAINLOOP: while (my $c = $d->accept ) {
148 while (my $r = $c->get_request) {
149 if ($r->method eq "GET" and $r->url->path =~ m^/statuscode/(\d+)^) {
150 $c->send_basic_header($1);
151 $c->send_crlf;
152 } elsif ($r->method eq "GET" and $r->url->path =~ m^/file/(.*)^) {
153 $c->send_basic_header;
154 $c->send_crlf;
155 $c->send_file_response("$Bin/var/$1");
156 } elsif ($r->method eq "GET" and $r->url->path eq "/slow") {
157 $c->send_basic_header;
158 $c->send_crlf;
159 sleep 1;
160 $c->send_response("slow");
161 } elsif ($r->url->path eq "/method") {
162 if ($r->method eq "DELETE") {
163 $c->send_error(HTTP::Status->RC_METHOD_NOT_ALLOWED);
164 } elsif ($r->method eq "foo") {
165 $c->send_error(HTTP::Status->RC_NOT_IMPLEMENTED);
166 } else {
167 $c->send_status_line(200, $r->method);
168 }
169 } elsif ($r->url->path eq "/postdata") {
170 $c->send_basic_header;
171 $c->send_crlf;
172 $c->send_response($r->method.":".$r->content);
173 } elsif ($r->url->path eq "/redirect") {
174 $c->send_redirect( "/redirect2" );
175 } elsif ($r->url->path eq "/redir_external") {
176 $c->send_redirect(($d->isa('HTTP::Daemon::SSL') ? "https" : "http") . "://169.254.169.254/redirect2" );
177 } elsif ($r->url->path eq "/redirect2") {
178 $c->send_basic_header;
179 $c->send_crlf;
180 $c->send_response(HTTP::Response->new( 200, 'OK', undef, 'redirected' ));
181 } elsif ($r->url->path eq "/redir_timeout") {
182 $c->send_redirect( "/timeout" );
183 } elsif ($r->url->path eq "/timeout") {
184 # Keep $c from being destroyed, but prevent severe leaks
185 unshift @persist, $c;
186 delete($persist[1000]);
187 next MAINLOOP;
188 } elsif ($r->url->path eq "/header_check") {
189 $c->send_basic_header;
190 $c->send_header('foo');
191 $c->send_crlf;
192 } elsif ($r->url->path eq "/header_broken_check") {
193 $c->send_basic_header;
194 $c->send_header('foo');
195 print $c "Test1:: broken\n";
196 print $c " Test2: leading whitespace\n";
197 $c->send_crlf;
198 } elsif ($r->url->path eq "/virtual_port") {
199 # return sent Host header
200 $c->send_basic_header;
201 $c->send_crlf;
202 $c->send_response(HTTP::Response->new( 200, 'OK', undef, $r->header ('Host')));
203 } else {
204 $c->send_error(HTTP::Status->RC_FORBIDDEN);
205 }
206 $c->close;
207 }
208 }
209}
210
211END {
212 foreach my $pid (@pids) {
213 if ($pid) { print "Killing $pid\n"; kill "INT", $pid }
214 }
215};
216
217if ($ARGV[0] && $ARGV[0] eq "-d") {
218 while (1) {
219 sleep 100;
220 }
221}
222
223my $result;
224my $command = "./$plugin -H 127.0.0.1";
225
226run_common_tests( { command => "$command -p $port_http" } );
227SKIP: {
228 skip "HTTP::Daemon::SSL not installed", $common_tests + $ssl_only_tests if ! exists $servers->{https};
229 run_common_tests( { command => "$command -p $port_https", ssl => 1 } );
230
231 $result = NPTest->testCmd( "$command -p $port_https -S -C 14" );
232 is( $result->return_code, 0, "$command -p $port_https -S -C 14" );
233 is( $result->output, "OK - Certificate 'Monitoring Plugins' will expire on Fri Feb 16 15:31:44 2029 +0000.", "output ok" );
234
235 $result = NPTest->testCmd( "$command -p $port_https -S -C 14000" );
236 is( $result->return_code, 1, "$command -p $port_https -S -C 14000" );
237 like( $result->output, '/WARNING - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(Fri Feb 16 15:31:44 2029 \+0000\)./', "output ok" );
238
239 # Expired cert tests
240 $result = NPTest->testCmd( "$command -p $port_https -S -C 13960,14000" );
241 is( $result->return_code, 2, "$command -p $port_https -S -C 13960,14000" );
242 like( $result->output, '/CRITICAL - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(Fri Feb 16 15:31:44 2029 \+0000\)./', "output ok" );
243
244 $result = NPTest->testCmd( "$command -p $port_https_expired -S -C 7" );
245 is( $result->return_code, 2, "$command -p $port_https_expired -S -C 7" );
246 is( $result->output,
247 'CRITICAL - Certificate \'Monitoring Plugins\' expired on Wed Jan 2 11:00:26 2008 +0000.',
248 "output ok" );
249
250}
251
252my $cmd;
253
254# advanced checks with virtual hostname and virtual port
255SKIP: {
256 skip "libcurl version is smaller than $required_version", 6 unless $use_advanced_checks;
257
258 # http without virtual port
259 $cmd = "./$plugin -H $virtual_host -I 127.0.0.1 -p $port_http -u /virtual_port -r ^$virtual_host:$port_http\$";
260 $result = NPTest->testCmd( $cmd );
261 is( $result->return_code, 0, $cmd);
262 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
263
264 # http with virtual port (!= 80)
265 $cmd = "./$plugin -H $virtual_host:$virtual_port -I 127.0.0.1 -p $port_http -u /virtual_port -r ^$virtual_host:$virtual_port\$";
266 $result = NPTest->testCmd( $cmd );
267 is( $result->return_code, 0, $cmd);
268 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
269
270 # http with virtual port (80)
271 $cmd = "./$plugin -H $virtual_host:80 -I 127.0.0.1 -p $port_http -u /virtual_port -r ^$virtual_host\$";
272 $result = NPTest->testCmd( $cmd );
273 is( $result->return_code, 0, $cmd);
274 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
275}
276
277# and the same for SSL
278SKIP: {
279 skip "libcurl version is smaller than $required_version and/or HTTP::Daemon::SSL not installed", 6 if ! exists $servers->{https} or not $use_advanced_checks;
280 # https without virtual port
281 $cmd = "./$plugin -H $virtual_host -I 127.0.0.1 -p $port_https --ssl -u /virtual_port -r ^$virtual_host:$port_https\$";
282 $result = NPTest->testCmd( $cmd );
283 is( $result->return_code, 0, $cmd);
284 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
285
286 # https with virtual port (!= 443)
287 $cmd = "./$plugin -H $virtual_host:$virtual_port -I 127.0.0.1 -p $port_https --ssl -u /virtual_port -r ^$virtual_host:$virtual_port\$";
288 $result = NPTest->testCmd( $cmd );
289 is( $result->return_code, 0, $cmd);
290 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
291
292 # https with virtual port (443)
293 $cmd = "./$plugin -H $virtual_host:443 -I 127.0.0.1 -p $port_https --ssl -u /virtual_port -r ^$virtual_host\$";
294 $result = NPTest->testCmd( $cmd );
295 is( $result->return_code, 0, $cmd);
296 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
297}
298
299
300sub run_common_tests {
301 my ($opts) = @_;
302 my $command = $opts->{command};
303 if ($opts->{ssl}) {
304 $command .= " --ssl";
305 }
306
307 $result = NPTest->testCmd( "$command -u /file/root" );
308 is( $result->return_code, 0, "/file/root");
309 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - 274 bytes in [\d\.]+ second/', "Output correct" );
310
311 $result = NPTest->testCmd( "$command -u /file/root -s Root" );
312 is( $result->return_code, 0, "/file/root search for string");
313 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - 274 bytes in [\d\.]+ second/', "Output correct" );
314
315 $result = NPTest->testCmd( "$command -u /file/root -s NonRoot" );
316 is( $result->return_code, 2, "Missing string check");
317 like( $result->output, qr%^HTTP CRITICAL: HTTP/1\.1 200 OK - string 'NonRoot' not found on 'https?://127\.0\.0\.1:\d+/file/root'%, "Shows search string and location");
318
319 $result = NPTest->testCmd( "$command -u /file/root -s NonRootWithOver30charsAndMoreFunThanAWetFish" );
320 is( $result->return_code, 2, "Missing string check");
321 like( $result->output, qr%HTTP CRITICAL: HTTP/1\.1 200 OK - string 'NonRootWithOver30charsAndM...' not found on 'https?://127\.0\.0\.1:\d+/file/root'%, "Shows search string and location");
322
323 $result = NPTest->testCmd( "$command -u /header_check -d foo" );
324 is( $result->return_code, 0, "header_check search for string");
325 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - 96 bytes in [\d\.]+ second/', "Output correct" );
326
327 $result = NPTest->testCmd( "$command -u /header_check -d bar" );
328 is( $result->return_code, 2, "Missing header string check");
329 like( $result->output, qr%^HTTP CRITICAL: HTTP/1\.1 200 OK - header 'bar' not found on 'https?://127\.0\.0\.1:\d+/header_check'%, "Shows search string and location");
330
331 $result = NPTest->testCmd( "$command -u /header_broken_check" );
332 is( $result->return_code, 0, "header_check search for string");
333 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - 138 bytes in [\d\.]+ second/', "Output correct" );
334
335 my $cmd;
336 $cmd = "$command -u /slow";
337 $result = NPTest->testCmd( $cmd );
338 is( $result->return_code, 0, "$cmd");
339 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
340 $result->output =~ /in ([\d\.]+) second/;
341 cmp_ok( $1, ">", 1, "Time is > 1 second" );
342
343 $cmd = "$command -u /statuscode/200";
344 $result = NPTest->testCmd( $cmd );
345 is( $result->return_code, 0, $cmd);
346 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
347
348 $cmd = "$command -u /statuscode/200 -e 200";
349 $result = NPTest->testCmd( $cmd );
350 is( $result->return_code, 0, $cmd);
351 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - Status line output matched "200" - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
352
353 $cmd = "$command -u /statuscode/201";
354 $result = NPTest->testCmd( $cmd );
355 is( $result->return_code, 0, $cmd);
356 like( $result->output, '/^HTTP OK: HTTP/1.1 201 Created - \d+ bytes in [\d\.]+ second /', "Output correct: ".$result->output );
357
358 $cmd = "$command -u /statuscode/201 -e 201";
359 $result = NPTest->testCmd( $cmd );
360 is( $result->return_code, 0, $cmd);
361 like( $result->output, '/^HTTP OK: HTTP/1.1 201 Created - Status line output matched "201" - \d+ bytes in [\d\.]+ second /', "Output correct: ".$result->output );
362
363 $cmd = "$command -u /statuscode/201 -e 200";
364 $result = NPTest->testCmd( $cmd );
365 is( $result->return_code, 2, $cmd);
366 like( $result->output, '/^HTTP CRITICAL - Invalid HTTP response received from host on port \d+: HTTP/1.1 201 Created/', "Output correct: ".$result->output );
367
368 $cmd = "$command -u /statuscode/200 -e 200,201,202";
369 $result = NPTest->testCmd( $cmd );
370 is( $result->return_code, 0, $cmd);
371 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - Status line output matched "200,201,202" - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
372
373 $cmd = "$command -u /statuscode/201 -e 200,201,202";
374 $result = NPTest->testCmd( $cmd );
375 is( $result->return_code, 0, $cmd);
376 like( $result->output, '/^HTTP OK: HTTP/1.1 201 Created - Status line output matched "200,201,202" - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
377
378 $cmd = "$command -u /statuscode/203 -e 200,201,202";
379 $result = NPTest->testCmd( $cmd );
380 is( $result->return_code, 2, $cmd);
381 like( $result->output, '/^HTTP CRITICAL - Invalid HTTP response received from host on port (\d+): HTTP/1.1 203 Non-Authoritative Information/', "Output correct: ".$result->output );
382
383 $cmd = "$command -j HEAD -u /method";
384 $result = NPTest->testCmd( $cmd );
385 is( $result->return_code, 0, $cmd);
386 like( $result->output, '/^HTTP OK: HTTP/1.1 200 HEAD - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
387
388 $cmd = "$command -j POST -u /method";
389 $result = NPTest->testCmd( $cmd );
390 is( $result->return_code, 0, $cmd);
391 like( $result->output, '/^HTTP OK: HTTP/1.1 200 POST - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
392
393 $cmd = "$command -j GET -u /method";
394 $result = NPTest->testCmd( $cmd );
395 is( $result->return_code, 0, $cmd);
396 like( $result->output, '/^HTTP OK: HTTP/1.1 200 GET - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
397
398 $cmd = "$command -u /method";
399 $result = NPTest->testCmd( $cmd );
400 is( $result->return_code, 0, $cmd);
401 like( $result->output, '/^HTTP OK: HTTP/1.1 200 GET - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
402
403 $cmd = "$command -P foo -u /method";
404 $result = NPTest->testCmd( $cmd );
405 is( $result->return_code, 0, $cmd);
406 like( $result->output, '/^HTTP OK: HTTP/1.1 200 POST - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
407
408 $cmd = "$command -j DELETE -u /method";
409 $result = NPTest->testCmd( $cmd );
410 is( $result->return_code, 1, $cmd);
411 like( $result->output, '/^HTTP WARNING: HTTP/1.1 405 Method Not Allowed/', "Output correct: ".$result->output );
412
413 $cmd = "$command -j foo -u /method";
414 $result = NPTest->testCmd( $cmd );
415 is( $result->return_code, 2, $cmd);
416 like( $result->output, '/^HTTP CRITICAL: HTTP/1.1 501 Not Implemented/', "Output correct: ".$result->output );
417
418 $cmd = "$command -P stufftoinclude -u /postdata -s POST:stufftoinclude";
419 $result = NPTest->testCmd( $cmd );
420 is( $result->return_code, 0, $cmd);
421 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
422
423 $cmd = "$command -j PUT -P stufftoinclude -u /postdata -s PUT:stufftoinclude";
424 $result = NPTest->testCmd( $cmd );
425 is( $result->return_code, 0, $cmd);
426 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
427
428 # To confirm that the free doesn't segfault
429 $cmd = "$command -P stufftoinclude -j PUT -u /postdata -s PUT:stufftoinclude";
430 $result = NPTest->testCmd( $cmd );
431 is( $result->return_code, 0, $cmd);
432 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
433
434 $cmd = "$command -u /redirect";
435 $result = NPTest->testCmd( $cmd );
436 is( $result->return_code, 0, $cmd);
437 like( $result->output, '/^HTTP OK: HTTP/1.1 301 Moved Permanently - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
438
439 $cmd = "$command -f follow -u /redirect";
440 $result = NPTest->testCmd( $cmd );
441 is( $result->return_code, 0, $cmd);
442 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
443
444 $cmd = "$command -u /redirect -k 'follow: me'";
445 $result = NPTest->testCmd( $cmd );
446 is( $result->return_code, 0, $cmd);
447 like( $result->output, '/^HTTP OK: HTTP/1.1 301 Moved Permanently - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
448
449 $cmd = "$command -f follow -u /redirect -k 'follow: me'";
450 $result = NPTest->testCmd( $cmd );
451 is( $result->return_code, 0, $cmd);
452 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
453
454 $cmd = "$command -f sticky -u /redirect -k 'follow: me'";
455 $result = NPTest->testCmd( $cmd );
456 is( $result->return_code, 0, $cmd);
457 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
458
459 $cmd = "$command -f stickyport -u /redirect -k 'follow: me'";
460 $result = NPTest->testCmd( $cmd );
461 is( $result->return_code, 0, $cmd);
462 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
463
464 # These tests may block
465 print "ALRM\n";
466
467 # stickyport - on full urlS port is set back to 80 otherwise
468 $cmd = "$command -f stickyport -u /redir_external -t 5 -s redirected";
469 eval {
470 local $SIG{ALRM} = sub { die "alarm\n" };
471 alarm(2);
472 $result = NPTest->testCmd( $cmd );
473 alarm(0); };
474 isnt( $@, "alarm\n", $cmd );
475 is( $result->return_code, 0, $cmd );
476
477 # Let's hope there won't be any web server on :80 returning "redirected"!
478 $cmd = "$command -f sticky -u /redir_external -t 5 -s redirected";
479 eval {
480 local $SIG{ALRM} = sub { die "alarm\n" };
481 alarm(2);
482 $result = NPTest->testCmd( $cmd );
483 alarm(0); };
484 isnt( $@, "alarm\n", $cmd );
485 isnt( $result->return_code, 0, $cmd );
486
487 # Test an external address - timeout
488 SKIP: {
489 skip "This doesn't seem to work all the time", 1 unless ($ENV{HTTP_EXTERNAL});
490 $cmd = "$command -f follow -u /redir_external -t 5";
491 eval {
492 $result = NPTest->testCmd( $cmd, 2 );
493 };
494 like( $@, "/timeout in command: $cmd/", $cmd );
495 }
496
497 $cmd = "$command -u /timeout -t 5";
498 eval {
499 $result = NPTest->testCmd( $cmd, 2 );
500 };
501 like( $@, "/timeout in command: $cmd/", $cmd );
502
503 $cmd = "$command -f follow -u /redir_timeout -t 2";
504 eval {
505 $result = NPTest->testCmd( $cmd, 5 );
506 };
507 is( $@, "", $cmd );
508
509}
diff --git a/plugins/tests/check_http.t b/plugins/tests/check_http.t
index e72d243..188f5e7 100755
--- a/plugins/tests/check_http.t
+++ b/plugins/tests/check_http.t
@@ -4,20 +4,25 @@
4# 4#
5# To create the https server certificate: 5# To create the https server certificate:
6# openssl req -new -x509 -keyout server-key.pem -out server-cert.pem -days 3650 -nodes 6# openssl req -new -x509 -keyout server-key.pem -out server-cert.pem -days 3650 -nodes
7# Country Name (2 letter code) [AU]:UK 7# to create a new expired certificate:
8# State or Province Name (full name) [Some-State]:Derbyshire 8# faketime '2008-01-01 12:00:00' openssl req -new -x509 -keyout expired-key.pem -out expired-cert.pem -days 1 -nodes
9# Locality Name (eg, city) []:Belper 9# Country Name (2 letter code) [AU]:DE
10# State or Province Name (full name) [Some-State]:Bavaria
11# Locality Name (eg, city) []:Munich
10# Organization Name (eg, company) [Internet Widgits Pty Ltd]:Monitoring Plugins 12# Organization Name (eg, company) [Internet Widgits Pty Ltd]:Monitoring Plugins
11# Organizational Unit Name (eg, section) []: 13# Organizational Unit Name (eg, section) []:
12# Common Name (eg, YOUR name) []:Ton Voon 14# Common Name (e.g. server FQDN or YOUR name) []:Monitoring Plugins
13# Email Address []:tonvoon@mac.com 15# Email Address []:devel@monitoring-plugins.org
14 16
15use strict; 17use strict;
16use Test::More; 18use Test::More;
17use NPTest; 19use NPTest;
18use FindBin qw($Bin); 20use FindBin qw($Bin);
19 21
22$ENV{'LC_TIME'} = "C";
23
20my $common_tests = 70; 24my $common_tests = 70;
25my $virtual_port_tests = 8;
21my $ssl_only_tests = 8; 26my $ssl_only_tests = 8;
22# Check that all dependent modules are available 27# Check that all dependent modules are available
23eval "use HTTP::Daemon 6.01;"; 28eval "use HTTP::Daemon 6.01;";
@@ -27,13 +32,16 @@ eval {
27 require HTTP::Response; 32 require HTTP::Response;
28}; 33};
29 34
35my $plugin = 'check_http';
36$plugin = 'check_curl' if $0 =~ m/check_curl/mx;
37
30if ($@) { 38if ($@) {
31 plan skip_all => "Missing required module for test: $@"; 39 plan skip_all => "Missing required module for test: $@";
32} else { 40} else {
33 if (-x "./check_http") { 41 if (-x "./$plugin") {
34 plan tests => $common_tests * 2 + $ssl_only_tests; 42 plan tests => $common_tests * 2 + $ssl_only_tests + $virtual_port_tests;
35 } else { 43 } else {
36 plan skip_all => "No check_http compiled"; 44 plan skip_all => "No $plugin compiled";
37 } 45 }
38} 46}
39 47
@@ -83,6 +91,8 @@ if ($pid) {
83 exit; 91 exit;
84 } 92 }
85 } else { 93 } else {
94 # closing the connection after -C cert checks make the daemon exit with a sigpipe otherwise
95 local $SIG{'PIPE'} = 'IGNORE';
86 my $d = HTTP::Daemon::SSL->new( 96 my $d = HTTP::Daemon::SSL->new(
87 LocalPort => $port_https, 97 LocalPort => $port_https,
88 LocalAddr => "127.0.0.1", 98 LocalAddr => "127.0.0.1",
@@ -94,8 +104,6 @@ if ($pid) {
94 exit; 104 exit;
95 } 105 }
96 } 106 }
97 # give our webservers some time to startup
98 sleep(1);
99} else { 107} else {
100 # Child 108 # Child
101 #print "child\n"; 109 #print "child\n";
@@ -108,6 +116,9 @@ if ($pid) {
108 exit; 116 exit;
109} 117}
110 118
119# give our webservers some time to startup
120sleep(3);
121
111# Run the same server on http and https 122# Run the same server on http and https
112sub run_server { 123sub run_server {
113 my $d = shift; 124 my $d = shift;
@@ -156,6 +167,11 @@ sub run_server {
156 $c->send_basic_header; 167 $c->send_basic_header;
157 $c->send_header('foo'); 168 $c->send_header('foo');
158 $c->send_crlf; 169 $c->send_crlf;
170 } elsif ($r->url->path eq "/virtual_port") {
171 # return sent Host header
172 $c->send_basic_header;
173 $c->send_crlf;
174 $c->send_response(HTTP::Response->new( 200, 'OK', undef, $r->header ('Host')));
159 } else { 175 } else {
160 $c->send_error(HTTP::Status->RC_FORBIDDEN); 176 $c->send_error(HTTP::Status->RC_FORBIDDEN);
161 } 177 }
@@ -177,7 +193,7 @@ if ($ARGV[0] && $ARGV[0] eq "-d") {
177} 193}
178 194
179my $result; 195my $result;
180my $command = "./check_http -H 127.0.0.1"; 196my $command = "./$plugin -H 127.0.0.1";
181 197
182run_common_tests( { command => "$command -p $port_http" } ); 198run_common_tests( { command => "$command -p $port_http" } );
183SKIP: { 199SKIP: {
@@ -186,25 +202,56 @@ SKIP: {
186 202
187 $result = NPTest->testCmd( "$command -p $port_https -S -C 14" ); 203 $result = NPTest->testCmd( "$command -p $port_https -S -C 14" );
188 is( $result->return_code, 0, "$command -p $port_https -S -C 14" ); 204 is( $result->return_code, 0, "$command -p $port_https -S -C 14" );
189 is( $result->output, 'OK - Certificate \'Ton Voon\' will expire on Sun Mar 3 21:41:28 2019.', "output ok" ); 205 is( $result->output, "OK - Certificate 'Monitoring Plugins' will expire on Fri Feb 16 15:31:44 2029 +0000.", "output ok" );
190 206
191 $result = NPTest->testCmd( "$command -p $port_https -S -C 14000" ); 207 $result = NPTest->testCmd( "$command -p $port_https -S -C 14000" );
192 is( $result->return_code, 1, "$command -p $port_https -S -C 14000" ); 208 is( $result->return_code, 1, "$command -p $port_https -S -C 14000" );
193 like( $result->output, '/WARNING - Certificate \'Ton Voon\' expires in \d+ day\(s\) \(Sun Mar 3 21:41:28 2019\)./', "output ok" ); 209 like( $result->output, '/WARNING - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(Fri Feb 16 15:31:44 2029 \+0000\)./', "output ok" );
194 210
195 # Expired cert tests 211 # Expired cert tests
196 $result = NPTest->testCmd( "$command -p $port_https -S -C 13960,14000" ); 212 $result = NPTest->testCmd( "$command -p $port_https -S -C 13960,14000" );
197 is( $result->return_code, 2, "$command -p $port_https -S -C 13960,14000" ); 213 is( $result->return_code, 2, "$command -p $port_https -S -C 13960,14000" );
198 like( $result->output, '/CRITICAL - Certificate \'Ton Voon\' expires in \d+ day\(s\) \(Sun Mar 3 21:41:28 2019\)./', "output ok" ); 214 like( $result->output, '/CRITICAL - Certificate \'Monitoring Plugins\' expires in \d+ day\(s\) \(Fri Feb 16 15:31:44 2029 \+0000\)./', "output ok" );
199 215
200 $result = NPTest->testCmd( "$command -p $port_https_expired -S -C 7" ); 216 $result = NPTest->testCmd( "$command -p $port_https_expired -S -C 7" );
201 is( $result->return_code, 2, "$command -p $port_https_expired -S -C 7" ); 217 is( $result->return_code, 2, "$command -p $port_https_expired -S -C 7" );
202 is( $result->output, 218 is( $result->output,
203 'CRITICAL - Certificate \'Ton Voon\' expired on Thu Mar 5 00:13:16 2009.', 219 'CRITICAL - Certificate \'Monitoring Plugins\' expired on Wed Jan 2 11:00:26 2008 +0000.',
204 "output ok" ); 220 "output ok" );
205 221
206} 222}
207 223
224my $cmd;
225# check virtual port behaviour
226#
227# http without virtual port
228$cmd = "$command -p $port_http -u /virtual_port -r ^127.0.0.1:$port_http\$";
229$result = NPTest->testCmd( $cmd );
230is( $result->return_code, 0, $cmd);
231like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
232
233# http with virtual port
234$cmd = "$command:80 -p $port_http -u /virtual_port -r ^127.0.0.1\$";
235$result = NPTest->testCmd( $cmd );
236is( $result->return_code, 0, $cmd);
237like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
238
239SKIP: {
240 skip "HTTP::Daemon::SSL not installed", 4 if ! exists $servers->{https};
241 # https without virtual port
242 $cmd = "$command -p $port_https --ssl -u /virtual_port -r ^127.0.0.1:$port_https\$";
243 $result = NPTest->testCmd( $cmd );
244 is( $result->return_code, 0, $cmd);
245 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
246
247 # https with virtual port
248 $cmd = "$command:443 -p $port_https --ssl -u /virtual_port -r ^127.0.0.1\$";
249 $result = NPTest->testCmd( $cmd );
250 is( $result->return_code, 0, $cmd);
251 like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output );
252}
253
254
208sub run_common_tests { 255sub run_common_tests {
209 my ($opts) = @_; 256 my ($opts) = @_;
210 my $command = $opts->{command}; 257 my $command = $opts->{command};
@@ -370,27 +417,29 @@ sub run_common_tests {
370 417
371 # stickyport - on full urlS port is set back to 80 otherwise 418 # stickyport - on full urlS port is set back to 80 otherwise
372 $cmd = "$command -f stickyport -u /redir_external -t 5 -s redirected"; 419 $cmd = "$command -f stickyport -u /redir_external -t 5 -s redirected";
420 alarm(2);
373 eval { 421 eval {
374 local $SIG{ALRM} = sub { die "alarm\n" }; 422 local $SIG{ALRM} = sub { die "alarm\n" };
375 alarm(2);
376 $result = NPTest->testCmd( $cmd ); 423 $result = NPTest->testCmd( $cmd );
377 alarm(0); }; 424 };
378 isnt( $@, "alarm\n", $cmd ); 425 isnt( $@, "alarm\n", $cmd );
426 alarm(0);
379 is( $result->return_code, 0, $cmd ); 427 is( $result->return_code, 0, $cmd );
380 428
381 # Let's hope there won't be any web server on :80 returning "redirected"! 429 # Let's hope there won't be any web server on :80 returning "redirected"!
382 $cmd = "$command -f sticky -u /redir_external -t 5 -s redirected"; 430 $cmd = "$command -f sticky -u /redir_external -t 5 -s redirected";
431 alarm(2);
383 eval { 432 eval {
384 local $SIG{ALRM} = sub { die "alarm\n" }; 433 local $SIG{ALRM} = sub { die "alarm\n" };
385 alarm(2);
386 $result = NPTest->testCmd( $cmd ); 434 $result = NPTest->testCmd( $cmd );
387 alarm(0); }; 435 };
388 isnt( $@, "alarm\n", $cmd ); 436 isnt( $@, "alarm\n", $cmd );
437 alarm(0);
389 isnt( $result->return_code, 0, $cmd ); 438 isnt( $result->return_code, 0, $cmd );
390 439
391 # Test an external address - timeout 440 # Test an external address - timeout
392 SKIP: { 441 SKIP: {
393 skip "This doesn't seems to work all the time", 1 unless ($ENV{HTTP_EXTERNAL}); 442 skip "This doesn't seem to work all the time", 1 unless ($ENV{HTTP_EXTERNAL});
394 $cmd = "$command -f follow -u /redir_external -t 5"; 443 $cmd = "$command -f follow -u /redir_external -t 5";
395 eval { 444 eval {
396 $result = NPTest->testCmd( $cmd, 2 ); 445 $result = NPTest->testCmd( $cmd, 2 );
diff --git a/plugins/tests/check_snmp.t b/plugins/tests/check_snmp.t
index 73a68b2..85d6bf5 100755
--- a/plugins/tests/check_snmp.t
+++ b/plugins/tests/check_snmp.t
@@ -7,6 +7,7 @@ use strict;
7use Test::More; 7use Test::More;
8use NPTest; 8use NPTest;
9use FindBin qw($Bin); 9use FindBin qw($Bin);
10use POSIX qw/strftime/;
10 11
11my $tests = 67; 12my $tests = 67;
12# Check that all dependent modules are available 13# Check that all dependent modules are available
@@ -37,6 +38,7 @@ if ($@) {
37 38
38my $port_snmp = 16100 + int(rand(100)); 39my $port_snmp = 16100 + int(rand(100));
39 40
41my $faketime = -x '/usr/bin/faketime' ? 1 : 0;
40 42
41# Start up server 43# Start up server
42my @pids; 44my @pids;
@@ -118,77 +120,81 @@ like($res->output, '/'.quotemeta('SNMP OK - And now have fun with with this: \"C
118"And now have fun with with this: \"C:\\\\\" 120"And now have fun with with this: \"C:\\\\\"
119because we\'re not done yet!"').'/m', "Attempt to confuse parser No.3"); 121because we\'re not done yet!"').'/m', "Attempt to confuse parser No.3");
120 122
121system("rm -f ".$ENV{'MP_STATE_PATH'}."/check_snmp/*"); 123system("rm -f ".$ENV{'MP_STATE_PATH'}."/*/check_snmp/*");
122$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -w 600" );
123is($res->return_code, 0, "Returns OK");
124is($res->output, "No previous data to calculate rate - assume okay");
125 124
126# Need to sleep, otherwise duration=0 125# run rate checks with faketime. rate checks depend on the exact amount of time spend between the
127sleep 1; 126# plugin runs which may fail on busy machines.
127# using faketime removes this race condition and also saves all the sleeps in between.
128SKIP: {
129 skip "No faketime binary found", 28 if !$faketime;
128 130
129$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -w 600" ); 131 my $ts = time();
130is($res->return_code, 1, "WARNING - due to going above rate calculation" ); 132 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts))."' ./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -w 600" );
131is($res->output, "SNMP RATE WARNING - *666* | iso.3.6.1.4.1.8072.3.2.67.10=666;600 "); 133 is($res->return_code, 0, "Returns OK");
134 is($res->output, "No previous data to calculate rate - assume okay");
132 135
133$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -w 600" ); 136 # test rate 1 second later
134is($res->return_code, 3, "UNKNOWN - basically the divide by zero error" ); 137 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts+1))."' ./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -w 600" );
135is($res->output, "Time duration between plugin calls is invalid"); 138 is($res->return_code, 1, "WARNING - due to going above rate calculation" );
139 is($res->output, "SNMP RATE WARNING - *666* | iso.3.6.1.4.1.8072.3.2.67.10=666;600 ");
136 140
141 # test rate with same time
142 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts+1))."' ./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -w 600" );
143 is($res->return_code, 3, "UNKNOWN - basically the divide by zero error" );
144 is($res->output, "Time duration between plugin calls is invalid");
137 145
138$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -l inoctets" );
139is($res->return_code, 0, "OK for first call" );
140is($res->output, "No previous data to calculate rate - assume okay" );
141 146
142# Need to sleep, otherwise duration=0 147 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts))."' ./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -l inoctets" );
143sleep 1; 148 is($res->return_code, 0, "OK for first call" );
149 is($res->output, "No previous data to calculate rate - assume okay" );
144 150
145$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -l inoctets" ); 151 # test rate 1 second later
146is($res->return_code, 0, "OK as no thresholds" ); 152 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts+1))."' ./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -l inoctets" );
147is($res->output, "SNMP RATE OK - inoctets 666 | inoctets=666 ", "Check label"); 153 is($res->return_code, 0, "OK as no thresholds" );
154 is($res->output, "SNMP RATE OK - inoctets 666 | inoctets=666 ", "Check label");
148 155
149sleep 2; 156 # test rate 3 seconds later
157 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts+3))."' ./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -l inoctets" );
158 is($res->return_code, 0, "OK as no thresholds" );
159 is($res->output, "SNMP RATE OK - inoctets 333 | inoctets=333 ", "Check rate decreases due to longer interval");
150 160
151$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -l inoctets" );
152is($res->return_code, 0, "OK as no thresholds" );
153is($res->output, "SNMP RATE OK - inoctets 333 | inoctets=333 ", "Check rate decreases due to longer interval");
154 161
162 # label performance data check
163 $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 -l test" );
164 is($res->return_code, 0, "OK as no thresholds" );
165 is($res->output, "SNMP OK - test 67996 | test=67996c ", "Check label");
155 166
156# label performance data check 167 $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 -l \"test'test\"" );
157$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 -l test" ); 168 is($res->return_code, 0, "OK as no thresholds" );
158is($res->return_code, 0, "OK as no thresholds" ); 169 is($res->output, "SNMP OK - test'test 68662 | \"test'test\"=68662c ", "Check label");
159is($res->output, "SNMP OK - test 67996 | test=67996c ", "Check label");
160 170
161$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 -l \"test'test\"" ); 171 $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 -l 'test\"test'" );
162is($res->return_code, 0, "OK as no thresholds" ); 172 is($res->return_code, 0, "OK as no thresholds" );
163is($res->output, "SNMP OK - test'test 68662 | \"test'test\"=68662c ", "Check label"); 173 is($res->output, "SNMP OK - test\"test 69328 | 'test\"test'=69328c ", "Check label");
164 174
165$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 -l 'test\"test'" ); 175 $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 -l test -O" );
166is($res->return_code, 0, "OK as no thresholds" ); 176 is($res->return_code, 0, "OK as no thresholds" );
167is($res->output, "SNMP OK - test\"test 69328 | 'test\"test'=69328c ", "Check label"); 177 is($res->output, "SNMP OK - test 69994 | iso.3.6.1.4.1.8072.3.2.67.10=69994c ", "Check label");
168 178
169$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 -l test -O" ); 179 $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10" );
170is($res->return_code, 0, "OK as no thresholds" ); 180 is($res->return_code, 0, "OK as no thresholds" );
171is($res->output, "SNMP OK - test 69994 | iso.3.6.1.4.1.8072.3.2.67.10=69994c ", "Check label"); 181 is($res->output, "SNMP OK - 70660 | iso.3.6.1.4.1.8072.3.2.67.10=70660c ", "Check label");
172 182
173$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10" ); 183 $res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 -l 'test test'" );
174is($res->return_code, 0, "OK as no thresholds" ); 184 is($res->return_code, 0, "OK as no thresholds" );
175is($res->output, "SNMP OK - 70660 | iso.3.6.1.4.1.8072.3.2.67.10=70660c ", "Check label"); 185 is($res->output, "SNMP OK - test test 71326 | 'test test'=71326c ", "Check label");
176 186
177$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 -l 'test test'" );
178is($res->return_code, 0, "OK as no thresholds" );
179is($res->output, "SNMP OK - test test 71326 | 'test test'=71326c ", "Check label");
180 187
188 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts))."' ./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -l inoctets_per_minute --rate-multiplier=60" );
189 is($res->return_code, 0, "OK for first call" );
190 is($res->output, "No previous data to calculate rate - assume okay" );
181 191
182$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -l inoctets_per_minute --rate-multiplier=60" ); 192 # test 1 second later
183is($res->return_code, 0, "OK for first call" ); 193 $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts+1))."' ./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -l inoctets_per_minute --rate-multiplier=60" );
184is($res->output, "No previous data to calculate rate - assume okay" ); 194 is($res->return_code, 0, "OK as no thresholds" );
185 195 is($res->output, "SNMP RATE OK - inoctets_per_minute 39960 | inoctets_per_minute=39960 ", "Checking multiplier");
186# Need to sleep, otherwise duration=0 196};
187sleep 1;
188 197
189$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.10 --rate -l inoctets_per_minute --rate-multiplier=60" );
190is($res->return_code, 0, "OK as no thresholds" );
191is($res->output, "SNMP RATE OK - inoctets_per_minute 39960 | inoctets_per_minute=39960 ", "Checking multiplier");
192 198
193 199
194$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.11 -s '\"stringtests\"'" ); 200$res = NPTest->testCmd( "./check_snmp -H 127.0.0.1 -C public -p $port_snmp -o .1.3.6.1.4.1.8072.3.2.67.11 -s '\"stringtests\"'" );
diff --git a/plugins/utils.c b/plugins/utils.c
index a864e4a..348ec02 100644
--- a/plugins/utils.c
+++ b/plugins/utils.c
@@ -36,9 +36,6 @@ extern const char *progname;
36#define STRLEN 64 36#define STRLEN 64
37#define TXTBLK 128 37#define TXTBLK 128
38 38
39unsigned int timeout_state = STATE_CRITICAL;
40unsigned int timeout_interval = DEFAULT_SOCKET_TIMEOUT;
41
42time_t start_time, end_time; 39time_t start_time, end_time;
43 40
44/* ************************************************************************** 41/* **************************************************************************
@@ -148,33 +145,6 @@ print_revision (const char *command_name, const char *revision)
148 command_name, revision, PACKAGE, VERSION); 145 command_name, revision, PACKAGE, VERSION);
149} 146}
150 147
151const char *
152state_text (int result)
153{
154 switch (result) {
155 case STATE_OK:
156 return "OK";
157 case STATE_WARNING:
158 return "WARNING";
159 case STATE_CRITICAL:
160 return "CRITICAL";
161 case STATE_DEPENDENT:
162 return "DEPENDENT";
163 default:
164 return "UNKNOWN";
165 }
166}
167
168void
169timeout_alarm_handler (int signo)
170{
171 if (signo == SIGALRM) {
172 printf (_("%s - Plugin timed out after %d seconds\n"),
173 state_text(timeout_state), timeout_interval);
174 exit (timeout_state);
175 }
176}
177
178int 148int
179is_numeric (char *number) 149is_numeric (char *number)
180{ 150{
@@ -668,3 +638,59 @@ char *sperfdata (const char *label,
668 638
669 return data; 639 return data;
670} 640}
641
642char *sperfdata_int (const char *label,
643 int val,
644 const char *uom,
645 char *warn,
646 char *crit,
647 int minp,
648 int minv,
649 int maxp,
650 int maxv)
651{
652 char *data = NULL;
653 if (strpbrk (label, "'= "))
654 xasprintf (&data, "'%s'=", label);
655 else
656 xasprintf (&data, "%s=", label);
657
658 xasprintf (&data, "%s%d", data, val);
659 xasprintf (&data, "%s%s;", data, uom);
660
661 if (warn!=NULL)
662 xasprintf (&data, "%s%s", data, warn);
663
664 xasprintf (&data, "%s;", data);
665
666 if (crit!=NULL)
667 xasprintf (&data, "%s%s", data, crit);
668
669 xasprintf (&data, "%s;", data);
670
671 if (minp)
672 xasprintf (&data, "%s%d", data, minv);
673
674 if (maxp) {
675 xasprintf (&data, "%s;", data);
676 xasprintf (&data, "%s%d", data, maxv);
677 }
678
679 return data;
680}
681
682int
683open_max (void)
684{
685 errno = 0;
686 if (maxfd > 0)
687 return(maxfd);
688
689 if ((maxfd = sysconf (_SC_OPEN_MAX)) < 0) {
690 if (errno == 0)
691 maxfd = DEFAULT_MAXFD; /* it's indeterminate */
692 else
693 die (STATE_UNKNOWN, _("sysconf error for _SC_OPEN_MAX\n"));
694 }
695 return(maxfd);
696}
diff --git a/plugins/utils.h b/plugins/utils.h
index 4c4aacc..33a2054 100644
--- a/plugins/utils.h
+++ b/plugins/utils.h
@@ -29,13 +29,6 @@ suite of plugins. */
29void support (void); 29void support (void);
30void print_revision (const char *, const char *); 30void print_revision (const char *, const char *);
31 31
32/* Handle timeouts */
33
34extern unsigned int timeout_state;
35extern unsigned int timeout_interval;
36
37RETSIGTYPE timeout_alarm_handler (int);
38
39extern time_t start_time, end_time; 32extern time_t start_time, end_time;
40 33
41/* Test input types */ 34/* Test input types */
@@ -89,34 +82,22 @@ void usage4(const char *) __attribute__((noreturn));
89void usage5(void) __attribute__((noreturn)); 82void usage5(void) __attribute__((noreturn));
90void usage_va(const char *fmt, ...) __attribute__((noreturn)); 83void usage_va(const char *fmt, ...) __attribute__((noreturn));
91 84
92const char *state_text (int);
93
94#define max(a,b) (((a)>(b))?(a):(b)) 85#define max(a,b) (((a)>(b))?(a):(b))
95#define min(a,b) (((a)<(b))?(a):(b)) 86#define min(a,b) (((a)<(b))?(a):(b))
96 87
97char *perfdata (const char *, 88char *perfdata (const char *, long int, const char *, int, long int,
98 long int, 89 int, long int, int, long int, int, long int);
99 const char *, 90
100 int, 91char *fperfdata (const char *, double, const char *, int, double,
101 long int, 92 int, double, int, double, int, double);
102 int, 93
103 long int, 94char *sperfdata (const char *, double, const char *, char *, char *,
104 int, 95 int, double, int, double);
105 long int, 96
106 int, 97char *sperfdata_int (const char *, int, const char *, char *, char *,
107 long int); 98 int, int, int, int);
108 99
109char *fperfdata (const char *, 100int open_max (void);
110 double,
111 const char *,
112 int,
113 double,
114 int,
115 double,
116 int,
117 double,
118 int,
119 double);
120 101
121/* The idea here is that, although not every plugin will use all of these, 102/* The idea here is that, although not every plugin will use all of these,
122 most will or should. Therefore, for consistency, these very common 103 most will or should. Therefore, for consistency, these very common