diff options
-rw-r--r-- | .gitignore | 7 | ||||
-rw-r--r-- | .travis.yml | 2 | ||||
-rw-r--r-- | ACKNOWLEDGEMENTS | 8 | ||||
-rw-r--r-- | REQUIREMENTS | 16 | ||||
-rw-r--r-- | configure.ac | 40 | ||||
-rw-r--r-- | m4/libcurl.m4 | 272 | ||||
-rw-r--r-- | m4/uriparser.m4 | 140 | ||||
-rw-r--r-- | plugins/Makefile.am | 9 | ||||
-rw-r--r-- | plugins/check_curl.c | 2268 | ||||
-rw-r--r-- | plugins/picohttpparser/Makefile.am | 3 | ||||
-rw-r--r-- | plugins/picohttpparser/picohttpparser.c | 620 | ||||
-rw-r--r-- | plugins/picohttpparser/picohttpparser.h | 89 | ||||
-rw-r--r-- | plugins/sslutils.c | 33 | ||||
-rw-r--r-- | plugins/t/check_curl.t | 216 | ||||
-rw-r--r-- | plugins/t/check_http.t | 76 | ||||
-rwxr-xr-x | plugins/tests/check_curl.t | 497 | ||||
-rwxr-xr-x | plugins/tests/check_http.t | 9 | ||||
-rw-r--r-- | po/de.po | 6 |
18 files changed, 4252 insertions, 59 deletions
@@ -142,6 +142,7 @@ NP-VERSION-FILE /plugins/check_by_ssh /plugins/check_clamd /plugins/check_cluster +/plugins/check_curl /plugins/check_dbi /plugins/check_dig /plugins/check_disk @@ -202,6 +203,12 @@ NP-VERSION-FILE /plugins/stamp-h* /plugins/urlize +# /plugins/picohttpparser +/plugins/picohttpparser/Makefile +/plugins/picohttpparser/Makefile.in +/plugins/picohttpparser/.deps +/plugins/picohttpparser/libpicohttpparser.a + # /plugins/t/ /plugins/t/*.tmp diff --git a/.travis.yml b/.travis.yml index 946345c4..3d9fe64e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -51,6 +51,8 @@ install: - sudo apt-get install -qq --no-install-recommends autoconf automake - sudo apt-get install -qq --no-install-recommends faketime - sudo apt-get install -qq --no-install-recommends libmonitoring-plugin-perl + - sudo apt-get install -qq --no-install-recommends libcurl4-openssl-dev + - sudo apt-get install -qq --no-install-recommends liburiparser-dev - sudo apt-get install -qq --no-install-recommends squid # Trusty related dependencies (not yet provided) - test "$(dpkg -l | grep -E "mysql-(client|server)-[0-9].[0-9]" | grep -c ^ii)" -gt 0 || sudo apt-get install -qq --no-install-recommends mariadb-client mariadb-server diff --git a/ACKNOWLEDGEMENTS b/ACKNOWLEDGEMENTS index 50c714c3..d73be549 100644 --- a/ACKNOWLEDGEMENTS +++ b/ACKNOWLEDGEMENTS @@ -20,7 +20,7 @@ Using the DLPI support on SysV systems to get the host MAC address in check_dhcp Stenberg, Daniel Copyright (c) 1996 - 2004, Daniel Stenberg, <daniel@haxx.se> http://curl.haxx.se/ -Use of duplication of macros in m4/np_curl.m4 +Use of duplication of macros in m4/np_curl.m4 (slighly adapted for m4/uriparser.m4 too) Coreutils team Copyright (C) 91, 1995-2004 Free Software Foundation, Inc. @@ -31,3 +31,9 @@ Gnulib team Copyright (C) 2001, 2003, 2004, 2006 Free Software Foundation, Inc http://www.gnu.org/software/gnulib/ Use of lib files that originally were used from coreutils + +Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase, + Shigeo Mitsunari +picohttpparser +https://github.com/h2o/picohttpparser +Use of the library for HTTP header parsing in check_curl. diff --git a/REQUIREMENTS b/REQUIREMENTS index ac7b5935..f04a3f0e 100644 --- a/REQUIREMENTS +++ b/REQUIREMENTS @@ -11,6 +11,22 @@ check_ldaps, check_http --ssl, check_tcp --ssl, check_smtp --starttls - Requires openssl or gnutls libraries for SSL connections http://www.openssl.org, http://www.gnu.org/software/gnutls +check_curl: + - Requires libcurl 7.15.2 or later + http://www.haxx.se + - --ssl/-S and -C requires OpenSSL for certificate checks, otherwise + libcurl must be quite new to support CURLINFO_CERTINFO with + GnuTLS and NSS libraries: + - 7.42.0 or newer for GnuTLS + - 7.34.0 or newer for NSS + GnuTLS is known to create problems on some distributions with + self-signed certificate chains + http://www.openssl.org, http://www.gnu.org/software/gnutls, + http://www.mozilla.org/projects/security/pki/nss/, + other SSL implementations are currently not supported + - uriparser 0.7.5 or later + https://uriparser.github.io/ + check_fping: - Requires the fping utility distributed with SATAN. Either download and install SATAN or grab the fping program from diff --git a/configure.ac b/configure.ac index 08a0e782..4ce14094 100644 --- a/configure.ac +++ b/configure.ac @@ -385,6 +385,43 @@ if test "$ac_cv_header_wtsapi32_h" = "yes"; then AC_SUBST(WTSAPI32LIBS) fi +_can_enable_check_curl=no +dnl Check for cURL library +LIBCURL_CHECK_CONFIG(yes, 7.15.2, [ + _can_enable_check_curl=yes + LIBCURLINCLUDE="$LIBCURL_CPPFLAGS" + LIBCURLLIBS="$LIBCURL" + LIBCURLCFLAGS="$LIBCURL_CPPFLAGS" + AC_SUBST(LIBCURLINCLUDE) + AC_SUBST(LIBCURLLIBS) + AC_SUBST(LIBCURLCFLAGS) + ], [ + _can_enable_check_curl=no + AC_MSG_WARN([Skipping curl plugin]) + AC_MSG_WARN([install libcurl libs to compile this plugin (see REQUIREMENTS).]) +]) + +dnl Check for uriparser library +URIPARSER_CHECK(yes, 0.7.5, [ + URIPARSERINCLUDE="$URIPARSER_CPPFLAGS" + URIPARSERLIBS="$URIPARSER" + URIPARSERCFLAGS="$URIPARSER_CPPFLAGS" + AC_SUBST(URIPARSERINCLUDE) + AC_SUBST(URIPARSERLIBS) + AC_SUBST(URIPARSERCFLAGS) + ], [ + _can_enable_check_curl=no + AC_MSG_WARN([Skipping curl plugin]) + AC_MSG_WARN([install the uriparser library to compile this plugin (see REQUIREMENTS).]) +]) + +dnl prerequisites met, enable the plugin +if test x$_can_enable_check_curl = xyes; then + EXTRAS="$EXTRAS check_curl\$(EXEEXT)" +fi +AM_CONDITIONAL([WITH_CHECK_CURL], [test "$_can_enable_check_curl" = "yes"]) +AC_CONFIG_FILES([plugins/picohttpparser/Makefile]) + dnl Fallback to who(1) if the system doesn't provide an utmpx(5) interface if test "$ac_cv_header_utmpx_h" = "no" -a "$ac_cv_header_wtsapi32_h" = "no" then @@ -1886,4 +1923,5 @@ ACX_FEATURE([enable],[perl-modules]) ACX_FEATURE([with],[cgiurl]) ACX_FEATURE([with],[trusted-path]) ACX_FEATURE([enable],[libtap]) - +ACX_FEATURE([with],[libcurl]) +ACX_FEATURE([with],[uriparser]) diff --git a/m4/libcurl.m4 b/m4/libcurl.m4 new file mode 100644 index 00000000..53d694d0 --- /dev/null +++ b/m4/libcurl.m4 @@ -0,0 +1,272 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) 2006, David Shaw <dshaw@jabberwocky.com> +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.haxx.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +########################################################################### +# LIBCURL_CHECK_CONFIG ([DEFAULT-ACTION], [MINIMUM-VERSION], +# [ACTION-IF-YES], [ACTION-IF-NO]) +# ---------------------------------------------------------- +# David Shaw <dshaw@jabberwocky.com> May-09-2006 +# +# Checks for libcurl. DEFAULT-ACTION is the string yes or no to +# specify whether to default to --with-libcurl or --without-libcurl. +# If not supplied, DEFAULT-ACTION is yes. MINIMUM-VERSION is the +# minimum version of libcurl to accept. Pass the version as a regular +# version number like 7.10.1. If not supplied, any version is +# accepted. ACTION-IF-YES is a list of shell commands to run if +# libcurl was successfully found and passed the various tests. +# ACTION-IF-NO is a list of shell commands that are run otherwise. +# Note that using --without-libcurl does run ACTION-IF-NO. +# +# This macro #defines HAVE_LIBCURL if a working libcurl setup is +# found, and sets @LIBCURL@ and @LIBCURL_CPPFLAGS@ to the necessary +# values. Other useful defines are LIBCURL_FEATURE_xxx where xxx are +# the various features supported by libcurl, and LIBCURL_PROTOCOL_yyy +# where yyy are the various protocols supported by libcurl. Both xxx +# and yyy are capitalized. See the list of AH_TEMPLATEs at the top of +# the macro for the complete list of possible defines. Shell +# variables $libcurl_feature_xxx and $libcurl_protocol_yyy are also +# defined to 'yes' for those features and protocols that were found. +# Note that xxx and yyy keep the same capitalization as in the +# curl-config list (e.g. it's "HTTP" and not "http"). +# +# Users may override the detected values by doing something like: +# LIBCURL="-lcurl" LIBCURL_CPPFLAGS="-I/usr/myinclude" ./configure +# +# For the sake of sanity, this macro assumes that any libcurl that is +# found is after version 7.7.2, the first version that included the +# curl-config script. Note that it is very important for people +# packaging binary versions of libcurl to include this script! +# Without curl-config, we can only guess what protocols are available, +# or use curl_version_info to figure it out at runtime. + +AC_DEFUN([LIBCURL_CHECK_CONFIG], +[ + AH_TEMPLATE([LIBCURL_FEATURE_SSL],[Defined if libcurl supports SSL]) + AH_TEMPLATE([LIBCURL_FEATURE_KRB4],[Defined if libcurl supports KRB4]) + AH_TEMPLATE([LIBCURL_FEATURE_IPV6],[Defined if libcurl supports IPv6]) + AH_TEMPLATE([LIBCURL_FEATURE_LIBZ],[Defined if libcurl supports libz]) + AH_TEMPLATE([LIBCURL_FEATURE_ASYNCHDNS],[Defined if libcurl supports AsynchDNS]) + AH_TEMPLATE([LIBCURL_FEATURE_IDN],[Defined if libcurl supports IDN]) + AH_TEMPLATE([LIBCURL_FEATURE_SSPI],[Defined if libcurl supports SSPI]) + AH_TEMPLATE([LIBCURL_FEATURE_NTLM],[Defined if libcurl supports NTLM]) + + AH_TEMPLATE([LIBCURL_PROTOCOL_HTTP],[Defined if libcurl supports HTTP]) + AH_TEMPLATE([LIBCURL_PROTOCOL_HTTPS],[Defined if libcurl supports HTTPS]) + AH_TEMPLATE([LIBCURL_PROTOCOL_FTP],[Defined if libcurl supports FTP]) + AH_TEMPLATE([LIBCURL_PROTOCOL_FTPS],[Defined if libcurl supports FTPS]) + AH_TEMPLATE([LIBCURL_PROTOCOL_FILE],[Defined if libcurl supports FILE]) + AH_TEMPLATE([LIBCURL_PROTOCOL_TELNET],[Defined if libcurl supports TELNET]) + AH_TEMPLATE([LIBCURL_PROTOCOL_LDAP],[Defined if libcurl supports LDAP]) + AH_TEMPLATE([LIBCURL_PROTOCOL_DICT],[Defined if libcurl supports DICT]) + AH_TEMPLATE([LIBCURL_PROTOCOL_TFTP],[Defined if libcurl supports TFTP]) + AH_TEMPLATE([LIBCURL_PROTOCOL_RTSP],[Defined if libcurl supports RTSP]) + AH_TEMPLATE([LIBCURL_PROTOCOL_POP3],[Defined if libcurl supports POP3]) + AH_TEMPLATE([LIBCURL_PROTOCOL_IMAP],[Defined if libcurl supports IMAP]) + AH_TEMPLATE([LIBCURL_PROTOCOL_SMTP],[Defined if libcurl supports SMTP]) + + AC_ARG_WITH(libcurl, + AS_HELP_STRING([--with-libcurl=PREFIX],[look for the curl library in PREFIX/lib and headers in PREFIX/include]), + [_libcurl_with=$withval],[_libcurl_with=ifelse([$1],,[yes],[$1])]) + + if test "$_libcurl_with" != "no" ; then + + AC_PROG_AWK + + _libcurl_version_parse="eval $AWK '{split(\$NF,A,\".\"); X=256*256*A[[1]]+256*A[[2]]+A[[3]]; print X;}'" + + _libcurl_try_link=yes + + if test -d "$_libcurl_with" ; then + LIBCURL_CPPFLAGS="-I$withval/include" + _libcurl_ldflags="-L$withval/lib" + AC_PATH_PROG([_libcurl_config],[curl-config],[], + ["$withval/bin"]) + else + AC_PATH_PROG([_libcurl_config],[curl-config],[],[$PATH]) + fi + + if test x$_libcurl_config != "x" ; then + AC_CACHE_CHECK([for the version of libcurl], + [libcurl_cv_lib_curl_version], + [libcurl_cv_lib_curl_version=`$_libcurl_config --version | $AWK '{print $[]2}'`]) + + _libcurl_version=`echo $libcurl_cv_lib_curl_version | $_libcurl_version_parse` + _libcurl_wanted=`echo ifelse([$2],,[0],[$2]) | $_libcurl_version_parse` + + if test $_libcurl_wanted -gt 0 ; then + AC_CACHE_CHECK([for libcurl >= version $2], + [libcurl_cv_lib_version_ok], + [ + if test $_libcurl_version -ge $_libcurl_wanted ; then + libcurl_cv_lib_version_ok=yes + else + libcurl_cv_lib_version_ok=no + fi + ]) + fi + + if test $_libcurl_wanted -eq 0 || test x$libcurl_cv_lib_version_ok = xyes ; then + if test x"$LIBCURL_CPPFLAGS" = "x" ; then + LIBCURL_CPPFLAGS=`$_libcurl_config --cflags` + fi + if test x"$LIBCURL" = "x" ; then + LIBCURL=`$_libcurl_config --libs` + + # This is so silly, but Apple actually has a bug in their + # curl-config script. Fixed in Tiger, but there are still + # lots of Panther installs around. + case "${host}" in + powerpc-apple-darwin7*) + LIBCURL=`echo $LIBCURL | sed -e 's|-arch i386||g'` + ;; + esac + fi + + # All curl-config scripts support --feature + _libcurl_features=`$_libcurl_config --feature` + + # Is it modern enough to have --protocols? (7.12.4) + if test $_libcurl_version -ge 461828 ; then + _libcurl_protocols=`$_libcurl_config --protocols` + fi + else + _libcurl_try_link=no + fi + + unset _libcurl_wanted + fi + + if test $_libcurl_try_link = yes ; then + + # we didn't find curl-config, so let's see if the user-supplied + # link line (or failing that, "-lcurl") is enough. + LIBCURL=${LIBCURL-"$_libcurl_ldflags -lcurl"} + + AC_CACHE_CHECK([whether libcurl is usable], + [libcurl_cv_lib_curl_usable], + [ + _libcurl_save_cppflags=$CPPFLAGS + CPPFLAGS="$LIBCURL_CPPFLAGS $CPPFLAGS" + _libcurl_save_libs=$LIBS + LIBS="$LIBCURL $LIBS" + + AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <curl/curl.h>]],[[ +/* Try and use a few common options to force a failure if we are + missing symbols or can't link. */ +int x; +curl_easy_setopt(NULL,CURLOPT_URL,NULL); +x=CURL_ERROR_SIZE; +x=CURLOPT_WRITEFUNCTION; +x=CURLOPT_WRITEDATA; +x=CURLOPT_ERRORBUFFER; +x=CURLOPT_STDERR; +x=CURLOPT_VERBOSE; +if (x) {;} +]])],libcurl_cv_lib_curl_usable=yes,libcurl_cv_lib_curl_usable=no) + + CPPFLAGS=$_libcurl_save_cppflags + LIBS=$_libcurl_save_libs + unset _libcurl_save_cppflags + unset _libcurl_save_libs + ]) + + if test $libcurl_cv_lib_curl_usable = yes ; then + + # Does curl_free() exist in this version of libcurl? + # If not, fake it with free() + + _libcurl_save_cppflags=$CPPFLAGS + CPPFLAGS="$CPPFLAGS $LIBCURL_CPPFLAGS" + _libcurl_save_libs=$LIBS + LIBS="$LIBS $LIBCURL" + + AC_CHECK_FUNC(curl_free,, + AC_DEFINE(curl_free,free, + [Define curl_free() as free() if our version of curl lacks curl_free.])) + + CPPFLAGS=$_libcurl_save_cppflags + LIBS=$_libcurl_save_libs + unset _libcurl_save_cppflags + unset _libcurl_save_libs + + AC_DEFINE(HAVE_LIBCURL,1, + [Define to 1 if you have a functional curl library.]) + AC_SUBST(LIBCURL_CPPFLAGS) + AC_SUBST(LIBCURL) + + for _libcurl_feature in $_libcurl_features ; do + AC_DEFINE_UNQUOTED(AS_TR_CPP(libcurl_feature_$_libcurl_feature),[1]) + eval AS_TR_SH(libcurl_feature_$_libcurl_feature)=yes + done + + if test "x$_libcurl_protocols" = "x" ; then + + # We don't have --protocols, so just assume that all + # protocols are available + _libcurl_protocols="HTTP FTP FILE TELNET LDAP DICT TFTP" + + if test x$libcurl_feature_SSL = xyes ; then + _libcurl_protocols="$_libcurl_protocols HTTPS" + + # FTPS wasn't standards-compliant until version + # 7.11.0 (0x070b00 == 461568) + if test $_libcurl_version -ge 461568; then + _libcurl_protocols="$_libcurl_protocols FTPS" + fi + fi + + # RTSP, IMAP, POP3 and SMTP were added in + # 7.20.0 (0x071400 == 463872) + if test $_libcurl_version -ge 463872; then + _libcurl_protocols="$_libcurl_protocols RTSP IMAP POP3 SMTP" + fi + fi + + for _libcurl_protocol in $_libcurl_protocols ; do + AC_DEFINE_UNQUOTED(AS_TR_CPP(libcurl_protocol_$_libcurl_protocol),[1]) + eval AS_TR_SH(libcurl_protocol_$_libcurl_protocol)=yes + done + else + unset LIBCURL + unset LIBCURL_CPPFLAGS + fi + fi + + unset _libcurl_try_link + unset _libcurl_version_parse + unset _libcurl_config + unset _libcurl_feature + unset _libcurl_features + unset _libcurl_protocol + unset _libcurl_protocols + unset _libcurl_version + unset _libcurl_ldflags + fi + + if test x$_libcurl_with = xno || test x$libcurl_cv_lib_curl_usable != xyes ; then + # This is the IF-NO path + ifelse([$4],,:,[$4]) + else + # This is the IF-YES path + ifelse([$3],,:,[$3]) + fi + + unset _libcurl_with +])dnl diff --git a/m4/uriparser.m4 b/m4/uriparser.m4 new file mode 100644 index 00000000..dbb8a551 --- /dev/null +++ b/m4/uriparser.m4 @@ -0,0 +1,140 @@ +# (this check is rougly based on and inspired libcurl.m4) +# URIPARSER_CHECK ([DEFAULT-ACTION], [MINIMUM-VERSION], +# [ACTION-IF-YES], [ACTION-IF-NO]) +# Checks for uriparser library. DEFAULT-ACTION is the string yes or no to +# specify whether to default to --with-uriparser or --without-liburiparser. +# If not supplied, DEFAULT-ACTION is yes. MINIMUM-VERSION is the +# minimum version of uriparser to accept. Pass the version as a regular +# version number like 0.8.5. If not supplied, any version is +# accepted. ACTION-IF-YES is a list of shell commands to run if +# uriparser was successfully found and passed the various tests. +# ACTION-IF-NO is a list of shell commands that are run otherwise. +# Note that using --without-uriparser does run ACTION-IF-NO. +# +# This macro #defines HAVE_URIPARSER if a working uriparser setup is +# found, and sets @URIPARSER@ and @URIPARSER_CPPFLAGS@ to the necessary +# values. +# +# Users may override the detected values by doing something like: +# URIPARSER="-luriparser" URIPARSER_CPPFLAGS="-I/usr/myinclude" ./configure +# + +AC_DEFUN([URIPARSER_CHECK], +[ + AC_ARG_WITH(uriparser, + AS_HELP_STRING([--with-uriparser=PREFIX],[look for the uriparser library in PREFIX/lib and headers in PREFIX/include]), + [_uriparser_with=$withval],[_uriparser_with=ifelse([$1],,[yes],[$1])]) + + if test "$_uriparser_with" != "no" ; then + + _uriparser_try_link=yes + + AC_CHECK_PROG(PKGCONFIG,pkg-config,pkg-config,no) + + if test "x$URIPARSER" != "x" || test "x$URIPARSER_CPPFLAGS" != "x"; then + : + elif test -d "$_uriparser_with" ; then + URIPARSER_CPPFLAGS="-I$withval/include" + _uriparser_ldflags="-L$withval/lib" + + elif test x$PKGCONFIG != xno; then + + AC_CACHE_CHECK([for the version of uriparser], + [uriparser_cv_uriparser_version], + [uriparser_cv_uriparser_version=`$PKGCONFIG liburiparser --modversion`]) + + AC_PROG_AWK + + _uriparser_version_parse="eval $AWK '{split(\$NF,A,\".\"); X=256*256*A[[1]]+256*A[[2]]+A[[3]]; print X;}'" + + _uriparser_version=`echo $uriparser_cv_uriparser_version | $_uriparser_version_parse` + _uriparser_wanted=`echo ifelse([$2],,[0],[$2]) | $_uriparser_version_parse` + + if test $_uriparser_wanted -gt 0 ; then + AC_CACHE_CHECK([for uriparser >= version $2], + [uriparser_cv_lib_version_ok], + [ + if test $_uriparser_version -ge $_uriparser_wanted ; then + uriparser_cv_lib_version_ok=yes + else + uriparser_cv_lib_version_ok=no + fi + ]) + fi + + if test $_uriparser_wanted -eq 0 || test x$uriparser_cv_lib_version_ok = xyes ; then + if test x"$URIPARSER_CPPFLAGS" = "x" ; then + URIPARSER_CPPFLAGS=`$PKGCONFIG liburiparser --cflags` + fi + if test x"$URIPARSER" = "x" ; then + URIPARSER=`$PKGCONFIG liburiparser --libs` + fi + else + _uriparser_try_link=no + fi + + unset _uriparser_wanted + else + dnl no pkg-config, ok, do our best and set some defaults + URIPARSER_CPPFLAGS="-I/usr/include" + URIPARSER="-luriparser -L/usr/lib -L/usr/lib64 -L/usr/lib/x86_64-linux-gnu -L/usr/lib/i686-linux-gnu" + fi + + if test $_uriparser_try_link = yes ; then + + # let's see if the user-supplied + # link line (or failing that, "-luriparser") is enough. + URIPARSER=${URIPARSER-"$_uriparser_ldflags -luriparser"} + + AC_CACHE_CHECK([whether uriparser is usable], + [uriparser_cv_lib_uriparser_usable], + [ + _liburiparser_save_cppflags=$CPPFLAGS + CPPFLAGS="$URIPARSER_CPPFLAGS $CPPFLAGS" + _liburiparser_save_libs=$LIBS + LIBS="$URIPARSER $LIBS" + + AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <uriparser/Uri.h>]],[[ +/* Try and use a few common options to force a failure if we are + missing symbols or cannot link. */ +UriParserStateA state; +UriUriA uri; +state.uri = &uri; +char *location = "http://test.dom/dir/file.ext"; +int x = uriParseUriA (&state, location); +if (x == URI_SUCCESS) {;} +]])],uriparser_cv_lib_uriparser_usable=yes,uriparser_cv_lib_uriparser_usable=no) + + CPPFLAGS=$_liburiparser_save_cppflags + LIBS=$_liburiparser_save_libs + unset _liburiparser_save_cppflags + unset _liburiparser_save_libs + ]) + + if test $uriparser_cv_lib_uriparser_usable = yes ; then + AC_DEFINE(HAVE_URIPARSER,1, + [Define to 1 if you have a functional uriparser library.]) + AC_SUBST(URIPARSER_CPPFLAGS) + AC_SUBST(URIPARSER) + else + unset URIPARSER + unset URIPARSER_CPPFLAGS + fi + fi + + unset _uriparser_try_link + unset _uriparser_version_parse + unset _uriparser_version + unset _uriparser_ldflags + fi + + if test x$_uriparser_with = xno || test x$uriparser_cv_lib_uriparser_usable != xyes ; then + # This is the IF-NO path + ifelse([$4],,:,[$4]) + else + # This is the IF-YES path + ifelse([$3],,:,[$3]) + fi + + unset _uriparser_with +])dnl diff --git a/plugins/Makefile.am b/plugins/Makefile.am index 0ddf9bd1..3fde54d6 100644 --- a/plugins/Makefile.am +++ b/plugins/Makefile.am @@ -38,7 +38,9 @@ check_tcp_programs = check_ftp check_imap check_nntp check_pop \ EXTRA_PROGRAMS = check_mysql check_radius check_pgsql check_snmp check_hpjd \ check_swap check_fping check_ldap check_game check_dig \ check_nagios check_by_ssh check_dns check_nt check_ide_smart \ - check_procs check_mysql_query check_apt check_dbi + check_procs check_mysql_query check_apt check_dbi check_curl + +SUBDIRS = picohttpparser EXTRA_DIST = t tests @@ -69,6 +71,9 @@ test-debug: check_apt_LDADD = $(BASEOBJS) check_cluster_LDADD = $(BASEOBJS) +check_curl_CFLAGS = $(AM_CFLAGS) $(LIBCURLCFLAGS) $(URIPARSERCFLAGS) $(LIBCURLINCLUDE) $(URIPARSERINCLUDE) -Ipicohttpparser +check_curl_CPPFLAGS = $(AM_CPPFLAGS) $(LIBCURLCFLAGS) $(URIPARSERCFLAGS) $(LIBCURLINCLUDE) $(URIPARSERINCLUDE) -Ipicohttpparser +check_curl_LDADD = $(NETLIBS) $(LIBCURLLIBS) $(SSLOBJS) $(URIPARSERLIBS) picohttpparser/libpicohttpparser.a check_dbi_LDADD = $(NETLIBS) $(DBILIBS) check_dig_LDADD = $(NETLIBS) check_disk_LDADD = $(BASEOBJS) @@ -89,7 +94,7 @@ check_mysql_query_CFLAGS = $(AM_CFLAGS) $(MYSQLCFLAGS) check_mysql_query_CPPFLAGS = $(AM_CPPFLAGS) $(MYSQLINCLUDE) check_mysql_query_LDADD = $(NETLIBS) $(MYSQLLIBS) check_nagios_LDADD = $(BASEOBJS) -check_nt_LDADD = $(NETLIBS) +check_nt_LDADD = $(NETLIBS) check_ntp_LDADD = $(NETLIBS) $(MATHLIBS) check_ntp_peer_LDADD = $(NETLIBS) $(MATHLIBS) check_nwstat_LDADD = $(NETLIBS) diff --git a/plugins/check_curl.c b/plugins/check_curl.c new file mode 100644 index 00000000..637e9ba3 --- /dev/null +++ b/plugins/check_curl.c @@ -0,0 +1,2268 @@ +/***************************************************************************** +* +* Monitoring check_curl plugin +* +* License: GPL +* Copyright (c) 1999-2018 Monitoring Plugins Development Team +* +* Description: +* +* This file contains the check_curl plugin +* +* This plugin tests the HTTP service on the specified host. It can test +* normal (http) and secure (https) servers, follow redirects, search for +* strings and regular expressions, check connection times, and report on +* certificate expiration times. +* +* This plugin uses functions from the curl library, see +* http://curl.haxx.se +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see <http://www.gnu.org/licenses/>. +* +* +*****************************************************************************/ +const char *progname = "check_http"; + +const char *copyright = "2006-2018"; +const char *email = "devel@monitoring-plugins.org"; + +#include <ctype.h> + +#include "common.h" +#include "utils.h" + +#ifndef LIBCURL_PROTOCOL_HTTP +#error libcurl compiled without HTTP support, compiling check_curl plugin does not makes a lot of sense +#endif + +#include "curl/curl.h" +#include "curl/easy.h" + +#include "picohttpparser.h" + +#include "uriparser/Uri.h" + +#include <arpa/inet.h> + +#define MAKE_LIBCURL_VERSION(major, minor, patch) ((major)*0x10000 + (minor)*0x100 + (patch)) + +#define DEFAULT_BUFFER_SIZE 2048 +#define DEFAULT_SERVER_URL "/" +#define HTTP_EXPECT "HTTP/1." +#define DEFAULT_MAX_REDIRS 15 +#define INET_ADDR_MAX_SIZE INET6_ADDRSTRLEN +enum { + MAX_IPV4_HOSTLENGTH = 255, + HTTP_PORT = 80, + HTTPS_PORT = 443, + MAX_PORT = 65535 +}; + +enum { + STICKY_NONE = 0, + STICKY_HOST = 1, + STICKY_PORT = 2 +}; + +enum { + FOLLOW_HTTP_CURL = 0, + FOLLOW_LIBCURL = 1 +}; + +/* for buffers for header and body */ +typedef struct { + char *buf; + size_t buflen; + size_t bufsize; +} curlhelp_write_curlbuf; + +/* for buffering the data sent in PUT */ +typedef struct { + char *buf; + size_t buflen; + off_t pos; +} curlhelp_read_curlbuf; + +/* for parsing the HTTP status line */ +typedef struct { + int http_major; /* major version of the protocol, always 1 (HTTP/0.9 + * never reached the big internet most likely) */ + int http_minor; /* minor version of the protocol, usually 0 or 1 */ + int http_code; /* HTTP return code as in RFC 2145 */ + int http_subcode; /* Microsoft IIS extension, HTTP subcodes, see + * http://support.microsoft.com/kb/318380/en-us */ + const char *msg; /* the human readable message */ + char *first_line; /* a copy of the first line */ +} curlhelp_statusline; + +/* to know the underlying SSL library used by libcurl */ +typedef enum curlhelp_ssl_library { + CURLHELP_SSL_LIBRARY_UNKNOWN, + CURLHELP_SSL_LIBRARY_OPENSSL, + CURLHELP_SSL_LIBRARY_LIBRESSL, + CURLHELP_SSL_LIBRARY_GNUTLS, + CURLHELP_SSL_LIBRARY_NSS +} curlhelp_ssl_library; + +enum { + REGS = 2, + MAX_RE_SIZE = 256 +}; +#include "regex.h" +regex_t preg; +regmatch_t pmatch[REGS]; +char regexp[MAX_RE_SIZE]; +int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE; +int errcode; +int invert_regex = 0; + +char *server_address; +char *host_name; +char *server_url = 0; +char server_ip[DEFAULT_BUFFER_SIZE]; +struct curl_slist *server_ips = NULL; +int specify_port = FALSE; +unsigned short server_port = HTTP_PORT; +unsigned short virtual_port = 0; +int host_name_length; +char output_header_search[30] = ""; +char output_string_search[30] = ""; +char *warning_thresholds = NULL; +char *critical_thresholds = NULL; +int days_till_exp_warn, days_till_exp_crit; +thresholds *thlds; +char user_agent[DEFAULT_BUFFER_SIZE]; +int verbose = 0; +int show_extended_perfdata = FALSE; +int min_page_len = 0; +int max_page_len = 0; +int redir_depth = 0; +int max_depth = DEFAULT_MAX_REDIRS; +char *http_method = NULL; +char *http_post_data = NULL; +char *http_content_type = NULL; +CURL *curl; +struct curl_slist *header_list = NULL; +curlhelp_write_curlbuf body_buf; +curlhelp_write_curlbuf header_buf; +curlhelp_statusline status_line; +curlhelp_read_curlbuf put_buf; +char http_header[DEFAULT_BUFFER_SIZE]; +long code; +long socket_timeout = DEFAULT_SOCKET_TIMEOUT; +double total_time; +double time_connect; +double time_appconnect; +double time_headers; +double time_firstbyte; +char errbuf[CURL_ERROR_SIZE+1]; +CURLcode res; +char url[DEFAULT_BUFFER_SIZE]; +char msg[DEFAULT_BUFFER_SIZE]; +char perfstring[DEFAULT_BUFFER_SIZE]; +char header_expect[MAX_INPUT_BUFFER] = ""; +char string_expect[MAX_INPUT_BUFFER] = ""; +char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT; +int server_expect_yn = 0; +char user_auth[MAX_INPUT_BUFFER] = ""; +char proxy_auth[MAX_INPUT_BUFFER] = ""; +char **http_opt_headers; +int http_opt_headers_count = 0; +int display_html = FALSE; +int onredirect = STATE_OK; +int followmethod = FOLLOW_HTTP_CURL; +int followsticky = STICKY_NONE; +int use_ssl = FALSE; +int use_sni = TRUE; +int check_cert = FALSE; +typedef union { + struct curl_slist* to_info; + struct curl_certinfo* to_certinfo; +} cert_ptr_union; +cert_ptr_union cert_ptr; +int ssl_version = CURL_SSLVERSION_DEFAULT; +char *client_cert = NULL; +char *client_privkey = NULL; +char *ca_cert = NULL; +int is_openssl_callback = FALSE; +#if defined(HAVE_SSL) && defined(USE_OPENSSL) +X509 *cert = NULL; +#endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ +int no_body = FALSE; +int maximum_age = -1; +int address_family = AF_UNSPEC; +curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; + +int process_arguments (int, char**); +void handle_curl_option_return_code (CURLcode res, const char* option); +int check_http (void); +void redir (curlhelp_write_curlbuf*); +char *perfd_time (double microsec); +char *perfd_time_connect (double microsec); +char *perfd_time_ssl (double microsec); +char *perfd_time_firstbyte (double microsec); +char *perfd_time_headers (double microsec); +char *perfd_time_transfer (double microsec); +char *perfd_size (int page_len); +void print_help (void); +void print_usage (void); +void print_curl_version (void); +int curlhelp_initwritebuffer (curlhelp_write_curlbuf*); +int curlhelp_buffer_write_callback (void*, size_t , size_t , void*); +void curlhelp_freewritebuffer (curlhelp_write_curlbuf*); +int curlhelp_initreadbuffer (curlhelp_read_curlbuf *, const char *, size_t); +int curlhelp_buffer_read_callback (void *, size_t , size_t , void *); +void curlhelp_freereadbuffer (curlhelp_read_curlbuf *); +curlhelp_ssl_library curlhelp_get_ssl_library (CURL*); +const char* curlhelp_get_ssl_library_string (curlhelp_ssl_library); +int net_noopenssl_check_certificate (cert_ptr_union*, int, int); + +int curlhelp_parse_statusline (const char*, curlhelp_statusline *); +void curlhelp_free_statusline (curlhelp_statusline *); +char *get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header); +int check_document_dates (const curlhelp_write_curlbuf *, char (*msg)[DEFAULT_BUFFER_SIZE]); +int get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_write_curlbuf* body_buf); + +#if defined(HAVE_SSL) && defined(USE_OPENSSL) +int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit); +#endif /* defined(HAVE_SSL) && defined(USE_OPENSSL) */ + +void remove_newlines (char *); +void test_file (char *); + +int +main (int argc, char **argv) +{ + int result = STATE_UNKNOWN; + + setlocale (LC_ALL, ""); + bindtextdomain (PACKAGE, LOCALEDIR); + textdomain (PACKAGE); + + /* Parse extra opts if any */ + argv = np_extra_opts (&argc, argv, progname); + + /* set defaults */ + snprintf( user_agent, DEFAULT_BUFFER_SIZE, "%s/v%s (monitoring-plugins %s, %s)", + progname, NP_VERSION, VERSION, curl_version()); + + /* parse arguments */ + if (process_arguments (argc, argv) == ERROR) + usage4 (_("Could not parse arguments")); + + if (display_html == TRUE) + printf ("<A HREF=\"%s://%s:%d%s\" target=\"_blank\">", + use_ssl ? "https" : "http", + host_name ? host_name : server_address, + virtual_port ? virtual_port : server_port, + server_url); + + result = check_http (); + return result; +} + +#ifdef HAVE_SSL +#ifdef USE_OPENSSL + +int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) +{ + /* TODO: we get all certificates of the chain, so which ones + * should we test? + * TODO: is the last certificate always the server certificate? + */ + cert = X509_STORE_CTX_get_current_cert(x509_ctx); + return 1; +} + +CURLcode sslctxfun(CURL *curl, SSL_CTX *sslctx, void *parm) +{ + SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER, verify_callback); + + return CURLE_OK; +} + +#endif /* USE_OPENSSL */ +#endif /* HAVE_SSL */ + +/* Checks if the server 'reply' is one of the expected 'statuscodes' */ +static int +expected_statuscode (const char *reply, const char *statuscodes) +{ + char *expected, *code; + int result = 0; + + if ((expected = strdup (statuscodes)) == NULL) + die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n")); + + for (code = strtok (expected, ","); code != NULL; code = strtok (NULL, ",")) + if (strstr (reply, code) != NULL) { + result = 1; + break; + } + + free (expected); + return result; +} + +void +handle_curl_option_return_code (CURLcode res, const char* option) +{ + if (res != CURLE_OK) { + snprintf (msg, DEFAULT_BUFFER_SIZE, _("Error while setting cURL option '%s': cURL returned %d - %s"), + option, res, curl_easy_strerror(res)); + die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } +} + +int +check_http (void) +{ + int result = STATE_OK; + int page_len = 0; + int i; + char *force_host_header = NULL; + + /* initialize curl */ + if (curl_global_init (CURL_GLOBAL_DEFAULT) != CURLE_OK) + die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_global_init failed\n"); + + if ((curl = curl_easy_init()) == NULL) + die (STATE_UNKNOWN, "HTTP UNKNOWN - curl_easy_init failed\n"); + + if (verbose >= 1) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_VERBOSE, TRUE), "CURLOPT_VERBOSE"); + + /* print everything on stdout like check_http would do */ + handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_STDERR, stdout), "CURLOPT_STDERR"); + + /* initialize buffer for body of the answer */ + if (curlhelp_initwritebuffer(&body_buf) < 0) + die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for body\n"); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_WRITEFUNCTION"); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEDATA, (void *)&body_buf), "CURLOPT_WRITEDATA"); + + /* initialize buffer for header of the answer */ + if (curlhelp_initwritebuffer( &header_buf ) < 0) + die (STATE_UNKNOWN, "HTTP CRITICAL - out of memory allocating buffer for header\n" ); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_HEADERFUNCTION, (curl_write_callback)curlhelp_buffer_write_callback), "CURLOPT_HEADERFUNCTION"); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_WRITEHEADER, (void *)&header_buf), "CURLOPT_WRITEHEADER"); + + /* set the error buffer */ + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, errbuf), "CURLOPT_ERRORBUFFER"); + + /* set timeouts */ + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, socket_timeout), "CURLOPT_CONNECTTIMEOUT"); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_TIMEOUT, socket_timeout), "CURLOPT_TIMEOUT"); + + /* compose URL: use the address we want to connect to, set Host: header later */ + snprintf (url, DEFAULT_BUFFER_SIZE, "%s://%s:%d%s", + use_ssl ? "https" : "http", + use_ssl ? host_name : server_address, + server_port, + server_url + ); + + if (verbose>=1) + printf ("* curl CURLOPT_URL: %s\n", url); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, url), "CURLOPT_URL"); + + /* extract proxy information for legacy proxy https requests */ + if (!strcmp(http_method, "CONNECT") || strstr(server_url, "http") == server_url) { + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXY, server_address), "CURLOPT_PROXY"); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXYPORT, (long)server_port), "CURLOPT_PROXYPORT"); + if (verbose>=2) + printf ("* curl CURLOPT_PROXY: %s:%d\n", server_address, server_port); + http_method = "GET"; + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_URL, server_url), "CURLOPT_URL"); + } + + /* set HTTP method */ + if (http_method) { + if (!strcmp(http_method, "POST")) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POST, 1), "CURLOPT_POST"); + else if (!strcmp(http_method, "PUT")) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_UPLOAD, 1), "CURLOPT_UPLOAD"); + else + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CUSTOMREQUEST, http_method), "CURLOPT_CUSTOMREQUEST"); + } + + /* check if Host header is explicitly set in options */ + if (http_opt_headers_count) { + for (i = 0; i < http_opt_headers_count ; i++) { + if (strncmp(http_opt_headers[i], "Host:", 5) == 0) { + force_host_header = http_opt_headers[i]; + } + } + } + + /* set hostname (virtual hosts), not needed if CURLOPT_CONNECT_TO is used, but left in anyway */ + if(host_name != NULL && force_host_header == NULL) { + if((virtual_port != HTTP_PORT && !use_ssl) || (virtual_port != HTTPS_PORT && use_ssl)) { + snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s:%d", host_name, virtual_port); + } else { + snprintf(http_header, DEFAULT_BUFFER_SIZE, "Host: %s", host_name); + } + header_list = curl_slist_append (header_list, http_header); + } + + /* always close connection, be nice to servers */ + snprintf (http_header, DEFAULT_BUFFER_SIZE, "Connection: close"); + header_list = curl_slist_append (header_list, http_header); + + /* attach additional headers supplied by the user */ + /* optionally send any other header tag */ + if (http_opt_headers_count) { + for (i = 0; i < http_opt_headers_count ; i++) { + header_list = curl_slist_append (header_list, http_opt_headers[i]); + } + /* This cannot be free'd here because a redirection will then try to access this and segfault */ + /* Covered in a testcase in tests/check_http.t */ + /* free(http_opt_headers); */ + } + + /* set HTTP headers */ + handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPHEADER, header_list ), "CURLOPT_HTTPHEADER"); + +#ifdef LIBCURL_FEATURE_SSL + + /* set SSL version, warn about unsecure or unsupported versions */ + if (use_ssl) { + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLVERSION, ssl_version), "CURLOPT_SSLVERSION"); + } + + /* client certificate and key to present to server (SSL) */ + if (client_cert) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLCERT, client_cert), "CURLOPT_SSLCERT"); + if (client_privkey) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSLKEY, client_privkey), "CURLOPT_SSLKEY"); + if (ca_cert) { + /* per default if we have a CA verify both the peer and the + * hostname in the certificate, can be switched off later */ + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CAINFO, ca_cert), "CURLOPT_CAINFO"); + handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER"); + handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST"); + } else { + /* backward-compatible behaviour, be tolerant in checks + * TODO: depending on more options have aspects we want + * to be less tolerant about ssl verfications + */ + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0), "CURLOPT_SSL_VERIFYPEER"); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0), "CURLOPT_SSL_VERIFYHOST"); + } + + /* detect SSL library used by libcurl */ + ssl_library = curlhelp_get_ssl_library (curl); + + /* try hard to get a stack of certificates to verify against */ + if (check_cert) { +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) + /* inform curl to report back certificates */ + switch (ssl_library) { + case CURLHELP_SSL_LIBRARY_OPENSSL: + case CURLHELP_SSL_LIBRARY_LIBRESSL: + /* set callback to extract certificate with OpenSSL context function (works with + * OpenSSL-style libraries only!) */ +#ifdef USE_OPENSSL + /* libcurl and monitoring plugins built with OpenSSL, good */ + handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION"); + is_openssl_callback = TRUE; +#else /* USE_OPENSSL */ +#endif /* USE_OPENSSL */ + /* libcurl is built with OpenSSL, monitoring plugins, so falling + * back to manually extracting certificate information */ + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); + break; + + case CURLHELP_SSL_LIBRARY_NSS: +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + /* NSS: support for CERTINFO is implemented since 7.34.0 */ + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); +#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n", curlhelp_get_ssl_library_string (ssl_library)); +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + break; + + case CURLHELP_SSL_LIBRARY_GNUTLS: +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) + /* GnuTLS: support for CERTINFO is implemented since 7.42.0 */ + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_CERTINFO, 1L), "CURLOPT_CERTINFO"); +#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */ + die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (libcurl linked with SSL library '%s' is too old)\n", curlhelp_get_ssl_library_string (ssl_library)); +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 42, 0) */ + break; + + case CURLHELP_SSL_LIBRARY_UNKNOWN: + default: + die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (unknown SSL library '%s', must implement first)\n", curlhelp_get_ssl_library_string (ssl_library)); + break; + } +#else /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ + /* old libcurl, our only hope is OpenSSL, otherwise we are out of luck */ + if (ssl_library == CURLHELP_SSL_LIBRARY_OPENSSL || ssl_library == CURLHELP_SSL_LIBRARY_LIBRESSL) + handle_curl_option_return_code (curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun), "CURLOPT_SSL_CTX_FUNCTION"); + else + die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates (no CURLOPT_SSL_CTX_FUNCTION, no OpenSSL library or libcurl too old and has no CURLOPT_CERTINFO)\n"); +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 1) */ + } + +#endif /* LIBCURL_FEATURE_SSL */ + + /* set default or user-given user agent identification */ + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERAGENT, user_agent), "CURLOPT_USERAGENT"); + + /* proxy-authentication */ + if (strcmp(proxy_auth, "")) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_PROXYUSERPWD, proxy_auth), "CURLOPT_PROXYUSERPWD"); + + /* authentication */ + if (strcmp(user_auth, "")) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_USERPWD, user_auth), "CURLOPT_USERPWD"); + + /* TODO: parameter auth method, bitfield of following methods: + * CURLAUTH_BASIC (default) + * CURLAUTH_DIGEST + * CURLAUTH_DIGEST_IE + * CURLAUTH_NEGOTIATE + * CURLAUTH_NTLM + * CURLAUTH_NTLM_WB + * + * convenience tokens for typical sets of methods: + * CURLAUTH_ANYSAFE: most secure, without BASIC + * or CURLAUTH_ANY: most secure, even BASIC if necessary + * + * handle_curl_option_return_code (curl_easy_setopt( curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST ), "CURLOPT_HTTPAUTH"); + */ + + /* handle redirections */ + if (onredirect == STATE_DEPENDENT) { + if( followmethod == FOLLOW_LIBCURL ) { + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1), "CURLOPT_FOLLOWLOCATION"); + + /* default -1 is infinite, not good, could lead to zombie plugins! + Setting it to one bigger than maximal limit to handle errors nicely below + */ + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_MAXREDIRS, max_depth+1), "CURLOPT_MAXREDIRS"); + + /* for now allow only http and https (we are a http(s) check plugin in the end) */ +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS), "CURLOPT_REDIRECT_PROTOCOLS"); +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 19, 4) */ + + /* TODO: handle the following aspects of redirection, make them + * command line options too later: + CURLOPT_POSTREDIR: method switch + CURLINFO_REDIRECT_URL: custom redirect option + CURLOPT_REDIRECT_PROTOCOLS: allow people to step outside safe protocols + CURLINFO_REDIRECT_COUNT: get the number of redirects, print it, maybe a range option here is nice like for expected page size? + */ + } else { + /* old style redirection is handled below */ + } + } + + /* no-body */ + if (no_body) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_NOBODY, 1), "CURLOPT_NOBODY"); + + /* IPv4 or IPv6 forced DNS resolution */ + if (address_family == AF_UNSPEC) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_WHATEVER)"); + else if (address_family == AF_INET) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V4)"); +#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6) + else if (address_family == AF_INET6) + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6), "CURLOPT_IPRESOLVE(CURL_IPRESOLVE_V6)"); +#endif + + /* either send http POST data (any data, not only POST)*/ + if (!strcmp(http_method, "POST") ||!strcmp(http_method, "PUT")) { + /* set content of payload for POST and PUT */ + if (http_content_type) { + snprintf (http_header, DEFAULT_BUFFER_SIZE, "Content-Type: %s", http_content_type); + header_list = curl_slist_append (header_list, http_header); + } + /* NULL indicates "HTTP Continue" in libcurl, provide an empty string + * in case of no POST/PUT data */ + if (!http_post_data) + http_post_data = ""; + if (!strcmp(http_method, "POST")) { + /* POST method, set payload with CURLOPT_POSTFIELDS */ + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_POSTFIELDS, http_post_data), "CURLOPT_POSTFIELDS"); + } else if (!strcmp(http_method, "PUT")) { + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READFUNCTION, (curl_read_callback)curlhelp_buffer_read_callback), "CURLOPT_READFUNCTION"); + curlhelp_initreadbuffer (&put_buf, http_post_data, strlen (http_post_data)); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_READDATA, (void *)&put_buf), "CURLOPT_READDATA"); + handle_curl_option_return_code (curl_easy_setopt (curl, CURLOPT_INFILESIZE, (curl_off_t)strlen (http_post_data)), "CURLOPT_INFILESIZE"); + } + } + + /* do the request */ + res = curl_easy_perform(curl); + + if (verbose>=2 && http_post_data) + printf ("**** REQUEST CONTENT ****\n%s\n", http_post_data); + + /* free header and server IP resolve lists, we don't need it anymore */ + curl_slist_free_all (header_list); header_list = NULL; + curl_slist_free_all (server_ips); server_ips = NULL; + + /* Curl errors, result in critical Nagios state */ + if (res != CURLE_OK) { + snprintf (msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: cURL returned %d - %s"), + server_port, res, curl_easy_strerror(res)); + die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + + /* certificate checks */ +#ifdef LIBCURL_FEATURE_SSL + if (use_ssl == TRUE) { + if (check_cert == TRUE) { + if (is_openssl_callback) { +#ifdef USE_OPENSSL + /* check certificate with OpenSSL functions, curl has been built against OpenSSL + * and we actually have OpenSSL in the monitoring tools + */ + result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); + return result; +#else /* USE_OPENSSL */ + die (STATE_CRITICAL, "HTTP CRITICAL - Cannot retrieve certificates - OpenSSL callback used and not linked against OpenSSL\n"); +#endif /* USE_OPENSSL */ + } else { + int i; + struct curl_slist *slist; + + cert_ptr.to_info = NULL; + res = curl_easy_getinfo (curl, CURLINFO_CERTINFO, &cert_ptr.to_info); + if (!res && cert_ptr.to_info) { +#ifdef USE_OPENSSL + /* We have no OpenSSL in libcurl, but we can use OpenSSL for X509 cert parsing + * We only check the first certificate and assume it's the one of the server + */ + const char* raw_cert = NULL; + for (i = 0; i < cert_ptr.to_certinfo->num_of_certs; i++) { + for (slist = cert_ptr.to_certinfo->certinfo[i]; slist; slist = slist->next) { + if (verbose >= 2) + printf ("%d ** %s\n", i, slist->data); + if (strncmp (slist->data, "Cert:", 5) == 0) { + raw_cert = &slist->data[5]; + goto GOT_FIRST_CERT; + } + } + } +GOT_FIRST_CERT: + if (!raw_cert) { + snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates from CERTINFO information - certificate data was empty")); + die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + BIO* cert_BIO = BIO_new (BIO_s_mem()); + BIO_write (cert_BIO, raw_cert, strlen(raw_cert)); + cert = PEM_read_bio_X509 (cert_BIO, NULL, NULL, NULL); + if (!cert) { + snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot read certificate from CERTINFO information - BIO error")); + die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + BIO_free (cert_BIO); + result = np_net_ssl_check_certificate(cert, days_till_exp_warn, days_till_exp_crit); + return result; +#else /* USE_OPENSSL */ + /* We assume we don't have OpenSSL and np_net_ssl_check_certificate at our disposal, + * so we use the libcurl CURLINFO data + */ + result = net_noopenssl_check_certificate(&cert_ptr, days_till_exp_warn, days_till_exp_crit); + return result; +#endif /* USE_OPENSSL */ + } else { + snprintf (msg, DEFAULT_BUFFER_SIZE, _("Cannot retrieve certificates - cURL returned %d - %s"), + res, curl_easy_strerror(res)); + die (STATE_CRITICAL, "HTTP CRITICAL - %s\n", msg); + } + } + } + } +#endif /* LIBCURL_FEATURE_SSL */ + + /* we got the data and we executed the request in a given time, so we can append + * performance data to the answer always + */ + handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_TOTAL_TIME, &total_time), "CURLINFO_TOTAL_TIME"); + page_len = get_content_length(&header_buf, &body_buf); + if(show_extended_perfdata) { + handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &time_connect), "CURLINFO_CONNECT_TIME"); + handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_APPCONNECT_TIME, &time_appconnect), "CURLINFO_APPCONNECT_TIME"); + handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &time_headers), "CURLINFO_PRETRANSFER_TIME"); + handle_curl_option_return_code (curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &time_firstbyte), "CURLINFO_STARTTRANSFER_TIME"); + snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s %s %s %s %s %s", + perfd_time(total_time), + perfd_size(page_len), + perfd_time_connect(time_connect), + use_ssl == TRUE ? perfd_time_ssl (time_appconnect-time_connect) : "", + perfd_time_headers(time_headers - time_appconnect), + perfd_time_firstbyte(time_firstbyte - time_headers), + perfd_time_transfer(total_time-time_firstbyte) + ); + } else { + snprintf(perfstring, DEFAULT_BUFFER_SIZE, "%s %s", + perfd_time(total_time), + perfd_size(page_len) + ); + } + + /* return a CRITICAL status if we couldn't read any data */ + if (strlen(header_buf.buf) == 0 && strlen(body_buf.buf) == 0) + die (STATE_CRITICAL, _("HTTP CRITICAL - No header received from host\n")); + + /* get status line of answer, check sanity of HTTP code */ + if (curlhelp_parse_statusline (header_buf.buf, &status_line) < 0) { + snprintf (msg, DEFAULT_BUFFER_SIZE, "Unparsable status line in %.3g seconds response time|%s\n", + total_time, perfstring); + die (STATE_CRITICAL, "HTTP CRITICAL HTTP/1.x %ld unknown - %s", code, msg); + } + + /* get result code from cURL */ + handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &code), "CURLINFO_RESPONSE_CODE"); + if (verbose>=2) + printf ("* curl CURLINFO_RESPONSE_CODE is %ld\n", code); + + /* print status line, header, body if verbose */ + if (verbose >= 2) { + printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header_buf.buf, + (no_body ? " [[ skipped ]]" : body_buf.buf)); + } + + /* make sure the status line matches the response we are looking for */ + if (!expected_statuscode(status_line.first_line, server_expect)) { + if (server_port == HTTP_PORT) + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host: %s\n"), status_line.first_line); + else + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Invalid HTTP response received from host on port %d: %s\n"), server_port, status_line.first_line); + die (STATE_CRITICAL, "HTTP CRITICAL - %s", msg); + } + + if( server_expect_yn ) { + snprintf(msg, DEFAULT_BUFFER_SIZE, _("Status line output matched \"%s\" - "), server_expect); + if (verbose) + printf ("%s\n",msg); + result = STATE_OK; + } + else { + /* illegal return codes result in a critical state */ + if (code >= 600 || code < 100) { + die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%d, %.40s)\n"), status_line.http_code, status_line.msg); + /* server errors result in a critical state */ + } else if (code >= 500) { + result = STATE_CRITICAL; + /* client errors result in a warning state */ + } else if (code >= 400) { + result = STATE_WARNING; + /* check redirected page if specified */ + } else if (code >= 300) { + if (onredirect == STATE_DEPENDENT) { + if( followmethod == FOLLOW_LIBCURL ) { + code = status_line.http_code; + } else { + /* old check_http style redirection, if we come + * back here, we are in the same status as with + * the libcurl method + */ + redir (&header_buf); + } + } else { + /* this is a specific code in the command line to + * be returned when a redirection is encoutered + */ + } + result = max_state_alt (onredirect, result); + /* all other codes are considered ok */ + } else { + result = STATE_OK; + } + } + + /* libcurl redirection internally, handle error states here */ + if( followmethod == FOLLOW_LIBCURL ) { + handle_curl_option_return_code (curl_easy_getinfo (curl, CURLINFO_REDIRECT_COUNT, &redir_depth), "CURLINFO_REDIRECT_COUNT"); + if (verbose >= 2) + printf(_("* curl LIBINFO_REDIRECT_COUNT is %d\n"), redir_depth); + if (redir_depth > max_depth) { + snprintf (msg, DEFAULT_BUFFER_SIZE, "maximum redirection depth %d exceeded in libcurl", + max_depth); + die (STATE_WARNING, "HTTP WARNING - %s", msg); + } + } + + /* check status codes, set exit status accordingly */ + if( status_line.http_code != code ) { + die (STATE_CRITICAL, _("HTTP CRITICAL HTTP/%d.%d %d %s - different HTTP codes (cUrl has %ld)\n"), + status_line.http_major, status_line.http_minor, + status_line.http_code, status_line.msg, code); + } + + if (maximum_age >= 0) { + result = max_state_alt(check_document_dates(&header_buf, &msg), result); + } + + /* Page and Header content checks go here */ + + if (strlen (header_expect)) { + if (!strstr (header_buf.buf, header_expect)) { + strncpy(&output_header_search[0],header_expect,sizeof(output_header_search)); + if(output_header_search[sizeof(output_header_search)-1]!='\0') { + bcopy("...",&output_header_search[sizeof(output_header_search)-4],4); + } + 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); + result = STATE_CRITICAL; + } + } + + if (strlen (string_expect)) { + if (!strstr (body_buf.buf, string_expect)) { + strncpy(&output_string_search[0],string_expect,sizeof(output_string_search)); + if(output_string_search[sizeof(output_string_search)-1]!='\0') { + bcopy("...",&output_string_search[sizeof(output_string_search)-4],4); + } + 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); + result = STATE_CRITICAL; + } + } + + if (strlen (regexp)) { + errcode = regexec (&preg, body_buf.buf, REGS, pmatch, 0); + if ((errcode == 0 && invert_regex == 0) || (errcode == REG_NOMATCH && invert_regex == 1)) { + /* OK - No-op to avoid changing the logic around it */ + result = max_state_alt(STATE_OK, result); + } + else if ((errcode == REG_NOMATCH && invert_regex == 0) || (errcode == 0 && invert_regex == 1)) { + if (invert_regex == 0) + snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spattern not found, "), msg); + else + snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spattern found, "), msg); + result = STATE_CRITICAL; + } + else { + regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); + snprintf (msg, DEFAULT_BUFFER_SIZE, _("%sExecute Error: %s, "), msg, errbuf); + result = STATE_UNKNOWN; + } + } + + /* make sure the page is of an appropriate size */ + if ((max_page_len > 0) && (page_len > max_page_len)) { + snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spage size %d too large, "), msg, page_len); + result = max_state_alt(STATE_WARNING, result); + } else if ((min_page_len > 0) && (page_len < min_page_len)) { + snprintf (msg, DEFAULT_BUFFER_SIZE, _("%spage size %d too small, "), msg, page_len); + result = max_state_alt(STATE_WARNING, result); + } + + /* -w, -c: check warning and critical level */ + result = max_state_alt(get_status(total_time, thlds), result); + + /* Cut-off trailing characters */ + if(msg[strlen(msg)-2] == ',') + msg[strlen(msg)-2] = '\0'; + else + msg[strlen(msg)-3] = '\0'; + + /* TODO: separate _() msg and status code: die (result, "HTTP %s: %s\n", state_text(result), msg); */ + die (result, "HTTP %s: HTTP/%d.%d %d %s%s%s - %d bytes in %.3f second response time %s|%s\n", + state_text(result), status_line.http_major, status_line.http_minor, + status_line.http_code, status_line.msg, + strlen(msg) > 0 ? " - " : "", + msg, page_len, total_time, + (display_html ? "</A>" : ""), + perfstring); + + /* proper cleanup after die? */ + curlhelp_free_statusline(&status_line); + curl_easy_cleanup (curl); + curl_global_cleanup (); + curlhelp_freewritebuffer (&body_buf); + curlhelp_freewritebuffer (&header_buf); + if (!strcmp (http_method, "PUT")) { + curlhelp_freereadbuffer (&put_buf); + } + + return result; +} + +int +uri_strcmp (const UriTextRangeA range, const char* s) +{ + if (!range.first) return -1; + if (range.afterLast - range.first < strlen (s)) return -1; + return strncmp (s, range.first, min( range.afterLast - range.first, strlen (s))); +} + +char* +uri_string (const UriTextRangeA range, char* buf, size_t buflen) +{ + if (!range.first) return "(null)"; + strncpy (buf, range.first, max (buflen, range.afterLast - range.first)); + buf[max (buflen, range.afterLast - range.first)] = '\0'; + buf[range.afterLast - range.first] = '\0'; + return buf; +} + +void +redir (curlhelp_write_curlbuf* header_buf) +{ + char *location = NULL; + curlhelp_statusline status_line; + struct phr_header headers[255]; + size_t nof_headers = 255; + size_t msglen; + char buf[DEFAULT_BUFFER_SIZE]; + char ipstr[INET_ADDR_MAX_SIZE]; + int new_port; + char *new_host; + char *new_url; + + int res = phr_parse_response (header_buf->buf, header_buf->buflen, + &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, + headers, &nof_headers, 0); + + location = get_header_value (headers, nof_headers, "location"); + + if (verbose >= 2) + printf(_("* Seen redirect location %s\n"), location); + + if (++redir_depth > max_depth) + die (STATE_WARNING, + _("HTTP WARNING - maximum redirection depth %d exceeded - %s%s\n"), + max_depth, location, (display_html ? "</A>" : "")); + + UriParserStateA state; + UriUriA uri; + state.uri = &uri; + if (uriParseUriA (&state, location) != URI_SUCCESS) { + if (state.errorCode == URI_ERROR_SYNTAX) { + die (STATE_UNKNOWN, + _("HTTP UNKNOWN - Could not parse redirect location '%s'%s\n"), + location, (display_html ? "</A>" : "")); + } else if (state.errorCode == URI_ERROR_MALLOC) { + die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n")); + } + } + + if (verbose >= 2) { + printf (_("** scheme: %s\n"), + uri_string (uri.scheme, buf, DEFAULT_BUFFER_SIZE)); + printf (_("** host: %s\n"), + uri_string (uri.hostText, buf, DEFAULT_BUFFER_SIZE)); + printf (_("** port: %s\n"), + uri_string (uri.portText, buf, DEFAULT_BUFFER_SIZE)); + if (uri.hostData.ip4) { + inet_ntop (AF_INET, uri.hostData.ip4->data, ipstr, sizeof (ipstr)); + printf (_("** IPv4: %s\n"), ipstr); + } + if (uri.hostData.ip6) { + inet_ntop (AF_INET, uri.hostData.ip6->data, ipstr, sizeof (ipstr)); + printf (_("** IPv6: %s\n"), ipstr); + } + if (uri.pathHead) { + printf (_("** path: ")); + const UriPathSegmentA* p = uri.pathHead; + for (; p; p = p->next) { + printf ("/%s", uri_string (p->text, buf, DEFAULT_BUFFER_SIZE)); + } + puts (""); + } + if (uri.query.first) { + printf (_("** query: %s\n"), + uri_string (uri.query, buf, DEFAULT_BUFFER_SIZE)); + } + if (uri.fragment.first) { + printf (_("** fragment: %s\n"), + uri_string (uri.fragment, buf, DEFAULT_BUFFER_SIZE)); + } + } + + use_ssl = !uri_strcmp (uri.scheme, "https"); + + /* we do a sloppy test here only, because uriparser would have failed + * above, if the port would be invalid, we just check for MAX_PORT + */ + if (uri.portText.first) { + new_port = atoi (uri_string (uri.portText, buf, DEFAULT_BUFFER_SIZE)); + } else { + new_port = HTTP_PORT; + if (use_ssl) + new_port = HTTPS_PORT; + } + if (new_port > MAX_PORT) + die (STATE_UNKNOWN, + _("HTTP UNKNOWN - Redirection to port above %d - %s%s\n"), + MAX_PORT, location, display_html ? "</A>" : ""); + + /* by RFC 7231 relative URLs in Location should be taken relative to + * the original URL, so wy try to form a new absolute URL here + */ + if (!uri.scheme.first && !uri.hostText.first) { + new_host = strdup (host_name ? host_name : server_address); + } else { + new_host = strdup (uri_string (uri.hostText, buf, DEFAULT_BUFFER_SIZE)); + } + + /* compose new path */ + /* TODO: handle fragments and query part of URL */ + new_url = (char *)calloc( 1, DEFAULT_BUFFER_SIZE); + if (uri.pathHead) { + const UriPathSegmentA* p = uri.pathHead; + for (; p; p = p->next) { + strncat (new_url, "/", DEFAULT_BUFFER_SIZE); + strncat (new_url, uri_string (p->text, buf, DEFAULT_BUFFER_SIZE), DEFAULT_BUFFER_SIZE); + } + } + + if (server_port==new_port && + !strncmp(server_address, new_host, MAX_IPV4_HOSTLENGTH) && + (host_name && !strncmp(host_name, new_host, MAX_IPV4_HOSTLENGTH)) && + !strcmp(server_url, new_url)) + die (STATE_WARNING, + _("HTTP WARNING - redirection creates an infinite loop - %s://%s:%d%s%s\n"), + use_ssl ? "https" : "http", new_host, new_port, new_url, (display_html ? "</A>" : "")); + + /* set new values for redirected request */ + + if (!(followsticky & STICKY_HOST)) { + free (server_address); + server_address = strndup (new_host, MAX_IPV4_HOSTLENGTH); + } + if (!(followsticky & STICKY_PORT)) { + server_port = (unsigned short)new_port; + } + + free (host_name); + host_name = strndup (new_host, MAX_IPV4_HOSTLENGTH); + + /* reset virtual port */ + virtual_port = server_port; + + free(new_host); + free (server_url); + server_url = new_url; + + uriFreeUriMembersA (&uri); + + if (verbose) + printf (_("Redirection to %s://%s:%d%s\n"), use_ssl ? "https" : "http", + host_name ? host_name : server_address, server_port, server_url); + + /* TODO: the hash component MUST be taken from the original URL and + * attached to the URL in Location + */ + + check_http (); +} + +/* check whether a file exists */ +void +test_file (char *path) +{ + if (access(path, R_OK) == 0) + return; + usage2 (_("file does not exist or is not readable"), path); +} + +int +process_arguments (int argc, char **argv) +{ + char *p; + int c = 1; + char *temp; + + enum { + INVERT_REGEX = CHAR_MAX + 1, + SNI_OPTION, + CA_CERT_OPTION + }; + + int option = 0; + int got_plus = 0; + static struct option longopts[] = { + STD_LONG_OPTS, + {"link", no_argument, 0, 'L'}, + {"nohtml", no_argument, 0, 'n'}, + {"ssl", optional_argument, 0, 'S'}, + {"sni", no_argument, 0, SNI_OPTION}, + {"post", required_argument, 0, 'P'}, + {"method", required_argument, 0, 'j'}, + {"IP-address", required_argument, 0, 'I'}, + {"url", required_argument, 0, 'u'}, + {"port", required_argument, 0, 'p'}, + {"authorization", required_argument, 0, 'a'}, + {"proxy-authorization", required_argument, 0, 'b'}, + {"header-string", required_argument, 0, 'd'}, + {"string", required_argument, 0, 's'}, + {"expect", required_argument, 0, 'e'}, + {"regex", required_argument, 0, 'r'}, + {"ereg", required_argument, 0, 'r'}, + {"eregi", required_argument, 0, 'R'}, + {"linespan", no_argument, 0, 'l'}, + {"onredirect", required_argument, 0, 'f'}, + {"certificate", required_argument, 0, 'C'}, + {"client-cert", required_argument, 0, 'J'}, + {"private-key", required_argument, 0, 'K'}, + {"ca-cert", required_argument, 0, CA_CERT_OPTION}, + {"useragent", required_argument, 0, 'A'}, + {"header", required_argument, 0, 'k'}, + {"no-body", no_argument, 0, 'N'}, + {"max-age", required_argument, 0, 'M'}, + {"content-type", required_argument, 0, 'T'}, + {"pagesize", required_argument, 0, 'm'}, + {"invert-regex", no_argument, NULL, INVERT_REGEX}, + {"use-ipv4", no_argument, 0, '4'}, + {"use-ipv6", no_argument, 0, '6'}, + {"extended-perfdata", no_argument, 0, 'E'}, + {0, 0, 0, 0} + }; + + if (argc < 2) + return ERROR; + + /* support check_http compatible arguments */ + for (c = 1; c < argc; c++) { + if (strcmp ("-to", argv[c]) == 0) + strcpy (argv[c], "-t"); + if (strcmp ("-hn", argv[c]) == 0) + strcpy (argv[c], "-H"); + if (strcmp ("-wt", argv[c]) == 0) + strcpy (argv[c], "-w"); + if (strcmp ("-ct", argv[c]) == 0) + strcpy (argv[c], "-c"); + if (strcmp ("-nohtml", argv[c]) == 0) + strcpy (argv[c], "-n"); + } + + server_url = strdup(DEFAULT_SERVER_URL); + + while (1) { + c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:d:e:p:s:R:r:u:f:C:J:K:nlLS::m:M:NE", longopts, &option); + if (c == -1 || c == EOF || c == 1) + break; + + switch (c) { + case 'h': + print_help(); + exit(STATE_UNKNOWN); + break; + case 'V': + print_revision(progname, NP_VERSION); + print_curl_version(); + exit(STATE_UNKNOWN); + break; + case 'v': + verbose++; + break; + case 't': /* timeout period */ + if (!is_intnonneg (optarg)) + usage2 (_("Timeout interval must be a positive integer"), optarg); + else + socket_timeout = (int)strtol (optarg, NULL, 10); + break; + case 'c': /* critical time threshold */ + critical_thresholds = optarg; + break; + case 'w': /* warning time threshold */ + warning_thresholds = optarg; + break; + case 'H': /* virtual host */ + host_name = strdup (optarg); + if (host_name[0] == '[') { + if ((p = strstr (host_name, "]:")) != NULL) { /* [IPv6]:port */ + virtual_port = atoi (p + 2); + /* cut off the port */ + host_name_length = strlen (host_name) - strlen (p) - 1; + free (host_name); + host_name = strndup (optarg, host_name_length); + } + } else if ((p = strchr (host_name, ':')) != NULL + && strchr (++p, ':') == NULL) { /* IPv4:port or host:port */ + virtual_port = atoi (p); + /* cut off the port */ + host_name_length = strlen (host_name) - strlen (p) - 1; + free (host_name); + host_name = strndup (optarg, host_name_length); + } + break; + case 'I': /* internet address */ + server_address = strdup (optarg); + break; + case 'u': /* URL path */ + server_url = strdup (optarg); + break; + case 'p': /* Server port */ + if (!is_intnonneg (optarg)) + usage2 (_("Invalid port number, expecting a non-negative number"), optarg); + else { + if( strtol(optarg, NULL, 10) > MAX_PORT) + usage2 (_("Invalid port number, supplied port number is too big"), optarg); + server_port = (unsigned short)strtol(optarg, NULL, 10); + specify_port = TRUE; + } + break; + case 'a': /* authorization info */ + strncpy (user_auth, optarg, MAX_INPUT_BUFFER - 1); + user_auth[MAX_INPUT_BUFFER - 1] = 0; + break; + case 'b': /* proxy-authorization info */ + strncpy (proxy_auth, optarg, MAX_INPUT_BUFFER - 1); + proxy_auth[MAX_INPUT_BUFFER - 1] = 0; + break; + case 'P': /* HTTP POST data in URL encoded format; ignored if settings already */ + if (! http_post_data) + http_post_data = strdup (optarg); + if (! http_method) + http_method = strdup("POST"); + break; + case 'j': /* Set HTTP method */ + if (http_method) + free(http_method); + http_method = strdup (optarg); + break; + case 'A': /* useragent */ + strncpy (user_agent, optarg, DEFAULT_BUFFER_SIZE); + user_agent[DEFAULT_BUFFER_SIZE-1] = '\0'; + break; + case 'k': /* Additional headers */ + if (http_opt_headers_count == 0) + http_opt_headers = malloc (sizeof (char *) * (++http_opt_headers_count)); + else + http_opt_headers = realloc (http_opt_headers, sizeof (char *) * (++http_opt_headers_count)); + http_opt_headers[http_opt_headers_count - 1] = optarg; + break; + case 'L': /* show html link */ + display_html = TRUE; + break; + case 'n': /* do not show html link */ + display_html = FALSE; + break; + case 'C': /* Check SSL cert validity */ +#ifdef LIBCURL_FEATURE_SSL + if ((temp=strchr(optarg,','))!=NULL) { + *temp='\0'; + if (!is_intnonneg (optarg)) + usage2 (_("Invalid certificate expiration period"), optarg); + days_till_exp_warn = atoi(optarg); + *temp=','; + temp++; + if (!is_intnonneg (temp)) + usage2 (_("Invalid certificate expiration period"), temp); + days_till_exp_crit = atoi (temp); + } + else { + days_till_exp_crit=0; + if (!is_intnonneg (optarg)) + usage2 (_("Invalid certificate expiration period"), optarg); + days_till_exp_warn = atoi (optarg); + } + check_cert = TRUE; + goto enable_ssl; +#endif + case 'J': /* use client certificate */ +#ifdef LIBCURL_FEATURE_SSL + test_file(optarg); + client_cert = optarg; + goto enable_ssl; +#endif + case 'K': /* use client private key */ +#ifdef LIBCURL_FEATURE_SSL + test_file(optarg); + client_privkey = optarg; + goto enable_ssl; +#endif +#ifdef LIBCURL_FEATURE_SSL + case CA_CERT_OPTION: /* use CA chain file */ + test_file(optarg); + ca_cert = optarg; + goto enable_ssl; +#endif + case 'S': /* use SSL */ +#ifdef LIBCURL_FEATURE_SSL + enable_ssl: + use_ssl = TRUE; + /* ssl_version initialized to CURL_SSLVERSION_DEFAULT as a default. + * Only set if it's non-zero. This helps when we include multiple + * parameters, like -S and -C combinations */ + ssl_version = CURL_SSLVERSION_DEFAULT; + if (c=='S' && optarg != NULL) { + char *plus_ptr = strchr(optarg, '+'); + if (plus_ptr) { + got_plus = 1; + *plus_ptr = '\0'; + } + + if (optarg[0] == '2') + ssl_version = CURL_SSLVERSION_SSLv2; + else if (optarg[0] == '3') + ssl_version = CURL_SSLVERSION_SSLv3; + else if (!strcmp (optarg, "1") || !strcmp (optarg, "1.0")) +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + ssl_version = CURL_SSLVERSION_TLSv1_0; +#else + ssl_version = CURL_SSLVERSION_DEFAULT; +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + else if (!strcmp (optarg, "1.1")) +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + ssl_version = CURL_SSLVERSION_TLSv1_1; +#else + ssl_version = CURL_SSLVERSION_DEFAULT; +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + else if (!strcmp (optarg, "1.2")) +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) + ssl_version = CURL_SSLVERSION_TLSv1_2; +#else + ssl_version = CURL_SSLVERSION_DEFAULT; +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 34, 0) */ + else if (!strcmp (optarg, "1.3")) +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) + ssl_version = CURL_SSLVERSION_TLSv1_3; +#else + ssl_version = CURL_SSLVERSION_DEFAULT; +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 52, 0) */ + else + usage4 (_("Invalid option - Valid SSL/TLS versions: 2, 3, 1, 1.1, 1.2 (with optional '+' suffix)")); + } +#if LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) + if (got_plus) { + switch (ssl_version) { + case CURL_SSLVERSION_TLSv1_3: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3; + break; + case CURL_SSLVERSION_TLSv1_2: + case CURL_SSLVERSION_TLSv1_1: + case CURL_SSLVERSION_TLSv1_0: + ssl_version |= CURL_SSLVERSION_MAX_DEFAULT; + break; + } + } else { + switch (ssl_version) { + case CURL_SSLVERSION_TLSv1_3: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_3; + break; + case CURL_SSLVERSION_TLSv1_2: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_2; + break; + case CURL_SSLVERSION_TLSv1_1: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_1; + break; + case CURL_SSLVERSION_TLSv1_0: + ssl_version |= CURL_SSLVERSION_MAX_TLSv1_0; + break; + } + } +#endif /* LIBCURL_VERSION_NUM >= MAKE_LIBCURL_VERSION(7, 54, 0) */ + if (verbose >= 2) + printf(_("* Set SSL/TLS version to %d\n"), ssl_version); + if (specify_port == FALSE) + server_port = HTTPS_PORT; + break; +#else /* LIBCURL_FEATURE_SSL */ + /* -C -J and -K fall through to here without SSL */ + usage4 (_("Invalid option - SSL is not available")); + break; + case SNI_OPTION: /* --sni is parsed, but ignored, the default is TRUE with libcurl */ + use_sni = TRUE; + break; +#endif /* LIBCURL_FEATURE_SSL */ + case 'f': /* onredirect */ + if (!strcmp (optarg, "ok")) + onredirect = STATE_OK; + else if (!strcmp (optarg, "warning")) + onredirect = STATE_WARNING; + else if (!strcmp (optarg, "critical")) + onredirect = STATE_CRITICAL; + else if (!strcmp (optarg, "unknown")) + onredirect = STATE_UNKNOWN; + else if (!strcmp (optarg, "follow")) + onredirect = STATE_DEPENDENT; + else if (!strcmp (optarg, "stickyport")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST|STICKY_PORT; + else if (!strcmp (optarg, "sticky")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_HOST; + else if (!strcmp (optarg, "follow")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_HTTP_CURL, followsticky = STICKY_NONE; + else if (!strcmp (optarg, "curl")) + onredirect = STATE_DEPENDENT, followmethod = FOLLOW_LIBCURL; + else usage2 (_("Invalid onredirect option"), optarg); + if (verbose >= 2) + printf(_("* Following redirects set to %s\n"), state_text(onredirect)); + break; + case 'd': /* string or substring */ + strncpy (header_expect, optarg, MAX_INPUT_BUFFER - 1); + header_expect[MAX_INPUT_BUFFER - 1] = 0; + break; + case 's': /* string or substring */ + strncpy (string_expect, optarg, MAX_INPUT_BUFFER - 1); + string_expect[MAX_INPUT_BUFFER - 1] = 0; + break; + case 'e': /* string or substring */ + strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1); + server_expect[MAX_INPUT_BUFFER - 1] = 0; + server_expect_yn = 1; + break; + case 'T': /* Content-type */ + http_content_type = strdup (optarg); + break; + case 'l': /* linespan */ + cflags &= ~REG_NEWLINE; + break; + case 'R': /* regex */ + cflags |= REG_ICASE; + case 'r': /* regex */ + strncpy (regexp, optarg, MAX_RE_SIZE - 1); + regexp[MAX_RE_SIZE - 1] = 0; + errcode = regcomp (&preg, regexp, cflags); + if (errcode != 0) { + (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); + printf (_("Could Not Compile Regular Expression: %s"), errbuf); + return ERROR; + } + break; + case INVERT_REGEX: + invert_regex = 1; + break; + case '4': + address_family = AF_INET; + break; + case '6': +#if defined (USE_IPV6) && defined (LIBCURL_FEATURE_IPV6) + address_family = AF_INET6; +#else + usage4 (_("IPv6 support not available")); +#endif + break; + case 'm': /* min_page_length */ + { + char *tmp; + if (strchr(optarg, ':') != (char *)NULL) { + /* range, so get two values, min:max */ + tmp = strtok(optarg, ":"); + if (tmp == NULL) { + printf("Bad format: try \"-m min:max\"\n"); + exit (STATE_WARNING); + } else + min_page_len = atoi(tmp); + + tmp = strtok(NULL, ":"); + if (tmp == NULL) { + printf("Bad format: try \"-m min:max\"\n"); + exit (STATE_WARNING); + } else + max_page_len = atoi(tmp); + } else + min_page_len = atoi (optarg); + break; + } + case 'N': /* no-body */ + no_body = TRUE; + break; + case 'M': /* max-age */ + { + int L = strlen(optarg); + if (L && optarg[L-1] == 'm') + maximum_age = atoi (optarg) * 60; + else if (L && optarg[L-1] == 'h') + maximum_age = atoi (optarg) * 60 * 60; + else if (L && optarg[L-1] == 'd') + maximum_age = atoi (optarg) * 60 * 60 * 24; + else if (L && (optarg[L-1] == 's' || + isdigit (optarg[L-1]))) + maximum_age = atoi (optarg); + else { + fprintf (stderr, "unparsable max-age: %s\n", optarg); + exit (STATE_WARNING); + } + if (verbose >= 2) + printf ("* Maximal age of document set to %d seconds\n", maximum_age); + } + break; + case 'E': /* show extended perfdata */ + show_extended_perfdata = TRUE; + break; + case '?': + /* print short usage statement if args not parsable */ + usage5 (); + break; + } + } + + c = optind; + + if (server_address == NULL && c < argc) + server_address = strdup (argv[c++]); + + if (host_name == NULL && c < argc) + host_name = strdup (argv[c++]); + + if (server_address == NULL) { + if (host_name == NULL) + usage4 (_("You must specify a server address or host name")); + else + server_address = strdup (host_name); + } + + set_thresholds(&thlds, warning_thresholds, critical_thresholds); + + if (critical_thresholds && thlds->critical->end>(double)socket_timeout) + socket_timeout = (int)thlds->critical->end + 1; + if (verbose >= 2) + printf ("* Socket timeout set to %ld seconds\n", socket_timeout); + + if (http_method == NULL) + http_method = strdup ("GET"); + + if (client_cert && !client_privkey) + usage4 (_("If you use a client certificate you must also specify a private key file")); + + if (virtual_port == 0) + virtual_port = server_port; + else { + if ((use_ssl && server_port == HTTPS_PORT) || (!use_ssl && server_port == HTTP_PORT)) + if(specify_port == FALSE) + server_port = virtual_port; + } + + return TRUE; +} + +char *perfd_time (double elapsed_time) +{ + return fperfdata ("time", elapsed_time, "s", + thlds->warning?TRUE:FALSE, thlds->warning?thlds->warning->end:0, + thlds->critical?TRUE:FALSE, thlds->critical?thlds->critical->end:0, + TRUE, 0, TRUE, socket_timeout); +} + +char *perfd_time_connect (double elapsed_time_connect) +{ + return fperfdata ("time_connect", elapsed_time_connect, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); +} + +char *perfd_time_ssl (double elapsed_time_ssl) +{ + return fperfdata ("time_ssl", elapsed_time_ssl, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); +} + +char *perfd_time_headers (double elapsed_time_headers) +{ + return fperfdata ("time_headers", elapsed_time_headers, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); +} + +char *perfd_time_firstbyte (double elapsed_time_firstbyte) +{ + return fperfdata ("time_firstbyte", elapsed_time_firstbyte, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); +} + +char *perfd_time_transfer (double elapsed_time_transfer) +{ + return fperfdata ("time_transfer", elapsed_time_transfer, "s", FALSE, 0, FALSE, 0, FALSE, 0, TRUE, socket_timeout); +} + +char *perfd_size (int page_len) +{ + return perfdata ("size", page_len, "B", + (min_page_len>0?TRUE:FALSE), min_page_len, + (min_page_len>0?TRUE:FALSE), 0, + TRUE, 0, FALSE, 0); +} + +void +print_help (void) +{ + print_revision (progname, NP_VERSION); + + printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"); + printf (COPYRIGHT, copyright, email); + + printf ("%s\n", _("This plugin tests the HTTP service on the specified host. It can test")); + printf ("%s\n", _("normal (http) and secure (https) servers, follow redirects, search for")); + printf ("%s\n", _("strings and regular expressions, check connection times, and report on")); + printf ("%s\n", _("certificate expiration times.")); + printf ("\n"); + printf ("%s\n", _("It makes use of libcurl to do so. It tries to be as compatible to check_http")); + printf ("%s\n", _("as possible.")); + + printf ("\n\n"); + + print_usage (); + + printf (_("NOTE: One or both of -H and -I must be specified")); + + printf ("\n"); + + printf (UT_HELP_VRSN); + printf (UT_EXTRA_OPTS); + + printf (" %s\n", "-H, --hostname=ADDRESS"); + printf (" %s\n", _("Host name argument for servers using host headers (virtual host)")); + printf (" %s\n", _("Append a port to include it in the header (eg: example.com:5000)")); + printf (" %s\n", "-I, --IP-address=ADDRESS"); + printf (" %s\n", _("IP address or name (use numeric address if possible to bypass DNS lookup).")); + printf (" %s\n", "-p, --port=INTEGER"); + printf (" %s", _("Port number (default: ")); + printf ("%d)\n", HTTP_PORT); + + printf (UT_IPv46); + +#ifdef LIBCURL_FEATURE_SSL + printf (" %s\n", "-S, --ssl=VERSION[+]"); + printf (" %s\n", _("Connect via SSL. Port defaults to 443. VERSION is optional, and prevents")); + printf (" %s\n", _("auto-negotiation (2 = SSLv2, 3 = SSLv3, 1 = TLSv1, 1.1 = TLSv1.1,")); + printf (" %s\n", _("1.2 = TLSv1.2). With a '+' suffix, newer versions are also accepted.")); + printf (" %s\n", _("Note: SSLv2 and SSLv3 are deprecated and are usually disabled in libcurl")); + printf (" %s\n", "--sni"); + printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); +#if LIBCURL_VERSION_NUM >= 0x071801 + printf (" %s\n", _("Note: --sni is the default in libcurl as SSLv2 and SSLV3 are deprecated and")); + printf (" %s\n", _(" SNI only really works since TLSv1.0")); +#else + printf (" %s\n", _("Note: SNI is not supported in libcurl before 7.18.1")); +#endif + printf (" %s\n", "-C, --certificate=INTEGER[,INTEGER]"); + printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443")); + printf (" %s\n", _("(when this option is used the URL is not checked.)")); + printf (" %s\n", "-J, --client-cert=FILE"); + printf (" %s\n", _("Name of file that contains the client certificate (PEM format)")); + printf (" %s\n", _("to be used in establishing the SSL session")); + printf (" %s\n", "-K, --private-key=FILE"); + printf (" %s\n", _("Name of file containing the private key (PEM format)")); + printf (" %s\n", _("matching the client certificate")); + printf (" %s\n", "--ca-cert=FILE"); + printf (" %s\n", _("CA certificate file to verify peer against")); +#endif + + printf (" %s\n", "-e, --expect=STRING"); + printf (" %s\n", _("Comma-delimited list of strings, at least one of them is expected in")); + printf (" %s", _("the first (status) line of the server response (default: ")); + printf ("%s)\n", HTTP_EXPECT); + printf (" %s\n", _("If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)")); + printf (" %s\n", "-d, --header-string=STRING"); + printf (" %s\n", _("String to expect in the response headers")); + printf (" %s\n", "-s, --string=STRING"); + printf (" %s\n", _("String to expect in the content")); + printf (" %s\n", "-u, --url=PATH"); + printf (" %s\n", _("URL to GET or POST (default: /)")); + printf (" %s\n", "-P, --post=STRING"); + printf (" %s\n", _("URL encoded http POST data")); + printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE, CONNECT)"); + printf (" %s\n", _("Set HTTP method.")); + printf (" %s\n", "-N, --no-body"); + printf (" %s\n", _("Don't wait for document body: stop reading after headers.")); + printf (" %s\n", _("(Note that this still does an HTTP GET or POST, not a HEAD.)")); + printf (" %s\n", "-M, --max-age=SECONDS"); + printf (" %s\n", _("Warn if document is more than SECONDS old. the number can also be of")); + printf (" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or \"10d\" for days.")); + printf (" %s\n", "-T, --content-type=STRING"); + printf (" %s\n", _("specify Content-Type header media type when POSTing\n")); + printf (" %s\n", "-l, --linespan"); + printf (" %s\n", _("Allow regex to span newlines (must precede -r or -R)")); + printf (" %s\n", "-r, --regex, --ereg=STRING"); + printf (" %s\n", _("Search page for regex STRING")); + printf (" %s\n", "-R, --eregi=STRING"); + printf (" %s\n", _("Search page for case-insensitive regex STRING")); + printf (" %s\n", "--invert-regex"); + printf (" %s\n", _("Return CRITICAL if found, OK if not\n")); + printf (" %s\n", "-a, --authorization=AUTH_PAIR"); + printf (" %s\n", _("Username:password on sites with basic authentication")); + printf (" %s\n", "-b, --proxy-authorization=AUTH_PAIR"); + printf (" %s\n", _("Username:password on proxy-servers with basic authentication")); + printf (" %s\n", "-A, --useragent=STRING"); + printf (" %s\n", _("String to be sent in http header as \"User Agent\"")); + printf (" %s\n", "-k, --header=STRING"); + printf (" %s\n", _("Any other tags to be sent in http header. Use multiple times for additional headers")); + printf (" %s\n", "-E, --extended-perfdata"); + printf (" %s\n", _("Print additional performance data")); + printf (" %s\n", "-L, --link"); + printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)")); + printf (" %s\n", "-f, --onredirect=<ok|warning|critical|follow|sticky|stickyport|curl>"); + printf (" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the")); + printf (" %s\n", _("specified IP address. stickyport also ensures port stays the same.")); + printf (" %s\n", _("follow uses the old redirection algorithm of check_http.")); + printf (" %s\n", _("curl uses CURL_FOLLOWLOCATION built into libcurl.")); + printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>"); + printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)")); + + printf (UT_WARN_CRIT); + + printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); + + printf (UT_VERBOSE); + + printf ("\n"); + printf ("%s\n", _("Notes:")); + printf (" %s\n", _("This plugin will attempt to open an HTTP connection with the host.")); + printf (" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL")); + printf (" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect response")); + printf (" %s\n", _("messages from the host result in STATE_WARNING return values. If you are")); + printf (" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN")); + printf (" %s\n", _("(fully qualified domain name) as the [host_name] argument.")); + +#ifdef LIBCURL_FEATURE_SSL + printf ("\n"); + printf (" %s\n", _("This plugin can also check whether an SSL enabled web server is able to")); + printf (" %s\n", _("serve content (optionally within a specified time) or whether the X509 ")); + printf (" %s\n", _("certificate is still valid for the specified number of days.")); + printf ("\n"); + printf (" %s\n", _("Please note that this plugin does not check if the presented server")); + printf (" %s\n", _("certificate matches the hostname of the server, or if the certificate")); + printf (" %s\n", _("has a valid chain of trust to one of the locally installed CAs.")); + printf ("\n"); + printf ("%s\n", _("Examples:")); + printf (" %s\n\n", "CHECK CONTENT: check_curl -w 5 -c 10 --ssl -H www.verisign.com"); + printf (" %s\n", _("When the 'www.verisign.com' server returns its content within 5 seconds,")); + printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); + printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); + printf (" %s\n", _("a STATE_CRITICAL will be returned.")); + printf ("\n"); + printf (" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 14"); + printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,")); + printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than")); + printf (" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when")); + printf (" %s\n\n", _("the certificate is expired.")); + printf ("\n"); + printf (" %s\n\n", "CHECK CERTIFICATE: check_curl -H www.verisign.com -C 30,14"); + printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 30 days,")); + printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than")); + printf (" %s\n", _("30 days, but more than 14 days, a STATE_WARNING is returned.")); + printf (" %s\n", _("A STATE_CRITICAL will be returned when certificate expires in less than 14 days")); +#endif + + printf ("\n %s\n", "CHECK WEBSERVER CONTENT VIA PROXY:"); + printf (" %s\n", _("It is recommended to use an environment proxy like:")); + printf (" %s\n", _("http_proxy=http://192.168.100.35:3128 ./check_curl -H www.monitoring-plugins.org")); + printf (" %s\n", _("legacy proxy requests in check_http style still work:")); + printf (" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u http://www.monitoring-plugins.org/ -H www.monitoring-plugins.org")); + +#ifdef LIBCURL_FEATURE_SSL + printf ("\n %s\n", "CHECK SSL WEBSERVER CONTENT VIA PROXY USING HTTP 1.1 CONNECT: "); + printf (" %s\n", _("It is recommended to use an environment proxy like:")); + printf (" %s\n", _("https_proxy=http://192.168.100.35:3128 ./check_curl -H www.verisign.com -S")); + printf (" %s\n", _("legacy proxy requests in check_http style still work:")); + printf (" %s\n", _("check_curl -I 192.168.100.35 -p 3128 -u https://www.verisign.com/ -S -j CONNECT -H www.verisign.com ")); + printf (" %s\n", _("all these options are needed: -I <proxy> -p <proxy-port> -u <check-url> -S(sl) -j CONNECT -H <webserver>")); + printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds")); + printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,")); + printf (" %s\n", _("a STATE_CRITICAL will be returned.")); + +#endif + + printf (UT_SUPPORT); + +} + + + +void +print_usage (void) +{ + printf ("%s\n", _("Usage:")); + printf (" %s -H <vhost> | -I <IP-address> [-u <uri>] [-p <port>]\n",progname); + printf (" [-J <client certificate file>] [-K <private key>] [--ca-cert <CA certificate file>]\n"); + printf (" [-w <warn time>] [-c <critical time>] [-t <timeout>] [-L] [-E] [-a auth]\n"); + printf (" [-b proxy_auth] [-f <ok|warning|critcal|follow|sticky|stickyport|curl>]\n"); + printf (" [-e <expect>] [-d string] [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n"); + printf (" [-P string] [-m <min_pg_size>:<max_pg_size>] [-4|-6] [-N] [-M <age>]\n"); + printf (" [-A string] [-k string] [-S <version>] [--sni] [-C <warn_age>[,<crit_age>]]\n"); + printf (" [-T <content-type>] [-j method]\n"); + printf ("\n"); + printf ("%s\n", _("WARNING: check_curl is experimental. Please use")); + printf ("%s\n\n", _("check_http if you need a stable version.")); +} + +void +print_curl_version (void) +{ + printf( "%s\n", curl_version()); +} + +int +curlhelp_initwritebuffer (curlhelp_write_curlbuf *buf) +{ + buf->bufsize = DEFAULT_BUFFER_SIZE; + buf->buflen = 0; + buf->buf = (char *)malloc ((size_t)buf->bufsize); + if (buf->buf == NULL) return -1; + return 0; +} + +int +curlhelp_buffer_write_callback (void *buffer, size_t size, size_t nmemb, void *stream) +{ + curlhelp_write_curlbuf *buf = (curlhelp_write_curlbuf *)stream; + + while (buf->bufsize < buf->buflen + size * nmemb + 1) { + buf->bufsize *= buf->bufsize * 2; + buf->buf = (char *)realloc (buf->buf, buf->bufsize); + if (buf->buf == NULL) return -1; + } + + memcpy (buf->buf + buf->buflen, buffer, size * nmemb); + buf->buflen += size * nmemb; + buf->buf[buf->buflen] = '\0'; + + return (int)(size * nmemb); +} + +int +curlhelp_buffer_read_callback (void *buffer, size_t size, size_t nmemb, void *stream) +{ + curlhelp_read_curlbuf *buf = (curlhelp_read_curlbuf *)stream; + + size_t n = min (nmemb * size, buf->buflen - buf->pos); + + memcpy (buffer, buf->buf + buf->pos, n); + buf->pos += n; + + return (int)n; +} + +void +curlhelp_freewritebuffer (curlhelp_write_curlbuf *buf) +{ + free (buf->buf); + buf->buf = NULL; +} + +int +curlhelp_initreadbuffer (curlhelp_read_curlbuf *buf, const char *data, size_t datalen) +{ + buf->buflen = datalen; + buf->buf = (char *)malloc ((size_t)buf->buflen); + if (buf->buf == NULL) return -1; + memcpy (buf->buf, data, datalen); + buf->pos = 0; + return 0; +} + +void +curlhelp_freereadbuffer (curlhelp_read_curlbuf *buf) +{ + free (buf->buf); + buf->buf = NULL; +} + +/* TODO: where to put this, it's actually part of sstrings2 (logically)? + */ +const char* +strrstr2(const char *haystack, const char *needle) +{ + int counter; + size_t len; + const char *prev_pos; + const char *pos; + + if (haystack == NULL || needle == NULL) + return NULL; + + if (haystack[0] == '\0' || needle[0] == '\0') + return NULL; + + counter = 0; + prev_pos = NULL; + pos = haystack; + len = strlen (needle); + for (;;) { + pos = strstr (pos, needle); + if (pos == NULL) { + if (counter == 0) + return NULL; + else + return prev_pos; + } + counter++; + prev_pos = pos; + pos += len; + if (*pos == '\0') return prev_pos; + } +} + +int +curlhelp_parse_statusline (const char *buf, curlhelp_statusline *status_line) +{ + char *first_line_end; + char *p; + size_t first_line_len; + char *pp; + const char *start; + char *first_line_buf; + + /* find last start of a new header */ + start = strrstr2 (buf, "\r\nHTTP"); + if (start != NULL) { + start += 2; + buf = start; + } + + first_line_end = strstr(buf, "\r\n"); + if (first_line_end == NULL) return -1; + + first_line_len = (size_t)(first_line_end - buf); + status_line->first_line = (char *)malloc (first_line_len + 1); + if (status_line->first_line == NULL) return -1; + memcpy (status_line->first_line, buf, first_line_len); + status_line->first_line[first_line_len] = '\0'; + first_line_buf = strdup( status_line->first_line ); + + /* protocol and version: "HTTP/x.x" SP */ + + p = strtok(first_line_buf, "/"); + if( p == NULL ) { free( first_line_buf ); return -1; } + if( strcmp( p, "HTTP" ) != 0 ) { free( first_line_buf ); return -1; } + + p = strtok( NULL, "." ); + if( p == NULL ) { free( first_line_buf ); return -1; } + status_line->http_major = (int)strtol( p, &pp, 10 ); + if( *pp != '\0' ) { free( first_line_buf ); return -1; } + + p = strtok( NULL, " " ); + if( p == NULL ) { free( first_line_buf ); return -1; } + status_line->http_minor = (int)strtol( p, &pp, 10 ); + if( *pp != '\0' ) { free( first_line_buf ); return -1; } + + /* status code: "404" or "404.1", then SP */ + + p = strtok( NULL, " ." ); + if( p == NULL ) { free( first_line_buf ); return -1; } + if( strchr( p, '.' ) != NULL ) { + char *ppp; + ppp = strtok( p, "." ); + status_line->http_code = (int)strtol( ppp, &pp, 10 ); + if( *pp != '\0' ) { free( first_line_buf ); return -1; } + + ppp = strtok( NULL, "" ); + status_line->http_subcode = (int)strtol( ppp, &pp, 10 ); + if( *pp != '\0' ) { free( first_line_buf ); return -1; } + } else { + status_line->http_code = (int)strtol( p, &pp, 10 ); + status_line->http_subcode = -1; + if( *pp != '\0' ) { free( first_line_buf ); return -1; } + } + + /* Human readable message: "Not Found" CRLF */ + + p = strtok( NULL, "" ); + if( p == NULL ) { status_line->msg = ""; return 0; } + status_line->msg = status_line->first_line + ( p - first_line_buf ); + free( first_line_buf ); + + return 0; +} + +void +curlhelp_free_statusline (curlhelp_statusline *status_line) +{ + free (status_line->first_line); +} + +void +remove_newlines (char *s) +{ + char *p; + + for (p = s; *p != '\0'; p++) + if (*p == '\r' || *p == '\n') + *p = ' '; +} + +char * +get_header_value (const struct phr_header* headers, const size_t nof_headers, const char* header) +{ + int i; + for( i = 0; i < nof_headers; i++ ) { + if( strncasecmp( header, headers[i].name, max( headers[i].name_len, 4 ) ) == 0 ) { + return strndup( headers[i].value, headers[i].value_len ); + } + } + return NULL; +} + +int +check_document_dates (const curlhelp_write_curlbuf *header_buf, char (*msg)[DEFAULT_BUFFER_SIZE]) +{ + char *server_date = NULL; + char *document_date = NULL; + int date_result = STATE_OK; + curlhelp_statusline status_line; + struct phr_header headers[255]; + size_t nof_headers = 255; + size_t msglen; + + int res = phr_parse_response (header_buf->buf, header_buf->buflen, + &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, + headers, &nof_headers, 0); + + server_date = get_header_value (headers, nof_headers, "date"); + document_date = get_header_value (headers, nof_headers, "last-modified"); + + if (!server_date || !*server_date) { + snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sServer date unknown, "), *msg); + date_result = max_state_alt(STATE_UNKNOWN, date_result); + } else if (!document_date || !*document_date) { + snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument modification date unknown, "), *msg); + date_result = max_state_alt(STATE_CRITICAL, date_result); + } else { + time_t srv_data = curl_getdate (server_date, NULL); + time_t doc_data = curl_getdate (document_date, NULL); + if (verbose >= 2) + printf ("* server date: '%s' (%d), doc_date: '%s' (%d)\n", server_date, (int)srv_data, document_date, (int)doc_data); + if (srv_data <= 0) { + snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sServer date \"%100s\" unparsable, "), *msg, server_date); + date_result = max_state_alt(STATE_CRITICAL, date_result); + } else if (doc_data <= 0) { + snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date); + date_result = max_state_alt(STATE_CRITICAL, date_result); + } else if (doc_data > srv_data + 30) { + snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data); + date_result = max_state_alt(STATE_CRITICAL, date_result); + } else if (doc_data < srv_data - maximum_age) { + int n = (srv_data - doc_data); + if (n > (60 * 60 * 24 * 2)) { + snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24)); + date_result = max_state_alt(STATE_CRITICAL, date_result); + } else { + snprintf (*msg, DEFAULT_BUFFER_SIZE, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60); + date_result = max_state_alt(STATE_CRITICAL, date_result); + } + } + } + + if (server_date) free (server_date); + if (document_date) free (document_date); + + return date_result; +} + + +int +get_content_length (const curlhelp_write_curlbuf* header_buf, const curlhelp_write_curlbuf* body_buf) +{ + const char *s; + int content_length = 0; + char *copy; + struct phr_header headers[255]; + size_t nof_headers = 255; + size_t msglen; + char *content_length_s = NULL; + curlhelp_statusline status_line; + + int res = phr_parse_response (header_buf->buf, header_buf->buflen, + &status_line.http_minor, &status_line.http_code, &status_line.msg, &msglen, + headers, &nof_headers, 0); + + content_length_s = get_header_value (headers, nof_headers, "content-length"); + if (!content_length_s) { + return header_buf->buflen + body_buf->buflen; + } + content_length_s += strspn (content_length_s, " \t"); + content_length = atoi (content_length_s); + if (content_length != body_buf->buflen) { + /* TODO: should we warn if the actual and the reported body length don't match? */ + } + + if (content_length_s) free (content_length_s); + + return header_buf->buflen + body_buf->buflen; +} + +/* TODO: is there a better way in libcurl to check for the SSL library? */ +curlhelp_ssl_library +curlhelp_get_ssl_library (CURL* curl) +{ + curl_version_info_data* version_data; + char *ssl_version; + char *library; + curlhelp_ssl_library ssl_library = CURLHELP_SSL_LIBRARY_UNKNOWN; + + version_data = curl_version_info (CURLVERSION_NOW); + if (version_data == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN; + + ssl_version = strdup (version_data->ssl_version); + if (ssl_version == NULL ) return CURLHELP_SSL_LIBRARY_UNKNOWN; + + library = strtok (ssl_version, "/"); + if (library == NULL) return CURLHELP_SSL_LIBRARY_UNKNOWN; + + if (strcmp (library, "OpenSSL") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_OPENSSL; + else if (strcmp (library, "LibreSSL") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_LIBRESSL; + else if (strcmp (library, "GnuTLS") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_GNUTLS; + else if (strcmp (library, "NSS") == 0) + ssl_library = CURLHELP_SSL_LIBRARY_NSS; + + if (verbose >= 2) + printf ("* SSL library string is : %s %s (%d)\n", version_data->ssl_version, library, ssl_library); + + free (ssl_version); + + return ssl_library; +} + +const char* +curlhelp_get_ssl_library_string (curlhelp_ssl_library ssl_library) +{ + switch (ssl_library) { + case CURLHELP_SSL_LIBRARY_OPENSSL: + return "OpenSSL"; + case CURLHELP_SSL_LIBRARY_LIBRESSL: + return "LibreSSL"; + case CURLHELP_SSL_LIBRARY_GNUTLS: + return "GnuTLS"; + case CURLHELP_SSL_LIBRARY_NSS: + return "NSS"; + case CURLHELP_SSL_LIBRARY_UNKNOWN: + default: + return "unknown"; + } +} + +#ifdef LIBCURL_FEATURE_SSL +#ifndef USE_OPENSSL +time_t +parse_cert_date (const char *s) +{ + struct tm tm; + time_t date; + + if (!s) return -1; + + strptime (s, "%Y-%m-%d %H:%M:%S GMT", &tm); + date = mktime (&tm); + + return date; +} + +/* TODO: this needs cleanup in the sslutils.c, maybe we the #else case to + * OpenSSL could be this function + */ +int +net_noopenssl_check_certificate (cert_ptr_union* cert_ptr, int days_till_exp_warn, int days_till_exp_crit) +{ + int i; + struct curl_slist* slist; + int cname_found = 0; + char* start_date_str = NULL; + char* end_date_str = NULL; + time_t start_date; + time_t end_date; + char *tz; + float time_left; + int days_left; + int time_remaining; + char timestamp[50] = ""; + int status = STATE_UNKNOWN; + + if (verbose >= 2) + printf ("**** REQUEST CERTIFICATES ****\n"); + + for (i = 0; i < cert_ptr->to_certinfo->num_of_certs; i++) { + for (slist = cert_ptr->to_certinfo->certinfo[i]; slist; slist = slist->next) { + /* find first common name in subject, TODO: check alternative subjects for + * multi-host certificate, check wildcards + */ + if (strncasecmp (slist->data, "Subject:", 8) == 0) { + char* p = strstr (slist->data, "CN="); + if (p != NULL) { + if (strncmp (host_name, p+3, strlen (host_name)) == 0) { + cname_found = 1; + } + } + } else if (strncasecmp (slist->data, "Start Date:", 11) == 0) { + start_date_str = &slist->data[11]; + } else if (strncasecmp (slist->data, "Expire Date:", 12) == 0) { + end_date_str = &slist->data[12]; + } else if (strncasecmp (slist->data, "Cert:", 5) == 0) { + goto HAVE_FIRST_CERT; + } + if (verbose >= 2) + printf ("%d ** %s\n", i, slist->data); + } + } +HAVE_FIRST_CERT: + + if (verbose >= 2) + printf ("**** REQUEST CERTIFICATES ****\n"); + + if (!cname_found) { + printf("%s\n",_("CRITICAL - Cannot retrieve certificate subject.")); + return STATE_CRITICAL; + } + + start_date = parse_cert_date (start_date_str); + if (start_date <= 0) { + snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Start Date' in certificate: '%s'"), + start_date_str); + puts (msg); + return STATE_WARNING; + } + + end_date = parse_cert_date (end_date_str); + if (end_date <= 0) { + snprintf (msg, DEFAULT_BUFFER_SIZE, _("WARNING - Unparsable 'Expire Date' in certificate: '%s'"), + start_date_str); + puts (msg); + return STATE_WARNING; + } + + time_left = difftime (end_date, time(NULL)); + days_left = time_left / 86400; + tz = getenv("TZ"); + setenv("TZ", "GMT", 1); + tzset(); + strftime(timestamp, 50, "%c %z", localtime(&end_date)); + if (tz) + setenv("TZ", tz, 1); + else + unsetenv("TZ"); + tzset(); + + if (days_left > 0 && days_left <= days_till_exp_warn) { + printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, days_left, timestamp); + if (days_left > days_till_exp_crit) + status = STATE_WARNING; + else + status = STATE_CRITICAL; + } else if (days_left == 0 && time_left > 0) { + if (time_left >= 3600) + time_remaining = (int) time_left / 3600; + else + time_remaining = (int) time_left / 60; + + printf (_("%s - Certificate '%s' expires in %u %s (%s)\n"), + (days_left>days_till_exp_crit) ? "WARNING" : "CRITICAL", host_name, time_remaining, + time_left >= 3600 ? "hours" : "minutes", timestamp); + + if ( days_left > days_till_exp_crit) + status = STATE_WARNING; + else + status = STATE_CRITICAL; + } else if (time_left < 0) { + printf(_("CRITICAL - Certificate '%s' expired on %s.\n"), host_name, timestamp); + status=STATE_CRITICAL; + } else if (days_left == 0) { + printf (_("%s - Certificate '%s' just expired (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", host_name, timestamp); + if (days_left > days_till_exp_crit) + status = STATE_WARNING; + else + status = STATE_CRITICAL; + } else { + printf(_("OK - Certificate '%s' will expire on %s.\n"), host_name, timestamp); + status = STATE_OK; + } + return status; +} +#endif /* USE_OPENSSL */ +#endif /* LIBCURL_FEATURE_SSL */ diff --git a/plugins/picohttpparser/Makefile.am b/plugins/picohttpparser/Makefile.am new file mode 100644 index 00000000..87e05313 --- /dev/null +++ b/plugins/picohttpparser/Makefile.am @@ -0,0 +1,3 @@ +noinst_LIBRARIES = libpicohttpparser.a + +libpicohttpparser_a_SOURCES = picohttpparser.c picohttpparser.h diff --git a/plugins/picohttpparser/picohttpparser.c b/plugins/picohttpparser/picohttpparser.c new file mode 100644 index 00000000..6a2d872d --- /dev/null +++ b/plugins/picohttpparser/picohttpparser.c @@ -0,0 +1,620 @@ +/* + * Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase, + * Shigeo Mitsunari + * + * The software is licensed under either the MIT License (below) or the Perl + * license. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include <assert.h> +#include <stddef.h> +#include <string.h> +#ifdef __SSE4_2__ +#ifdef _MSC_VER +#include <nmmintrin.h> +#else +#include <x86intrin.h> +#endif +#endif +#include "picohttpparser.h" + +/* $Id: a707070d11d499609f99d09f97535642cec910a8 $ */ + +#if __GNUC__ >= 3 +#define likely(x) __builtin_expect(!!(x), 1) +#define unlikely(x) __builtin_expect(!!(x), 0) +#else +#define likely(x) (x) +#define unlikely(x) (x) +#endif + +#ifdef _MSC_VER +#define ALIGNED(n) _declspec(align(n)) +#else +#define ALIGNED(n) __attribute__((aligned(n))) +#endif + +#define IS_PRINTABLE_ASCII(c) ((unsigned char)(c)-040u < 0137u) + +#define CHECK_EOF() \ + if (buf == buf_end) { \ + *ret = -2; \ + return NULL; \ + } + +#define EXPECT_CHAR_NO_CHECK(ch) \ + if (*buf++ != ch) { \ + *ret = -1; \ + return NULL; \ + } + +#define EXPECT_CHAR(ch) \ + CHECK_EOF(); \ + EXPECT_CHAR_NO_CHECK(ch); + +#define ADVANCE_TOKEN(tok, toklen) \ + do { \ + const char *tok_start = buf; \ + static const char ALIGNED(16) ranges2[] = "\000\040\177\177"; \ + int found2; \ + buf = findchar_fast(buf, buf_end, ranges2, sizeof(ranges2) - 1, &found2); \ + if (!found2) { \ + CHECK_EOF(); \ + } \ + while (1) { \ + if (*buf == ' ') { \ + break; \ + } else if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { \ + if ((unsigned char)*buf < '\040' || *buf == '\177') { \ + *ret = -1; \ + return NULL; \ + } \ + } \ + ++buf; \ + CHECK_EOF(); \ + } \ + tok = tok_start; \ + toklen = buf - tok_start; \ + } while (0) + +static 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" + "\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" + "\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" + "\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" + "\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" + "\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" + "\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" + "\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"; + +static const char *findchar_fast(const char *buf, const char *buf_end, const char *ranges, size_t ranges_size, int *found) +{ + *found = 0; +#if __SSE4_2__ + if (likely(buf_end - buf >= 16)) { + __m128i ranges16 = _mm_loadu_si128((const __m128i *)ranges); + + size_t left = (buf_end - buf) & ~15; + do { + __m128i b16 = _mm_loadu_si128((const __m128i *)buf); + int r = _mm_cmpestri(ranges16, ranges_size, b16, 16, _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_RANGES | _SIDD_UBYTE_OPS); + if (unlikely(r != 16)) { + buf += r; + *found = 1; + break; + } + buf += 16; + left -= 16; + } while (likely(left != 0)); + } +#else + /* suppress unused parameter warning */ + (void)buf_end; + (void)ranges; + (void)ranges_size; +#endif + return buf; +} + +static const char *get_token_to_eol(const char *buf, const char *buf_end, const char **token, size_t *token_len, int *ret) +{ + const char *token_start = buf; + +#ifdef __SSE4_2__ + static const char ranges1[] = "\0\010" + /* allow HT */ + "\012\037" + /* allow SP and up to but not including DEL */ + "\177\177" + /* allow chars w. MSB set */ + ; + int found; + buf = findchar_fast(buf, buf_end, ranges1, sizeof(ranges1) - 1, &found); + if (found) + goto FOUND_CTL; +#else + /* find non-printable char within the next 8 bytes, this is the hottest code; manually inlined */ + while (likely(buf_end - buf >= 8)) { +#define DOIT() \ + do { \ + if (unlikely(!IS_PRINTABLE_ASCII(*buf))) \ + goto NonPrintable; \ + ++buf; \ + } while (0) + DOIT(); + DOIT(); + DOIT(); + DOIT(); + DOIT(); + DOIT(); + DOIT(); + DOIT(); +#undef DOIT + continue; + NonPrintable: + if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { + goto FOUND_CTL; + } + ++buf; + } +#endif + for (;; ++buf) { + CHECK_EOF(); + if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { + if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { + goto FOUND_CTL; + } + } + } +FOUND_CTL: + if (likely(*buf == '\015')) { + ++buf; + EXPECT_CHAR('\012'); + *token_len = buf - 2 - token_start; + } else if (*buf == '\012') { + *token_len = buf - token_start; + ++buf; + } else { + *ret = -1; + return NULL; + } + *token = token_start; + + return buf; +} + +static const char *is_complete(const char *buf, const char *buf_end, size_t last_len, int *ret) +{ + int ret_cnt = 0; + buf = last_len < 3 ? buf : buf + last_len - 3; + + while (1) { + CHECK_EOF(); + if (*buf == '\015') { + ++buf; + CHECK_EOF(); + EXPECT_CHAR('\012'); + ++ret_cnt; + } else if (*buf == '\012') { + ++buf; + ++ret_cnt; + } else { + ++buf; + ret_cnt = 0; + } + if (ret_cnt == 2) { + return buf; + } + } + + *ret = -2; + return NULL; +} + +#define PARSE_INT(valp_, mul_) \ + if (*buf < '0' || '9' < *buf) { \ + buf++; \ + *ret = -1; \ + return NULL; \ + } \ + *(valp_) = (mul_) * (*buf++ - '0'); + +#define PARSE_INT_3(valp_) \ + do { \ + int res_ = 0; \ + PARSE_INT(&res_, 100) \ + *valp_ = res_; \ + PARSE_INT(&res_, 10) \ + *valp_ += res_; \ + PARSE_INT(&res_, 1) \ + *valp_ += res_; \ + } while (0) + +/* returned pointer is always within [buf, buf_end), or null */ +static const char *parse_http_version(const char *buf, const char *buf_end, int *minor_version, int *ret) +{ + /* we want at least [HTTP/1.<two chars>] to try to parse */ + if (buf_end - buf < 9) { + *ret = -2; + return NULL; + } + EXPECT_CHAR_NO_CHECK('H'); + EXPECT_CHAR_NO_CHECK('T'); + EXPECT_CHAR_NO_CHECK('T'); + EXPECT_CHAR_NO_CHECK('P'); + EXPECT_CHAR_NO_CHECK('/'); + EXPECT_CHAR_NO_CHECK('1'); + EXPECT_CHAR_NO_CHECK('.'); + PARSE_INT(minor_version, 1); + return buf; +} + +static const char *parse_headers(const char *buf, const char *buf_end, struct phr_header *headers, size_t *num_headers, + size_t max_headers, int *ret) +{ + for (;; ++*num_headers) { + CHECK_EOF(); + if (*buf == '\015') { + ++buf; + EXPECT_CHAR('\012'); + break; + } else if (*buf == '\012') { + ++buf; + break; + } + if (*num_headers == max_headers) { + *ret = -1; + return NULL; + } + if (!(*num_headers != 0 && (*buf == ' ' || *buf == '\t'))) { + /* parsing name, but do not discard SP before colon, see + * http://www.mozilla.org/security/announce/2006/mfsa2006-33.html */ + headers[*num_headers].name = buf; + static const char ALIGNED(16) ranges1[] = "\x00 " /* control chars and up to SP */ + "\"\"" /* 0x22 */ + "()" /* 0x28,0x29 */ + ",," /* 0x2c */ + "//" /* 0x2f */ + ":@" /* 0x3a-0x40 */ + "[]" /* 0x5b-0x5d */ + "{\377"; /* 0x7b-0xff */ + int found; + buf = findchar_fast(buf, buf_end, ranges1, sizeof(ranges1) - 1, &found); + if (!found) { + CHECK_EOF(); + } + while (1) { + if (*buf == ':') { + break; + } else if (!token_char_map[(unsigned char)*buf]) { + *ret = -1; + return NULL; + } + ++buf; + CHECK_EOF(); + } + if ((headers[*num_headers].name_len = buf - headers[*num_headers].name) == 0) { + *ret = -1; + return NULL; + } + ++buf; + for (;; ++buf) { + CHECK_EOF(); + if (!(*buf == ' ' || *buf == '\t')) { + break; + } + } + } else { + headers[*num_headers].name = NULL; + headers[*num_headers].name_len = 0; + } + if ((buf = get_token_to_eol(buf, buf_end, &headers[*num_headers].value, &headers[*num_headers].value_len, ret)) == NULL) { + return NULL; + } + } + return buf; +} + +static const char *parse_request(const char *buf, const char *buf_end, const char **method, size_t *method_len, const char **path, + size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, + size_t max_headers, int *ret) +{ + /* skip first empty line (some clients add CRLF after POST content) */ + CHECK_EOF(); + if (*buf == '\015') { + ++buf; + EXPECT_CHAR('\012'); + } else if (*buf == '\012') { + ++buf; + } + + /* parse request line */ + ADVANCE_TOKEN(*method, *method_len); + ++buf; + ADVANCE_TOKEN(*path, *path_len); + ++buf; + if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) { + return NULL; + } + if (*buf == '\015') { + ++buf; + EXPECT_CHAR('\012'); + } else if (*buf == '\012') { + ++buf; + } else { + *ret = -1; + return NULL; + } + + return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); +} + +int phr_parse_request(const char *buf_start, size_t len, const char **method, size_t *method_len, const char **path, + size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len) +{ + const char *buf = buf_start, *buf_end = buf_start + len; + size_t max_headers = *num_headers; + int r; + + *method = NULL; + *method_len = 0; + *path = NULL; + *path_len = 0; + *minor_version = -1; + *num_headers = 0; + + /* if last_len != 0, check if the request is complete (a fast countermeasure + againt slowloris */ + if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { + return r; + } + + if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, minor_version, headers, num_headers, max_headers, + &r)) == NULL) { + return r; + } + + return (int)(buf - buf_start); +} + +static const char *parse_response(const char *buf, const char *buf_end, int *minor_version, int *status, const char **msg, + size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret) +{ + /* parse "HTTP/1.x" */ + if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) { + return NULL; + } + /* skip space */ + if (*buf++ != ' ') { + *ret = -1; + return NULL; + } + /* parse status code, we want at least [:digit:][:digit:][:digit:]<other char> to try to parse */ + if (buf_end - buf < 4) { + *ret = -2; + return NULL; + } + PARSE_INT_3(status); + + /* skip space */ + if (*buf++ != ' ') { + *ret = -1; + return NULL; + } + /* get message */ + if ((buf = get_token_to_eol(buf, buf_end, msg, msg_len, ret)) == NULL) { + return NULL; + } + + return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); +} + +int phr_parse_response(const char *buf_start, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len, + struct phr_header *headers, size_t *num_headers, size_t last_len) +{ + const char *buf = buf_start, *buf_end = buf + len; + size_t max_headers = *num_headers; + int r; + + *minor_version = -1; + *status = 0; + *msg = NULL; + *msg_len = 0; + *num_headers = 0; + + /* if last_len != 0, check if the response is complete (a fast countermeasure + against slowloris */ + if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { + return r; + } + + if ((buf = parse_response(buf, buf_end, minor_version, status, msg, msg_len, headers, num_headers, max_headers, &r)) == NULL) { + return r; + } + + return (int)(buf - buf_start); +} + +int phr_parse_headers(const char *buf_start, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len) +{ + const char *buf = buf_start, *buf_end = buf + len; + size_t max_headers = *num_headers; + int r; + + *num_headers = 0; + + /* if last_len != 0, check if the response is complete (a fast countermeasure + against slowloris */ + if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { + return r; + } + + if ((buf = parse_headers(buf, buf_end, headers, num_headers, max_headers, &r)) == NULL) { + return r; + } + + return (int)(buf - buf_start); +} + +enum { + CHUNKED_IN_CHUNK_SIZE, + CHUNKED_IN_CHUNK_EXT, + CHUNKED_IN_CHUNK_DATA, + CHUNKED_IN_CHUNK_CRLF, + CHUNKED_IN_TRAILERS_LINE_HEAD, + CHUNKED_IN_TRAILERS_LINE_MIDDLE +}; + +static int decode_hex(int ch) +{ + if ('0' <= ch && ch <= '9') { + return ch - '0'; + } else if ('A' <= ch && ch <= 'F') { + return ch - 'A' + 0xa; + } else if ('a' <= ch && ch <= 'f') { + return ch - 'a' + 0xa; + } else { + return -1; + } +} + +ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *_bufsz) +{ + size_t dst = 0, src = 0, bufsz = *_bufsz; + ssize_t ret = -2; /* incomplete */ + + while (1) { + switch (decoder->_state) { + case CHUNKED_IN_CHUNK_SIZE: + for (;; ++src) { + int v; + if (src == bufsz) + goto Exit; + if ((v = decode_hex(buf[src])) == -1) { + if (decoder->_hex_count == 0) { + ret = -1; + goto Exit; + } + break; + } + if (decoder->_hex_count == sizeof(size_t) * 2) { + ret = -1; + goto Exit; + } + decoder->bytes_left_in_chunk = decoder->bytes_left_in_chunk * 16 + v; + ++decoder->_hex_count; + } + decoder->_hex_count = 0; + decoder->_state = CHUNKED_IN_CHUNK_EXT; + /* fallthru */ + case CHUNKED_IN_CHUNK_EXT: + /* RFC 7230 A.2 "Line folding in chunk extensions is disallowed" */ + for (;; ++src) { + if (src == bufsz) + goto Exit; + if (buf[src] == '\012') + break; + } + ++src; + if (decoder->bytes_left_in_chunk == 0) { + if (decoder->consume_trailer) { + decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; + break; + } else { + goto Complete; + } + } + decoder->_state = CHUNKED_IN_CHUNK_DATA; + /* fallthru */ + case CHUNKED_IN_CHUNK_DATA: { + size_t avail = bufsz - src; + if (avail < decoder->bytes_left_in_chunk) { + if (dst != src) + memmove(buf + dst, buf + src, avail); + src += avail; + dst += avail; + decoder->bytes_left_in_chunk -= avail; + goto Exit; + } + if (dst != src) + memmove(buf + dst, buf + src, decoder->bytes_left_in_chunk); + src += decoder->bytes_left_in_chunk; + dst += decoder->bytes_left_in_chunk; + decoder->bytes_left_in_chunk = 0; + decoder->_state = CHUNKED_IN_CHUNK_CRLF; + } + /* fallthru */ + case CHUNKED_IN_CHUNK_CRLF: + for (;; ++src) { + if (src == bufsz) + goto Exit; + if (buf[src] != '\015') + break; + } + if (buf[src] != '\012') { + ret = -1; + goto Exit; + } + ++src; + decoder->_state = CHUNKED_IN_CHUNK_SIZE; + break; + case CHUNKED_IN_TRAILERS_LINE_HEAD: + for (;; ++src) { + if (src == bufsz) + goto Exit; + if (buf[src] != '\015') + break; + } + if (buf[src++] == '\012') + goto Complete; + decoder->_state = CHUNKED_IN_TRAILERS_LINE_MIDDLE; + /* fallthru */ + case CHUNKED_IN_TRAILERS_LINE_MIDDLE: + for (;; ++src) { + if (src == bufsz) + goto Exit; + if (buf[src] == '\012') + break; + } + ++src; + decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; + break; + default: + assert(!"decoder is corrupt"); + } + } + +Complete: + ret = bufsz - src; +Exit: + if (dst != src) + memmove(buf + dst, buf + src, bufsz - src); + *_bufsz = dst; + return ret; +} + +int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder) +{ + return decoder->_state == CHUNKED_IN_CHUNK_DATA; +} + +#undef CHECK_EOF +#undef EXPECT_CHAR +#undef ADVANCE_TOKEN diff --git a/plugins/picohttpparser/picohttpparser.h b/plugins/picohttpparser/picohttpparser.h new file mode 100644 index 00000000..a8fad71d --- /dev/null +++ b/plugins/picohttpparser/picohttpparser.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase, + * Shigeo Mitsunari + * + * The software is licensed under either the MIT License (below) or the Perl + * license. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#ifndef picohttpparser_h +#define picohttpparser_h + +#include <sys/types.h> + +#ifdef _MSC_VER +#define ssize_t intptr_t +#endif + +/* $Id: 67fd3ee74103ada60258d8a16e868f483abcca87 $ */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* contains name and value of a header (name == NULL if is a continuing line + * of a multiline header */ +struct phr_header { + const char *name; + size_t name_len; + const char *value; + size_t value_len; +}; + +/* returns number of bytes consumed if successful, -2 if request is partial, + * -1 if failed */ +int phr_parse_request(const char *buf, size_t len, const char **method, size_t *method_len, const char **path, size_t *path_len, + int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len); + +/* ditto */ +int phr_parse_response(const char *_buf, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len, + struct phr_header *headers, size_t *num_headers, size_t last_len); + +/* ditto */ +int phr_parse_headers(const char *buf, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len); + +/* should be zero-filled before start */ +struct phr_chunked_decoder { + size_t bytes_left_in_chunk; /* number of bytes left in current chunk */ + char consume_trailer; /* if trailing headers should be consumed */ + char _hex_count; + char _state; +}; + +/* the function rewrites the buffer given as (buf, bufsz) removing the chunked- + * encoding headers. When the function returns without an error, bufsz is + * updated to the length of the decoded data available. Applications should + * repeatedly call the function while it returns -2 (incomplete) every time + * supplying newly arrived data. If the end of the chunked-encoded data is + * found, the function returns a non-negative number indicating the number of + * octets left undecoded at the tail of the supplied buffer. Returns -1 on + * error. + */ +ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *bufsz); + +/* returns if the chunked decoder is in middle of chunked data */ +int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/plugins/sslutils.c b/plugins/sslutils.c index e38947e3..14f6579d 100644 --- a/plugins/sslutils.c +++ b/plugins/sslutils.c @@ -1,29 +1,29 @@ /***************************************************************************** -* +* * Monitoring Plugins SSL utilities -* +* * License: GPL * Copyright (c) 2005-2010 Monitoring Plugins Development Team -* +* * Description: -* +* * This file contains common functions for plugins that require SSL. -* +* * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. -* +* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. -* +* * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. -* -* +* +* *****************************************************************************/ #define MAX_CN_LENGTH 256 @@ -193,12 +193,22 @@ int np_net_ssl_read(void *buf, int num) { int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){ # ifdef USE_OPENSSL - X509 *certificate=NULL; + X509 *certificate = NULL; + certificate=SSL_get_peer_certificate(s); + return(np_net_ssl_check_certificate(certificate, days_till_exp_warn, days_till_exp_crit)); +# else /* ifndef USE_OPENSSL */ + printf("%s\n", _("WARNING - Plugin does not support checking certificates.")); + return STATE_WARNING; +# endif /* USE_OPENSSL */ +} + +int np_net_ssl_check_certificate(X509 *certificate, int days_till_exp_warn, int days_till_exp_crit){ +# ifdef USE_OPENSSL X509_NAME *subj=NULL; char timestamp[50] = ""; char cn[MAX_CN_LENGTH]= ""; char *tz; - + int cnlen =-1; int status=STATE_UNKNOWN; @@ -210,7 +220,6 @@ int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){ int time_remaining; time_t tm_t; - certificate=SSL_get_peer_certificate(s); if (!certificate) { printf("%s\n",_("CRITICAL - Cannot retrieve server certificate.")); return STATE_CRITICAL; diff --git a/plugins/t/check_curl.t b/plugins/t/check_curl.t new file mode 100644 index 00000000..050416cb --- /dev/null +++ b/plugins/t/check_curl.t @@ -0,0 +1,216 @@ +#! /usr/bin/perl -w -I .. +# +# HyperText Transfer Protocol (HTTP) Test via check_http +# +# + +use strict; +use Test::More; +use POSIX qw/mktime strftime/; +use NPTest; + +plan tests => 57; + +my $successOutput = '/OK.*HTTP.*second/'; + +my $res; +my $plugin = 'check_http'; +$plugin = 'check_curl' if $0 =~ m/check_curl/mx; + +my $host_tcp_http = getTestParameter( "NP_HOST_TCP_HTTP", + "A host providing the HTTP Service (a web server)", + "localhost" ); + +my $host_tls_http = getTestParameter( "host_tls_http", "NP_HOST_TLS_HTTP", "localhost", + "A host providing the HTTPS Service (a tls web server)" ); + +my $host_tls_cert = getTestParameter( "host_tls_cert", "NP_HOST_TLS_CERT", "localhost", + "the common name of the certificate." ); + + +my $host_nonresponsive = getTestParameter( "NP_HOST_NONRESPONSIVE", + "The hostname of system not responsive to network requests", + "10.0.0.1" ); + +my $hostname_invalid = getTestParameter( "NP_HOSTNAME_INVALID", + "An invalid (not known to DNS) hostname", + "nosuchhost"); + +my $internet_access = getTestParameter( "NP_INTERNET_ACCESS", + "Is this system directly connected to the internet?", + "yes"); + +my $host_tcp_http2 = getTestParameter( "NP_HOST_TCP_HTTP2", + "A host providing an index page containing the string 'monitoring'", + "test.monitoring-plugins.org" ); + +my $faketime = -x '/usr/bin/faketime' ? 1 : 0; + + +$res = NPTest->testCmd( + "./$plugin $host_tcp_http -wt 300 -ct 600" + ); +cmp_ok( $res->return_code, '==', 0, "Webserver $host_tcp_http responded" ); +like( $res->output, $successOutput, "Output OK" ); + +$res = NPTest->testCmd( + "./$plugin $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there' -k 'carl:frown'" + ); +like( $res->output, '/bob:there\r\ncarl:frown\r\n/', "Got headers with multiple -k options" ); + +$res = NPTest->testCmd( + "./$plugin $host_nonresponsive -wt 1 -ct 2 -t 3" + ); +cmp_ok( $res->return_code, '==', 2, "Webserver $host_nonresponsive not responding" ); +# was CRITICAL only, but both check_curl and check_http print HTTP CRITICAL (puzzle?!) +cmp_ok( $res->output, 'eq', "HTTP CRITICAL - Invalid HTTP response received from host on port 80: cURL returned 28 - Timeout was reached", "Output OK"); + +$res = NPTest->testCmd( + "./$plugin $hostname_invalid -wt 1 -ct 2" + ); +cmp_ok( $res->return_code, '==', 2, "Webserver $hostname_invalid not valid" ); +# The first part of the message comes from the OS catalogue, so cannot check this. +# On Debian, it is Name or service not known, on Darwin, it is No address associated with nodename +# Is also possible to get a socket timeout if DNS is not responding fast enough +# cURL gives us consistent strings from it's own 'lib/strerror.c' +like( $res->output, "/cURL returned 6 - Couldn't resolve host name/", "Output OK"); + +# host header checks +$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http"); +like( $res->output, '/^Host: '.$host_tcp_http.'\s*$/ms', "Host Header OK" ); +like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" ); + +$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http -p 80"); +like( $res->output, '/^Host: '.$host_tcp_http.'\s*$/ms', "Host Header OK" ); +like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" ); + +$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http:8080 -p 80"); +like( $res->output, '/^Host: '.$host_tcp_http.':8080\s*$/ms', "Host Header OK" ); +like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" ); + +$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http:8080 -p 80"); +like( $res->output, '/^Host: '.$host_tcp_http.':8080\s*$/ms', "Host Header OK" ); +like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" ); + +$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http:8080 -p 80 -k 'Host: testhost:8001'"); +like( $res->output, '/^Host: testhost:8001\s*$/ms', "Host Header OK" ); +like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" ); + +$res = NPTest->testCmd("./$plugin -v -I $host_tcp_http -p 80 -k 'Host: testhost:8001'"); +like( $res->output, '/^Host: testhost:8001\s*$/ms', "Host Header OK" ); +like( $res->output, '/CURLOPT_URL: http:\/\/'.$host_tcp_http.':80\//ms', "Url OK" ); + +SKIP: { + skip "No internet access", 3 if $internet_access eq "no"; + + $res = NPTest->testCmd("./$plugin -v -H $host_tls_http -S"); + like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" ); + + $res = NPTest->testCmd("./$plugin -v -H $host_tls_http:8080 -S -p 443"); + like( $res->output, '/^Host: '.$host_tls_http.':8080\s*$/ms', "Host Header OK" ); + + $res = NPTest->testCmd("./$plugin -v -H $host_tls_http:443 -S -p 443"); + like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" ); +}; + +SKIP: { + skip "No host serving monitoring in index file", 7 unless $host_tcp_http2; + + $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'monitoring'" ); + cmp_ok( $res->return_code, "==", 0, "Got a reference to 'monitoring'"); + + $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'mONiTORing'" ); + cmp_ok( $res->return_code, "==", 2, "Not got 'mONiTORing'"); + like ( $res->output, "/pattern not found/", "Error message says 'pattern not found'"); + + $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -R 'mONiTORing'" ); + cmp_ok( $res->return_code, "==", 0, "But case insensitive doesn't mind 'mONiTORing'"); + + $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'monitoring' --invert-regex" ); + cmp_ok( $res->return_code, "==", 2, "Invert results work when found"); + like ( $res->output, "/pattern found/", "Error message says 'pattern found'"); + + $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'mONiTORing' --invert-regex" ); + cmp_ok( $res->return_code, "==", 0, "And also when not found"); +} +SKIP: { + skip "No internet access", 16 if $internet_access eq "no"; + + $res = NPTest->testCmd( + "./$plugin --ssl $host_tls_http" + ); + cmp_ok( $res->return_code, '==', 0, "Can read https for $host_tls_http" ); + + $res = NPTest->testCmd( "./$plugin -C 1 --ssl $host_tls_http" ); + cmp_ok( $res->return_code, '==', 0, "Checking certificate for $host_tls_http"); + like ( $res->output, "/Certificate '$host_tls_cert' will expire on/", "Output OK" ); + my $saved_cert_output = $res->output; + + $res = NPTest->testCmd( "./$plugin -C 8000,1 --ssl $host_tls_http" ); + cmp_ok( $res->return_code, '==', 1, "Checking certificate for $host_tls_http"); + like ( $res->output, qr/WARNING - Certificate '$host_tls_cert' expires in \d+ day/, "Output Warning" ); + + $res = NPTest->testCmd( "./$plugin $host_tls_http -C 1" ); + is( $res->return_code, 0, "Old syntax for cert checking okay" ); + is( $res->output, $saved_cert_output, "Same output as new syntax" ); + + $res = NPTest->testCmd( "./$plugin -H $host_tls_http -C 1" ); + is( $res->return_code, 0, "Updated syntax for cert checking okay" ); + is( $res->output, $saved_cert_output, "Same output as new syntax" ); + + $res = NPTest->testCmd( "./$plugin -C 1 $host_tls_http" ); + cmp_ok( $res->output, 'eq', $saved_cert_output, "--ssl option automatically added"); + + $res = NPTest->testCmd( "./$plugin $host_tls_http -C 1" ); + cmp_ok( $res->output, 'eq', $saved_cert_output, "Old syntax for cert checking still works"); + + # run some certificate checks with faketime + SKIP: { + skip "No faketime binary found", 12 if !$faketime; + $res = NPTest->testCmd("LC_TIME=C TZ=UTC ./$plugin -C 1 $host_tls_http"); + like($res->output, qr/OK - Certificate '$host_tls_cert' will expire on/, "Catch cert output"); + is( $res->return_code, 0, "Catch cert output exit code" ); + my($mon,$day,$hour,$min,$sec,$year) = ($res->output =~ /(\w+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\d+)/); + if(!defined $year) { + die("parsing date failed from: ".$res->output); + } + 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}; + my $ts = mktime($sec, $min, $hour, $day, $months->{$mon}, $year-1900); + my $time = strftime("%Y-%m-%d %H:%M:%S", localtime($ts)); + $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"); + like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' just expired/, "Output on expire date"); + is( $res->return_code, 2, "Output on expire date" ); + + $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"); + like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 0 minutes/, "cert expires in 1 second output"); + is( $res->return_code, 2, "cert expires in 1 second exit code" ); + + $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"); + like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 2 minutes/, "cert expires in 2 minutes output"); + is( $res->return_code, 2, "cert expires in 2 minutes exit code" ); + + $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"); + like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 2 hours/, "cert expires in 2 hours output"); + is( $res->return_code, 2, "cert expires in 2 hours exit code" ); + + $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"); + like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expired on/, "Certificate expired output"); + is( $res->return_code, 2, "Certificate expired exit code" ); + }; + + $res = NPTest->testCmd( "./$plugin --ssl $host_tls_http -E" ); + like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' ); + like ( $res->output, '/time_ssl=[\d\.]+/', 'Extended Performance Data SSL Output OK' ); + + $res = NPTest->testCmd( + "./$plugin --ssl -H www.e-paycobalt.com" + ); + cmp_ok( $res->return_code, "==", 0, "Can read https for www.e-paycobalt.com (uses AES certificate)" ); + + + $res = NPTest->testCmd( "./$plugin -H www.mozilla.com -u /firefox -f follow" ); + is( $res->return_code, 0, "Redirection based on location is okay"); + + $res = NPTest->testCmd( "./$plugin -H www.mozilla.com --extended-perfdata" ); + like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' ); +} diff --git a/plugins/t/check_http.t b/plugins/t/check_http.t index b3760ebe..e92681e9 100644 --- a/plugins/t/check_http.t +++ b/plugins/t/check_http.t @@ -14,6 +14,8 @@ plan tests => 50; my $successOutput = '/OK.*HTTP.*second/'; my $res; +my $plugin = 'check_http'; +$plugin = 'check_curl' if $0 =~ m/check_curl/mx; my $host_tcp_http = getTestParameter("NP_HOST_TCP_HTTP", "A host providing the HTTP Service (a web server)", "localhost"); my $host_tls_http = getTestParameter("NP_HOST_TLS_HTTP", "A host providing the HTTPS Service (a tls web server)", "localhost"); @@ -29,24 +31,24 @@ my $faketime = -x '/usr/bin/faketime' ? 1 : 0; $res = NPTest->testCmd( - "./check_http $host_tcp_http -wt 300 -ct 600" + "./$plugin $host_tcp_http -wt 300 -ct 600" ); cmp_ok( $res->return_code, '==', 0, "Webserver $host_tcp_http responded" ); like( $res->output, $successOutput, "Output OK" ); $res = NPTest->testCmd( - "./check_http $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there' -k 'carl:frown'" + "./$plugin $host_tcp_http -wt 300 -ct 600 -v -v -v -k 'bob:there' -k 'carl:frown'" ); like( $res->output, '/bob:there\r\ncarl:frown\r\n/', "Got headers with multiple -k options" ); $res = NPTest->testCmd( - "./check_http $host_nonresponsive -wt 1 -ct 2 -t 3" + "./$plugin $host_nonresponsive -wt 1 -ct 2 -t 3" ); cmp_ok( $res->return_code, '==', 2, "Webserver $host_nonresponsive not responding" ); cmp_ok( $res->output, 'eq', "CRITICAL - Socket timeout after 3 seconds", "Output OK"); $res = NPTest->testCmd( - "./check_http $hostname_invalid -wt 1 -ct 2" + "./$plugin $hostname_invalid -wt 1 -ct 2" ); cmp_ok( $res->return_code, '==', 2, "Webserver $hostname_invalid not valid" ); # The first part of the message comes from the OS catalogue, so cannot check this. @@ -55,86 +57,86 @@ cmp_ok( $res->return_code, '==', 2, "Webserver $hostname_invalid not valid" ); like( $res->output, "/Unable to open TCP socket|Socket timeout after/", "Output OK"); # host header checks -$res = NPTest->testCmd("./check_http -v -H $host_tcp_http"); +$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http"); like( $res->output, '/^Host: '.$host_tcp_http.'\s*$/ms', "Host Header OK" ); -$res = NPTest->testCmd("./check_http -v -H $host_tcp_http -p 80"); +$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http -p 80"); like( $res->output, '/^Host: '.$host_tcp_http.'\s*$/ms', "Host Header OK" ); -$res = NPTest->testCmd("./check_http -v -H $host_tcp_http:8080 -p 80"); +$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http:8080 -p 80"); like( $res->output, '/^Host: '.$host_tcp_http.':8080\s*$/ms', "Host Header OK" ); -$res = NPTest->testCmd("./check_http -v -H $host_tcp_http:8080 -p 80"); +$res = NPTest->testCmd("./$plugin -v -H $host_tcp_http:8080 -p 80"); like( $res->output, '/^Host: '.$host_tcp_http.':8080\s*$/ms', "Host Header OK" ); SKIP: { skip "No internet access", 3 if $internet_access eq "no"; - $res = NPTest->testCmd("./check_http -v -H $host_tls_http -S"); + $res = NPTest->testCmd("./$plugin -v -H $host_tls_http -S"); like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" ); - $res = NPTest->testCmd("./check_http -v -H $host_tls_http:8080 -S -p 443"); + $res = NPTest->testCmd("./$plugin -v -H $host_tls_http:8080 -S -p 443"); like( $res->output, '/^Host: '.$host_tls_http.':8080\s*$/ms', "Host Header OK" ); - $res = NPTest->testCmd("./check_http -v -H $host_tls_http:443 -S -p 443"); + $res = NPTest->testCmd("./$plugin -v -H $host_tls_http:443 -S -p 443"); like( $res->output, '/^Host: '.$host_tls_http.'\s*$/ms', "Host Header OK" ); }; SKIP: { skip "No host serving monitoring in index file", 7 unless $host_tcp_http2; - $res = NPTest->testCmd( "./check_http -H $host_tcp_http2 -r 'monitoring'" ); + $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'monitoring'" ); cmp_ok( $res->return_code, "==", 0, "Got a reference to 'monitoring'"); - $res = NPTest->testCmd( "./check_http -H $host_tcp_http2 -r 'mONiTORing'" ); + $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'mONiTORing'" ); cmp_ok( $res->return_code, "==", 2, "Not got 'mONiTORing'"); like ( $res->output, "/pattern not found/", "Error message says 'pattern not found'"); - $res = NPTest->testCmd( "./check_http -H $host_tcp_http2 -R 'mONiTORing'" ); + $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -R 'mONiTORing'" ); cmp_ok( $res->return_code, "==", 0, "But case insensitive doesn't mind 'mONiTORing'"); - $res = NPTest->testCmd( "./check_http -H $host_tcp_http2 -r 'monitoring' --invert-regex" ); + $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'monitoring' --invert-regex" ); cmp_ok( $res->return_code, "==", 2, "Invert results work when found"); like ( $res->output, "/pattern found/", "Error message says 'pattern found'"); - $res = NPTest->testCmd( "./check_http -H $host_tcp_http2 -r 'mONiTORing' --invert-regex" ); + $res = NPTest->testCmd( "./$plugin -H $host_tcp_http2 -r 'mONiTORing' --invert-regex" ); cmp_ok( $res->return_code, "==", 0, "And also when not found"); } SKIP: { skip "No internet access", 16 if $internet_access eq "no"; $res = NPTest->testCmd( - "./check_http --ssl $host_tls_http" + "./$plugin --ssl $host_tls_http" ); cmp_ok( $res->return_code, '==', 0, "Can read https for $host_tls_http" ); - $res = NPTest->testCmd( "./check_http -C 1 --ssl $host_tls_http" ); + $res = NPTest->testCmd( "./$plugin -C 1 --ssl $host_tls_http" ); cmp_ok( $res->return_code, '==', 0, "Checking certificate for $host_tls_http"); like ( $res->output, "/Certificate '$host_tls_cert' will expire on/", "Output OK" ); my $saved_cert_output = $res->output; - $res = NPTest->testCmd( "./check_http -C 8000,1 --ssl $host_tls_http" ); + $res = NPTest->testCmd( "./$plugin -C 8000,1 --ssl $host_tls_http" ); cmp_ok( $res->return_code, '==', 1, "Checking certificate for $host_tls_http"); like ( $res->output, qr/WARNING - Certificate '$host_tls_cert' expires in \d+ day/, "Output Warning" ); - $res = NPTest->testCmd( "./check_http $host_tls_http -C 1" ); + $res = NPTest->testCmd( "./$plugin $host_tls_http -C 1" ); is( $res->return_code, 0, "Old syntax for cert checking okay" ); is( $res->output, $saved_cert_output, "Same output as new syntax" ); - $res = NPTest->testCmd( "./check_http -H $host_tls_http -C 1" ); + $res = NPTest->testCmd( "./$plugin -H $host_tls_http -C 1" ); is( $res->return_code, 0, "Updated syntax for cert checking okay" ); is( $res->output, $saved_cert_output, "Same output as new syntax" ); - $res = NPTest->testCmd( "./check_http -C 1 $host_tls_http" ); + $res = NPTest->testCmd( "./$plugin -C 1 $host_tls_http" ); cmp_ok( $res->output, 'eq', $saved_cert_output, "--ssl option automatically added"); - $res = NPTest->testCmd( "./check_http $host_tls_http -C 1" ); + $res = NPTest->testCmd( "./$plugin $host_tls_http -C 1" ); cmp_ok( $res->output, 'eq', $saved_cert_output, "Old syntax for cert checking still works"); # run some certificate checks with faketime SKIP: { - skip "No faketime binary found", 7 if !$faketime; - $res = NPTest->testCmd("LC_TIME=C TZ=UTC ./check_http -C 1 $host_tls_http"); + skip "No faketime binary found", 12 if !$faketime; + $res = NPTest->testCmd("LC_TIME=C TZ=UTC ./$plugin -C 1 $host_tls_http"); like($res->output, qr/OK - Certificate '$host_tls_cert' will expire on/, "Catch cert output"); is( $res->return_code, 0, "Catch cert output exit code" ); my($mon,$day,$hour,$min,$sec,$year) = ($res->output =~ /(\w+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\d+)/); @@ -144,51 +146,51 @@ SKIP: { 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}; my $ts = mktime($sec, $min, $hour, $day, $months->{$mon}, $year-1900); my $time = strftime("%Y-%m-%d %H:%M:%S", localtime($ts)); - $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts))."' ./check_http -C 1 $host_tls_http"); + $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"); like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' just expired/, "Output on expire date"); - $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-1))."' ./check_http -C 1 $host_tls_http"); + $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"); like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 0 minutes/, "cert expires in 1 second output"); - $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-120))."' ./check_http -C 1 $host_tls_http"); + $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"); like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 2 minutes/, "cert expires in 2 minutes output"); - $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts-7200))."' ./check_http -C 1 $host_tls_http"); + $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"); like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expires in 2 hours/, "cert expires in 2 hours output"); - $res = NPTest->testCmd("LC_TIME=C TZ=UTC faketime -f '".strftime("%Y-%m-%d %H:%M:%S", localtime($ts+1))."' ./check_http -C 1 $host_tls_http"); + $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"); like($res->output, qr/CRITICAL - Certificate '$host_tls_cert' expired on/, "Certificate expired output"); }; - $res = NPTest->testCmd( "./check_http --ssl $host_tls_http -E" ); + $res = NPTest->testCmd( "./$plugin --ssl $host_tls_http -E" ); like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' ); like ( $res->output, '/time_ssl=[\d\.]+/', 'Extended Performance Data SSL Output OK' ); $res = NPTest->testCmd( - "./check_http --ssl -H www.e-paycobalt.com" + "./$plugin --ssl -H www.e-paycobalt.com" ); cmp_ok( $res->return_code, "==", 0, "Can read https for www.e-paycobalt.com (uses AES certificate)" ); - $res = NPTest->testCmd( "./check_http -H www.mozilla.com -u /firefox -f follow" ); + $res = NPTest->testCmd( "./$plugin -H www.mozilla.com -u /firefox -f follow" ); is( $res->return_code, 0, "Redirection based on location is okay"); - $res = NPTest->testCmd( "./check_http -H www.mozilla.com --extended-perfdata" ); + $res = NPTest->testCmd( "./$plugin -H www.mozilla.com --extended-perfdata" ); like ( $res->output, '/time_connect=[\d\.]+/', 'Extended Performance Data Output OK' ); } SKIP: { skip "No internet access or proxy configured", 6 if $internet_access eq "no" or ! $host_tcp_proxy; - $res = NPTest->testCmd( "./check_http -I $host_tcp_proxy -p $port_tcp_proxy -u http://$host_tcp_http -e 200,301,302"); + $res = NPTest->testCmd( "./$plugin -I $host_tcp_proxy -p $port_tcp_proxy -u http://$host_tcp_http -e 200,301,302"); is( $res->return_code, 0, "Proxy HTTP works"); like($res->output, qr/OK: Status line output matched/, "Proxy HTTP Output is sufficent"); - $res = NPTest->testCmd( "./check_http -I $host_tcp_proxy -p $port_tcp_proxy -H $host_tls_http -S -j CONNECT"); + $res = NPTest->testCmd( "./$plugin -I $host_tcp_proxy -p $port_tcp_proxy -H $host_tls_http -S -j CONNECT"); is( $res->return_code, 0, "Proxy HTTP CONNECT works"); like($res->output, qr/HTTP OK:/, "Proxy HTTP CONNECT output sufficent"); - $res = NPTest->testCmd( "./check_http -I $host_tcp_proxy -p $port_tcp_proxy -H $host_tls_http -S -j CONNECT:HEAD"); + $res = NPTest->testCmd( "./$plugin -I $host_tcp_proxy -p $port_tcp_proxy -H $host_tls_http -S -j CONNECT:HEAD"); is( $res->return_code, 0, "Proxy HTTP CONNECT works with override method"); like($res->output, qr/HTTP OK:/, "Proxy HTTP CONNECT output sufficent"); } diff --git a/plugins/tests/check_curl.t b/plugins/tests/check_curl.t new file mode 100755 index 00000000..e182623c --- /dev/null +++ b/plugins/tests/check_curl.t @@ -0,0 +1,497 @@ +#! /usr/bin/perl -w -I .. +# +# Test check_http by having an actual HTTP server running +# +# To create the https server certificate: +# openssl req -new -x509 -keyout server-key.pem -out server-cert.pem -days 3650 -nodes +# Country Name (2 letter code) [AU]:UK +# State or Province Name (full name) [Some-State]:Derbyshire +# Locality Name (eg, city) []:Belper +# Organization Name (eg, company) [Internet Widgits Pty Ltd]:Monitoring Plugins +# Organizational Unit Name (eg, section) []: +# Common Name (eg, YOUR name) []:Ton Voon +# Email Address []:tonvoon@mac.com + +use strict; +use Test::More; +use NPTest; +use FindBin qw($Bin); + +$ENV{'LC_TIME'} = "C"; + +my $common_tests = 70; +my $ssl_only_tests = 8; +# Check that all dependent modules are available +eval "use HTTP::Daemon 6.01;"; +plan skip_all => 'HTTP::Daemon >= 6.01 required' if $@; +eval { + require HTTP::Status; + require HTTP::Response; +}; + +my $plugin = 'check_http'; +$plugin = 'check_curl' if $0 =~ m/check_curl/mx; + +# look for libcurl version to see if some advanced checks are possible (>= 7.49.0) +my $advanced_checks = 12; +my $use_advanced_checks = 0; +my $required_version = '7.49.0'; +my $virtual_host = 'www.somefunnyhost.com'; +my $virtual_port = 42; +my $curl_version = ''; +open (my $fh, '-|', "./$plugin --version") or die; +while (<$fh>) { + if (m{libcurl/([\d.]+)\s}) { + $curl_version = $1; + last; + } +} +close ($fh); +if ($curl_version) { + my ($major, $minor, $release) = split (/\./, $curl_version); + my ($req_major, $req_minor, $req_release) = split (/\./, $required_version); + my $check = ($major <=> $req_major or $minor <=> $req_minor or $release <=> $req_release); + if ($check >= 0) { + $use_advanced_checks = 1; + print "Found libcurl $major.$minor.$release. Using advanced checks\n"; + } +} + +if ($@) { + plan skip_all => "Missing required module for test: $@"; +} else { + if (-x "./$plugin") { + plan tests => $common_tests * 2 + $ssl_only_tests + $advanced_checks; + } else { + plan skip_all => "No $plugin compiled"; + } +} + +my $servers = { http => 0 }; # HTTP::Daemon should always be available +eval { require HTTP::Daemon::SSL }; +if ($@) { + diag "Cannot load HTTP::Daemon::SSL: $@"; +} else { + $servers->{https} = 0; +} + +# set a fixed version, so the header size doesn't vary +$HTTP::Daemon::VERSION = "1.00"; + +my $port_http = 50000 + int(rand(1000)); +my $port_https = $port_http + 1; +my $port_https_expired = $port_http + 2; + +# This array keeps sockets around for implementing timeouts +my @persist; + +# Start up all servers +my @pids; +my $pid = fork(); +if ($pid) { + # Parent + push @pids, $pid; + if (exists $servers->{https}) { + # Fork a normal HTTPS server + $pid = fork(); + if ($pid) { + # Parent + push @pids, $pid; + # Fork an expired cert server + $pid = fork(); + if ($pid) { + push @pids, $pid; + } else { + my $d = HTTP::Daemon::SSL->new( + LocalPort => $port_https_expired, + LocalAddr => "127.0.0.1", + SSL_cert_file => "$Bin/certs/expired-cert.pem", + SSL_key_file => "$Bin/certs/expired-key.pem", + ) || die; + print "Please contact https expired at: <URL:", $d->url, ">\n"; + run_server( $d ); + exit; + } + } else { + my $d = HTTP::Daemon::SSL->new( + LocalPort => $port_https, + LocalAddr => "127.0.0.1", + SSL_cert_file => "$Bin/certs/server-cert.pem", + SSL_key_file => "$Bin/certs/server-key.pem", + ) || die; + print "Please contact https at: <URL:", $d->url, ">\n"; + run_server( $d ); + exit; + } + } + # give our webservers some time to startup + sleep(1); +} else { + # Child + #print "child\n"; + my $d = HTTP::Daemon->new( + LocalPort => $port_http, + LocalAddr => "127.0.0.1", + ) || die; + print "Please contact http at: <URL:", $d->url, ">\n"; + run_server( $d ); + exit; +} + +# Run the same server on http and https +sub run_server { + my $d = shift; + MAINLOOP: while (my $c = $d->accept ) { + while (my $r = $c->get_request) { + if ($r->method eq "GET" and $r->url->path =~ m^/statuscode/(\d+)^) { + $c->send_basic_header($1); + $c->send_crlf; + } elsif ($r->method eq "GET" and $r->url->path =~ m^/file/(.*)^) { + $c->send_basic_header; + $c->send_crlf; + $c->send_file_response("$Bin/var/$1"); + } elsif ($r->method eq "GET" and $r->url->path eq "/slow") { + $c->send_basic_header; + $c->send_crlf; + sleep 1; + $c->send_response("slow"); + } elsif ($r->url->path eq "/method") { + if ($r->method eq "DELETE") { + $c->send_error(HTTP::Status->RC_METHOD_NOT_ALLOWED); + } elsif ($r->method eq "foo") { + $c->send_error(HTTP::Status->RC_NOT_IMPLEMENTED); + } else { + $c->send_status_line(200, $r->method); + } + } elsif ($r->url->path eq "/postdata") { + $c->send_basic_header; + $c->send_crlf; + $c->send_response($r->method.":".$r->content); + } elsif ($r->url->path eq "/redirect") { + $c->send_redirect( "/redirect2" ); + } elsif ($r->url->path eq "/redir_external") { + $c->send_redirect(($d->isa('HTTP::Daemon::SSL') ? "https" : "http") . "://169.254.169.254/redirect2" ); + } elsif ($r->url->path eq "/redirect2") { + $c->send_basic_header; + $c->send_crlf; + $c->send_response(HTTP::Response->new( 200, 'OK', undef, 'redirected' )); + } elsif ($r->url->path eq "/redir_timeout") { + $c->send_redirect( "/timeout" ); + } elsif ($r->url->path eq "/timeout") { + # Keep $c from being destroyed, but prevent severe leaks + unshift @persist, $c; + delete($persist[1000]); + next MAINLOOP; + } elsif ($r->url->path eq "/header_check") { + $c->send_basic_header; + $c->send_header('foo'); + $c->send_crlf; + } elsif ($r->url->path eq "/virtual_port") { + # return sent Host header + $c->send_basic_header; + $c->send_crlf; + $c->send_response(HTTP::Response->new( 200, 'OK', undef, $r->header ('Host'))); + } else { + $c->send_error(HTTP::Status->RC_FORBIDDEN); + } + $c->close; + } + } +} + +END { + foreach my $pid (@pids) { + if ($pid) { print "Killing $pid\n"; kill "INT", $pid } + } +}; + +if ($ARGV[0] && $ARGV[0] eq "-d") { + while (1) { + sleep 100; + } +} + +my $result; +my $command = "./$plugin -H 127.0.0.1"; + +run_common_tests( { command => "$command -p $port_http" } ); +SKIP: { + skip "HTTP::Daemon::SSL not installed", $common_tests + $ssl_only_tests if ! exists $servers->{https}; + run_common_tests( { command => "$command -p $port_https", ssl => 1 } ); + + $result = NPTest->testCmd( "$command -p $port_https -S -C 14" ); + is( $result->return_code, 0, "$command -p $port_https -S -C 14" ); + is( $result->output, 'OK - Certificate \'Ton Voon\' will expire on Sun Mar 3 21:41:28 2019 +0000.', "output ok" ); + + $result = NPTest->testCmd( "$command -p $port_https -S -C 14000" ); + is( $result->return_code, 1, "$command -p $port_https -S -C 14000" ); + like( $result->output, '/WARNING - Certificate \'Ton Voon\' expires in \d+ day\(s\) \(Sun Mar 3 21:41:28 2019 \+0000\)./', "output ok" ); + + # Expired cert tests + $result = NPTest->testCmd( "$command -p $port_https -S -C 13960,14000" ); + is( $result->return_code, 2, "$command -p $port_https -S -C 13960,14000" ); + like( $result->output, '/CRITICAL - Certificate \'Ton Voon\' expires in \d+ day\(s\) \(Sun Mar 3 21:41:28 2019 \+0000\)./', "output ok" ); + + $result = NPTest->testCmd( "$command -p $port_https_expired -S -C 7" ); + is( $result->return_code, 2, "$command -p $port_https_expired -S -C 7" ); + is( $result->output, + 'CRITICAL - Certificate \'Ton Voon\' expired on Thu Mar 5 00:13:16 2009 +0000.', + "output ok" ); + +} + +my $cmd; + +# advanced checks with virtual hostname and virtual port +SKIP: { + skip "libcurl version is smaller than $required_version", 6 unless $use_advanced_checks; + + # http without virtual port + $cmd = "./$plugin -H $virtual_host -I 127.0.0.1 -p $port_http -u /virtual_port -r ^$virtual_host:$port_http\$"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + # http with virtual port (!= 80) + $cmd = "./$plugin -H $virtual_host:$virtual_port -I 127.0.0.1 -p $port_http -u /virtual_port -r ^$virtual_host:$virtual_port\$"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + # http with virtual port (80) + $cmd = "./$plugin -H $virtual_host:80 -I 127.0.0.1 -p $port_http -u /virtual_port -r ^$virtual_host\$"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); +} + +# and the same for SSL +SKIP: { + 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; + # https without virtual port + $cmd = "./$plugin -H $virtual_host -I 127.0.0.1 -p $port_https --ssl -u /virtual_port -r ^$virtual_host:$port_https\$"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + # https with virtual port (!= 443) + $cmd = "./$plugin -H $virtual_host:$virtual_port -I 127.0.0.1 -p $port_https --ssl -u /virtual_port -r ^$virtual_host:$virtual_port\$"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + # https with virtual port (443) + $cmd = "./$plugin -H $virtual_host:443 -I 127.0.0.1 -p $port_https --ssl -u /virtual_port -r ^$virtual_host\$"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); +} + + + +sub run_common_tests { + my ($opts) = @_; + my $command = $opts->{command}; + if ($opts->{ssl}) { + $command .= " --ssl"; + } + + $result = NPTest->testCmd( "$command -u /file/root" ); + is( $result->return_code, 0, "/file/root"); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - 274 bytes in [\d\.]+ second/', "Output correct" ); + + $result = NPTest->testCmd( "$command -u /file/root -s Root" ); + is( $result->return_code, 0, "/file/root search for string"); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - 274 bytes in [\d\.]+ second/', "Output correct" ); + + $result = NPTest->testCmd( "$command -u /file/root -s NonRoot" ); + is( $result->return_code, 2, "Missing string check"); + 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"); + + $result = NPTest->testCmd( "$command -u /file/root -s NonRootWithOver30charsAndMoreFunThanAWetFish" ); + is( $result->return_code, 2, "Missing string check"); + 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"); + + $result = NPTest->testCmd( "$command -u /header_check -d foo" ); + is( $result->return_code, 0, "header_check search for string"); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - 96 bytes in [\d\.]+ second/', "Output correct" ); + + $result = NPTest->testCmd( "$command -u /header_check -d bar" ); + is( $result->return_code, 2, "Missing header string check"); + 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"); + + my $cmd; + $cmd = "$command -u /slow"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, "$cmd"); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + $result->output =~ /in ([\d\.]+) second/; + cmp_ok( $1, ">", 1, "Time is > 1 second" ); + + $cmd = "$command -u /statuscode/200"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -u /statuscode/200 -e 200"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - Status line output matched "200" - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -u /statuscode/201"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 201 Created - \d+ bytes in [\d\.]+ second /', "Output correct: ".$result->output ); + + $cmd = "$command -u /statuscode/201 -e 201"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 201 Created - Status line output matched "201" - \d+ bytes in [\d\.]+ second /', "Output correct: ".$result->output ); + + $cmd = "$command -u /statuscode/201 -e 200"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 2, $cmd); + like( $result->output, '/^HTTP CRITICAL - Invalid HTTP response received from host on port \d+: HTTP/1.1 201 Created/', "Output correct: ".$result->output ); + + $cmd = "$command -u /statuscode/200 -e 200,201,202"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + 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 ); + + $cmd = "$command -u /statuscode/201 -e 200,201,202"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + 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 ); + + $cmd = "$command -u /statuscode/203 -e 200,201,202"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 2, $cmd); + 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 ); + + $cmd = "$command -j HEAD -u /method"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 HEAD - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -j POST -u /method"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 POST - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -j GET -u /method"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 GET - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -u /method"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 GET - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -P foo -u /method"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 POST - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -j DELETE -u /method"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 1, $cmd); + like( $result->output, '/^HTTP WARNING: HTTP/1.1 405 Method Not Allowed/', "Output correct: ".$result->output ); + + $cmd = "$command -j foo -u /method"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 2, $cmd); + like( $result->output, '/^HTTP CRITICAL: HTTP/1.1 501 Not Implemented/', "Output correct: ".$result->output ); + + $cmd = "$command -P stufftoinclude -u /postdata -s POST:stufftoinclude"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -j PUT -P stufftoinclude -u /postdata -s PUT:stufftoinclude"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + # To confirm that the free doesn't segfault + $cmd = "$command -P stufftoinclude -j PUT -u /postdata -s PUT:stufftoinclude"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -u /redirect"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 301 Moved Permanently - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -f follow -u /redirect"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -u /redirect -k 'follow: me'"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 301 Moved Permanently - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -f follow -u /redirect -k 'follow: me'"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -f sticky -u /redirect -k 'follow: me'"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + $cmd = "$command -f stickyport -u /redirect -k 'follow: me'"; + $result = NPTest->testCmd( $cmd ); + is( $result->return_code, 0, $cmd); + like( $result->output, '/^HTTP OK: HTTP/1.1 200 OK - \d+ bytes in [\d\.]+ second/', "Output correct: ".$result->output ); + + # These tests may block + print "ALRM\n"; + + # stickyport - on full urlS port is set back to 80 otherwise + $cmd = "$command -f stickyport -u /redir_external -t 5 -s redirected"; + eval { + local $SIG{ALRM} = sub { die "alarm\n" }; + alarm(2); + $result = NPTest->testCmd( $cmd ); + alarm(0); }; + isnt( $@, "alarm\n", $cmd ); + is( $result->return_code, 0, $cmd ); + + # Let's hope there won't be any web server on :80 returning "redirected"! + $cmd = "$command -f sticky -u /redir_external -t 5 -s redirected"; + eval { + local $SIG{ALRM} = sub { die "alarm\n" }; + alarm(2); + $result = NPTest->testCmd( $cmd ); + alarm(0); }; + isnt( $@, "alarm\n", $cmd ); + isnt( $result->return_code, 0, $cmd ); + + # Test an external address - timeout + SKIP: { + skip "This doesn't seem to work all the time", 1 unless ($ENV{HTTP_EXTERNAL}); + $cmd = "$command -f follow -u /redir_external -t 5"; + eval { + $result = NPTest->testCmd( $cmd, 2 ); + }; + like( $@, "/timeout in command: $cmd/", $cmd ); + } + + $cmd = "$command -u /timeout -t 5"; + eval { + $result = NPTest->testCmd( $cmd, 2 ); + }; + like( $@, "/timeout in command: $cmd/", $cmd ); + + $cmd = "$command -f follow -u /redir_timeout -t 2"; + eval { + $result = NPTest->testCmd( $cmd, 5 ); + }; + is( $@, "", $cmd ); + +} diff --git a/plugins/tests/check_http.t b/plugins/tests/check_http.t index 006f1339..fe65325c 100755 --- a/plugins/tests/check_http.t +++ b/plugins/tests/check_http.t @@ -30,13 +30,16 @@ eval { require HTTP::Response; }; +my $plugin = 'check_http'; +$plugin = 'check_curl' if $0 =~ m/check_curl/mx; + if ($@) { plan skip_all => "Missing required module for test: $@"; } else { - if (-x "./check_http") { + if (-x "./$plugin") { plan tests => $common_tests * 2 + $ssl_only_tests + $virtual_port_tests; } else { - plan skip_all => "No check_http compiled"; + plan skip_all => "No $plugin compiled"; } } @@ -185,7 +188,7 @@ if ($ARGV[0] && $ARGV[0] eq "-d") { } my $result; -my $command = "./check_http -H 127.0.0.1"; +my $command = "./$plugin -H 127.0.0.1"; run_common_tests( { command => "$command -p $port_http" } ); SKIP: { @@ -13,10 +13,10 @@ msgstr "" "PO-Revision-Date: 2004-12-23 17:46+0100\n" "Last-Translator: <>\n" "Language-Team: English <en@li.org>\n" -"Language: en\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=iso-8859-1\n" "Content-Transfer-Encoding: 8bit\n" +"Language: en\n" "Plural-Forms: nplurals=2; plural=(n > 1);X-Generator: KBabel 1.3.1\n" #: plugins/check_by_ssh.c:86 plugins/check_cluster.c:76 plugins/check_dig.c:88 @@ -5438,8 +5438,8 @@ msgstr "" #: plugins/negate.c:174 msgid "" -"Ok must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer " -"(0-3)." +"Ok must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-" +"3)." msgstr "" #: plugins/negate.c:180 |