From f5f56e1a1c4d9e9496fcb9d81131066a964ccd23 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sat, 13 Apr 2024 14:15:43 +0200 Subject: Adding upstream version 2.4.1. Signed-off-by: Daniel Baumann --- src/lib/tcp/tests/Makefile.am | 57 ++ src/lib/tcp/tests/Makefile.in | 970 ++++++++++++++++++++ src/lib/tcp/tests/mt_tcp_listener_mgr_unittests.cc | 984 +++++++++++++++++++++ src/lib/tcp/tests/run_unittests.cc | 20 + src/lib/tcp/tests/tcp_listener_unittests.cc | 603 +++++++++++++ src/lib/tcp/tests/tcp_test_client.h | 437 +++++++++ src/lib/tcp/tests/tcp_test_listener.h | 315 +++++++ src/lib/tcp/tests/tls_listener_unittests.cc | 498 +++++++++++ 8 files changed, 3884 insertions(+) create mode 100644 src/lib/tcp/tests/Makefile.am create mode 100644 src/lib/tcp/tests/Makefile.in create mode 100644 src/lib/tcp/tests/mt_tcp_listener_mgr_unittests.cc create mode 100644 src/lib/tcp/tests/run_unittests.cc create mode 100644 src/lib/tcp/tests/tcp_listener_unittests.cc create mode 100644 src/lib/tcp/tests/tcp_test_client.h create mode 100644 src/lib/tcp/tests/tcp_test_listener.h create mode 100644 src/lib/tcp/tests/tls_listener_unittests.cc (limited to 'src/lib/tcp/tests') diff --git a/src/lib/tcp/tests/Makefile.am b/src/lib/tcp/tests/Makefile.am new file mode 100644 index 0000000..fd06ef4 --- /dev/null +++ b/src/lib/tcp/tests/Makefile.am @@ -0,0 +1,57 @@ +AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib +AM_CPPFLAGS += $(BOOST_INCLUDES) $(CRYPTO_CFLAGS) $(CRYPTO_INCLUDES) +AM_CPPFLAGS += -DTEST_CA_DIR=\"$(abs_srcdir)/../../asiolink/testutils/ca\" + +AM_CXXFLAGS = $(KEA_CXXFLAGS) + +if USE_STATIC_LINK +AM_LDFLAGS = -static +endif + +CLEANFILES = *.gcno *.gcda test-socket + +DISTCLEANFILES = + +noinst_SCRIPTS = + +TESTS_ENVIRONMENT = $(LIBTOOL) --mode=execute $(VALGRIND_COMMAND) + +TESTS = +if HAVE_GTEST +TESTS += run_unittests +run_unittests_SOURCES = run_unittests.cc +run_unittests_SOURCES += tcp_test_client.h tcp_test_listener.h +run_unittests_SOURCES += tcp_listener_unittests.cc +run_unittests_SOURCES += mt_tcp_listener_mgr_unittests.cc + +if HAVE_OPENSSL +run_unittests_SOURCES += tls_listener_unittests.cc +endif +if HAVE_BOTAN_BOOST +run_unittests_SOURCES += tls_listener_unittests.cc +endif + +run_unittests_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES) + +run_unittests_LDADD = $(top_builddir)/src/lib/tcp/libkea-tcp.la +run_unittests_LDADD += $(top_builddir)/src/lib/cc/libkea-cc.la +run_unittests_LDADD += $(top_builddir)/src/lib/asiolink/testutils/libasiolinktest.la +run_unittests_LDADD += $(top_builddir)/src/lib/asiolink/libkea-asiolink.la +run_unittests_LDADD += $(top_builddir)/src/lib/log/libkea-log.la +run_unittests_LDADD += $(top_builddir)/src/lib/util/unittests/libutil_unittests.la +run_unittests_LDADD += $(top_builddir)/src/lib/util/libkea-util.la +run_unittests_LDADD += $(top_builddir)/src/lib/exceptions/libkea-exceptions.la +run_unittests_LDADD += $(LOG4CPLUS_LIBS) $(BOOST_LIBS) $(CRYPTO_LIBS) +run_unittests_LDADD += $(GTEST_LDADD) + +run_unittests_LDFLAGS = $(AM_LDFLAGS) $(CRYPTO_LDFLAGS) $(GTEST_LDFLAGS) + +# Note: the ordering matters: -Wno-... must follow -Wextra (defined in +# KEA_CXXFLAGS) +run_unittests_CXXFLAGS = $(AM_CXXFLAGS) +if USE_GXX +run_unittests_CXXFLAGS += -Wno-unused-parameter -Wno-unused-private-field +endif +endif + +noinst_PROGRAMS = $(TESTS) diff --git a/src/lib/tcp/tests/Makefile.in b/src/lib/tcp/tests/Makefile.in new file mode 100644 index 0000000..2713f70 --- /dev/null +++ b/src/lib/tcp/tests/Makefile.in @@ -0,0 +1,970 @@ +# Makefile.in generated by automake 1.16.1 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2018 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + + +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +TESTS = $(am__EXEEXT_1) +@HAVE_GTEST_TRUE@am__append_1 = run_unittests +@HAVE_GTEST_TRUE@@HAVE_OPENSSL_TRUE@am__append_2 = tls_listener_unittests.cc +@HAVE_BOTAN_BOOST_TRUE@@HAVE_GTEST_TRUE@am__append_3 = tls_listener_unittests.cc +@HAVE_GTEST_TRUE@@USE_GXX_TRUE@am__append_4 = -Wno-unused-parameter -Wno-unused-private-field +noinst_PROGRAMS = $(am__EXEEXT_2) +subdir = src/lib/tcp/tests +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4macros/ax_boost_for_kea.m4 \ + $(top_srcdir)/m4macros/ax_cpp11.m4 \ + $(top_srcdir)/m4macros/ax_cpp20.m4 \ + $(top_srcdir)/m4macros/ax_crypto.m4 \ + $(top_srcdir)/m4macros/ax_find_library.m4 \ + $(top_srcdir)/m4macros/ax_gssapi.m4 \ + $(top_srcdir)/m4macros/ax_gtest.m4 \ + $(top_srcdir)/m4macros/ax_isc_rpath.m4 \ + $(top_srcdir)/m4macros/ax_netconf.m4 \ + $(top_srcdir)/m4macros/libtool.m4 \ + $(top_srcdir)/m4macros/ltoptions.m4 \ + $(top_srcdir)/m4macros/ltsugar.m4 \ + $(top_srcdir)/m4macros/ltversion.m4 \ + $(top_srcdir)/m4macros/lt~obsolete.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +@HAVE_GTEST_TRUE@am__EXEEXT_1 = run_unittests$(EXEEXT) +am__EXEEXT_2 = $(am__EXEEXT_1) +PROGRAMS = $(noinst_PROGRAMS) +am__run_unittests_SOURCES_DIST = run_unittests.cc tcp_test_client.h \ + tcp_test_listener.h tcp_listener_unittests.cc \ + mt_tcp_listener_mgr_unittests.cc tls_listener_unittests.cc +@HAVE_GTEST_TRUE@@HAVE_OPENSSL_TRUE@am__objects_1 = run_unittests-tls_listener_unittests.$(OBJEXT) +@HAVE_BOTAN_BOOST_TRUE@@HAVE_GTEST_TRUE@am__objects_2 = run_unittests-tls_listener_unittests.$(OBJEXT) +@HAVE_GTEST_TRUE@am_run_unittests_OBJECTS = \ +@HAVE_GTEST_TRUE@ run_unittests-run_unittests.$(OBJEXT) \ +@HAVE_GTEST_TRUE@ run_unittests-tcp_listener_unittests.$(OBJEXT) \ +@HAVE_GTEST_TRUE@ run_unittests-mt_tcp_listener_mgr_unittests.$(OBJEXT) \ +@HAVE_GTEST_TRUE@ $(am__objects_1) $(am__objects_2) +run_unittests_OBJECTS = $(am_run_unittests_OBJECTS) +am__DEPENDENCIES_1 = +@HAVE_GTEST_TRUE@run_unittests_DEPENDENCIES = \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/tcp/libkea-tcp.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/cc/libkea-cc.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/asiolink/testutils/libasiolinktest.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/asiolink/libkea-asiolink.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/log/libkea-log.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/util/unittests/libutil_unittests.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/util/libkea-util.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/exceptions/libkea-exceptions.la \ +@HAVE_GTEST_TRUE@ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ +@HAVE_GTEST_TRUE@ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) +AM_V_lt = $(am__v_lt_@AM_V@) +am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) +am__v_lt_0 = --silent +am__v_lt_1 = +run_unittests_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX \ + $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ + $(run_unittests_CXXFLAGS) $(CXXFLAGS) $(run_unittests_LDFLAGS) \ + $(LDFLAGS) -o $@ +SCRIPTS = $(noinst_SCRIPTS) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__maybe_remake_depfiles = depfiles +am__depfiles_remade = \ + ./$(DEPDIR)/run_unittests-mt_tcp_listener_mgr_unittests.Po \ + ./$(DEPDIR)/run_unittests-run_unittests.Po \ + ./$(DEPDIR)/run_unittests-tcp_listener_unittests.Po \ + ./$(DEPDIR)/run_unittests-tls_listener_unittests.Po +am__mv = mv -f +CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = +CXXLD = $(CXX) +CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ + $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CFLAGS) $(CFLAGS) +AM_V_CC = $(am__v_CC_@AM_V@) +am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) +am__v_CC_0 = @echo " CC " $@; +am__v_CC_1 = +CCLD = $(CC) +LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(AM_LDFLAGS) $(LDFLAGS) -o $@ +AM_V_CCLD = $(am__v_CCLD_@AM_V@) +am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) +am__v_CCLD_0 = @echo " CCLD " $@; +am__v_CCLD_1 = +SOURCES = $(run_unittests_SOURCES) +DIST_SOURCES = $(am__run_unittests_SOURCES_DIST) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` +ETAGS = etags +CTAGS = ctags +am__tty_colors_dummy = \ + mgn= red= grn= lgn= blu= brg= std=; \ + am__color_tests=no +am__tty_colors = { \ + $(am__tty_colors_dummy); \ + if test "X$(AM_COLOR_TESTS)" = Xno; then \ + am__color_tests=no; \ + elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ + am__color_tests=yes; \ + elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ + am__color_tests=yes; \ + fi; \ + if test $$am__color_tests = yes; then \ + red=''; \ + grn=''; \ + lgn=''; \ + blu=''; \ + mgn=''; \ + brg=''; \ + std=''; \ + fi; \ +} +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/depcomp +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ +ASCIIDOC = @ASCIIDOC@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BOOST_INCLUDES = @BOOST_INCLUDES@ +BOOST_LIBS = @BOOST_LIBS@ +BOTAN_TOOL = @BOTAN_TOOL@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CONTRIB_DIR = @CONTRIB_DIR@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CRYPTO_CFLAGS = @CRYPTO_CFLAGS@ +CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ +CRYPTO_LDFLAGS = @CRYPTO_LDFLAGS@ +CRYPTO_LIBS = @CRYPTO_LIBS@ +CRYPTO_PACKAGE = @CRYPTO_PACKAGE@ +CRYPTO_RPATH = @CRYPTO_RPATH@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DISTCHECK_BOOST_CONFIGURE_FLAG = @DISTCHECK_BOOST_CONFIGURE_FLAG@ +DISTCHECK_CONTRIB_CONFIGURE_FLAG = @DISTCHECK_CONTRIB_CONFIGURE_FLAG@ +DISTCHECK_CRYPTO_CONFIGURE_FLAG = @DISTCHECK_CRYPTO_CONFIGURE_FLAG@ +DISTCHECK_GSSAPI_CONFIGURE_FLAG = @DISTCHECK_GSSAPI_CONFIGURE_FLAG@ +DISTCHECK_GTEST_CONFIGURE_FLAG = @DISTCHECK_GTEST_CONFIGURE_FLAG@ +DISTCHECK_KEA_SHELL_CONFIGURE_FLAG = @DISTCHECK_KEA_SHELL_CONFIGURE_FLAG@ +DISTCHECK_LIBYANGCPP_CONFIGURE_FLAG = @DISTCHECK_LIBYANGCPP_CONFIGURE_FLAG@ +DISTCHECK_LIBYANG_CONFIGURE_FLAG = @DISTCHECK_LIBYANG_CONFIGURE_FLAG@ +DISTCHECK_LOG4CPLUS_CONFIGURE_FLAG = @DISTCHECK_LOG4CPLUS_CONFIGURE_FLAG@ +DISTCHECK_MYSQL_CONFIGURE_FLAG = @DISTCHECK_MYSQL_CONFIGURE_FLAG@ +DISTCHECK_PERFDHCP_CONFIGURE_FLAG = @DISTCHECK_PERFDHCP_CONFIGURE_FLAG@ +DISTCHECK_PGSQL_CONFIGURE_FLAG = @DISTCHECK_PGSQL_CONFIGURE_FLAG@ +DISTCHECK_PREMIUM_CONFIGURE_FLAG = @DISTCHECK_PREMIUM_CONFIGURE_FLAG@ +DISTCHECK_SYSREPOCPP_CONFIGURE_FLAG = @DISTCHECK_SYSREPOCPP_CONFIGURE_FLAG@ +DISTCHECK_SYSREPO_CONFIGURE_FLAG = @DISTCHECK_SYSREPO_CONFIGURE_FLAG@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GENHTML = @GENHTML@ +GREP = @GREP@ +GSSAPI_CFLAGS = @GSSAPI_CFLAGS@ +GSSAPI_LIBS = @GSSAPI_LIBS@ +GTEST_CONFIG = @GTEST_CONFIG@ +GTEST_INCLUDES = @GTEST_INCLUDES@ +GTEST_LDADD = @GTEST_LDADD@ +GTEST_LDFLAGS = @GTEST_LDFLAGS@ +GTEST_SOURCE = @GTEST_SOURCE@ +HAVE_NETCONF = @HAVE_NETCONF@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +KEA_CXXFLAGS = @KEA_CXXFLAGS@ +KEA_SRCID = @KEA_SRCID@ +KRB5_CONFIG = @KRB5_CONFIG@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LEX = @LEX@ +LEXLIB = @LEXLIB@ +LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIBYANGCPP_CPPFLAGS = @LIBYANGCPP_CPPFLAGS@ +LIBYANGCPP_INCLUDEDIR = @LIBYANGCPP_INCLUDEDIR@ +LIBYANGCPP_LIBS = @LIBYANGCPP_LIBS@ +LIBYANGCPP_PREFIX = @LIBYANGCPP_PREFIX@ +LIBYANGCPP_VERSION = @LIBYANGCPP_VERSION@ +LIBYANG_CPPFLAGS = @LIBYANG_CPPFLAGS@ +LIBYANG_INCLUDEDIR = @LIBYANG_INCLUDEDIR@ +LIBYANG_LIBS = @LIBYANG_LIBS@ +LIBYANG_PREFIX = @LIBYANG_PREFIX@ +LIBYANG_VERSION = @LIBYANG_VERSION@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LOG4CPLUS_INCLUDES = @LOG4CPLUS_INCLUDES@ +LOG4CPLUS_LIBS = @LOG4CPLUS_LIBS@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MYSQL_CPPFLAGS = @MYSQL_CPPFLAGS@ +MYSQL_LIBS = @MYSQL_LIBS@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PACKAGE_VERSION_TYPE = @PACKAGE_VERSION_TYPE@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PDFLATEX = @PDFLATEX@ +PERL = @PERL@ +PGSQL_CPPFLAGS = @PGSQL_CPPFLAGS@ +PGSQL_LIBS = @PGSQL_LIBS@ +PKGPYTHONDIR = @PKGPYTHONDIR@ +PKG_CONFIG = @PKG_CONFIG@ +PLANTUML = @PLANTUML@ +PREMIUM_DIR = @PREMIUM_DIR@ +PYTHON = @PYTHON@ +PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ +PYTHON_PLATFORM = @PYTHON_PLATFORM@ +PYTHON_PREFIX = @PYTHON_PREFIX@ +PYTHON_VERSION = @PYTHON_VERSION@ +RANLIB = @RANLIB@ +SED = @SED@ +SEP = @SEP@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SPHINXBUILD = @SPHINXBUILD@ +SRPD_PLUGINS_PATH = @SRPD_PLUGINS_PATH@ +SR_PLUGINS_PATH = @SR_PLUGINS_PATH@ +SR_REPO_PATH = @SR_REPO_PATH@ +STRIP = @STRIP@ +SYSREPOCPP_CPPFLAGS = @SYSREPOCPP_CPPFLAGS@ +SYSREPOCPP_INCLUDEDIR = @SYSREPOCPP_INCLUDEDIR@ +SYSREPOCPP_LIBS = @SYSREPOCPP_LIBS@ +SYSREPOCPP_PREFIX = @SYSREPOCPP_PREFIX@ +SYSREPOCPP_VERSION = @SYSREPOCPP_VERSION@ +SYSREPO_CPPFLAGS = @SYSREPO_CPPFLAGS@ +SYSREPO_INCLUDEDIR = @SYSREPO_INCLUDEDIR@ +SYSREPO_LIBS = @SYSREPO_LIBS@ +SYSREPO_PREFIX = @SYSREPO_PREFIX@ +SYSREPO_VERSION = @SYSREPO_VERSION@ +USE_LCOV = @USE_LCOV@ +VALGRIND = @VALGRIND@ +VERSION = @VERSION@ +WARNING_GCC_44_STRICT_ALIASING_CFLAG = @WARNING_GCC_44_STRICT_ALIASING_CFLAG@ +YACC = @YACC@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +pkgpyexecdir = @pkgpyexecdir@ +pkgpythondir = @pkgpythondir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +pyexecdir = @pyexecdir@ +pythondir = @pythondir@ +runstatedir = @runstatedir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib \ + $(BOOST_INCLUDES) $(CRYPTO_CFLAGS) $(CRYPTO_INCLUDES) \ + -DTEST_CA_DIR=\"$(abs_srcdir)/../../asiolink/testutils/ca\" +AM_CXXFLAGS = $(KEA_CXXFLAGS) +@USE_STATIC_LINK_TRUE@AM_LDFLAGS = -static +CLEANFILES = *.gcno *.gcda test-socket +DISTCLEANFILES = +noinst_SCRIPTS = +TESTS_ENVIRONMENT = $(LIBTOOL) --mode=execute $(VALGRIND_COMMAND) +@HAVE_GTEST_TRUE@run_unittests_SOURCES = run_unittests.cc \ +@HAVE_GTEST_TRUE@ tcp_test_client.h tcp_test_listener.h \ +@HAVE_GTEST_TRUE@ tcp_listener_unittests.cc \ +@HAVE_GTEST_TRUE@ mt_tcp_listener_mgr_unittests.cc \ +@HAVE_GTEST_TRUE@ $(am__append_2) $(am__append_3) +@HAVE_GTEST_TRUE@run_unittests_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES) +@HAVE_GTEST_TRUE@run_unittests_LDADD = \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/tcp/libkea-tcp.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/cc/libkea-cc.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/asiolink/testutils/libasiolinktest.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/asiolink/libkea-asiolink.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/log/libkea-log.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/util/unittests/libutil_unittests.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/util/libkea-util.la \ +@HAVE_GTEST_TRUE@ $(top_builddir)/src/lib/exceptions/libkea-exceptions.la \ +@HAVE_GTEST_TRUE@ $(LOG4CPLUS_LIBS) $(BOOST_LIBS) \ +@HAVE_GTEST_TRUE@ $(CRYPTO_LIBS) $(GTEST_LDADD) +@HAVE_GTEST_TRUE@run_unittests_LDFLAGS = $(AM_LDFLAGS) $(CRYPTO_LDFLAGS) $(GTEST_LDFLAGS) + +# Note: the ordering matters: -Wno-... must follow -Wextra (defined in +# KEA_CXXFLAGS) +@HAVE_GTEST_TRUE@run_unittests_CXXFLAGS = $(AM_CXXFLAGS) \ +@HAVE_GTEST_TRUE@ $(am__append_4) +all: all-am + +.SUFFIXES: +.SUFFIXES: .cc .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/tcp/tests/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/lib/tcp/tests/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +clean-noinstPROGRAMS: + @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ + echo " rm -f" $$list; \ + rm -f $$list || exit $$?; \ + test -n "$(EXEEXT)" || exit 0; \ + list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ + echo " rm -f" $$list; \ + rm -f $$list + +run_unittests$(EXEEXT): $(run_unittests_OBJECTS) $(run_unittests_DEPENDENCIES) $(EXTRA_run_unittests_DEPENDENCIES) + @rm -f run_unittests$(EXEEXT) + $(AM_V_CXXLD)$(run_unittests_LINK) $(run_unittests_OBJECTS) $(run_unittests_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/run_unittests-mt_tcp_listener_mgr_unittests.Po@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/run_unittests-run_unittests.Po@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/run_unittests-tcp_listener_unittests.Po@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/run_unittests-tls_listener_unittests.Po@am__quote@ # am--include-marker + +$(am__depfiles_remade): + @$(MKDIR_P) $(@D) + @echo '# dummy' >$@-t && $(am__mv) $@-t $@ + +am--depfiles: $(am__depfiles_remade) + +.cc.o: +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< + +.cc.obj: +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` + +.cc.lo: +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< + +run_unittests-run_unittests.o: run_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -MT run_unittests-run_unittests.o -MD -MP -MF $(DEPDIR)/run_unittests-run_unittests.Tpo -c -o run_unittests-run_unittests.o `test -f 'run_unittests.cc' || echo '$(srcdir)/'`run_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/run_unittests-run_unittests.Tpo $(DEPDIR)/run_unittests-run_unittests.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='run_unittests.cc' object='run_unittests-run_unittests.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -c -o run_unittests-run_unittests.o `test -f 'run_unittests.cc' || echo '$(srcdir)/'`run_unittests.cc + +run_unittests-run_unittests.obj: run_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -MT run_unittests-run_unittests.obj -MD -MP -MF $(DEPDIR)/run_unittests-run_unittests.Tpo -c -o run_unittests-run_unittests.obj `if test -f 'run_unittests.cc'; then $(CYGPATH_W) 'run_unittests.cc'; else $(CYGPATH_W) '$(srcdir)/run_unittests.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/run_unittests-run_unittests.Tpo $(DEPDIR)/run_unittests-run_unittests.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='run_unittests.cc' object='run_unittests-run_unittests.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -c -o run_unittests-run_unittests.obj `if test -f 'run_unittests.cc'; then $(CYGPATH_W) 'run_unittests.cc'; else $(CYGPATH_W) '$(srcdir)/run_unittests.cc'; fi` + +run_unittests-tcp_listener_unittests.o: tcp_listener_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -MT run_unittests-tcp_listener_unittests.o -MD -MP -MF $(DEPDIR)/run_unittests-tcp_listener_unittests.Tpo -c -o run_unittests-tcp_listener_unittests.o `test -f 'tcp_listener_unittests.cc' || echo '$(srcdir)/'`tcp_listener_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/run_unittests-tcp_listener_unittests.Tpo $(DEPDIR)/run_unittests-tcp_listener_unittests.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='tcp_listener_unittests.cc' object='run_unittests-tcp_listener_unittests.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -c -o run_unittests-tcp_listener_unittests.o `test -f 'tcp_listener_unittests.cc' || echo '$(srcdir)/'`tcp_listener_unittests.cc + +run_unittests-tcp_listener_unittests.obj: tcp_listener_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -MT run_unittests-tcp_listener_unittests.obj -MD -MP -MF $(DEPDIR)/run_unittests-tcp_listener_unittests.Tpo -c -o run_unittests-tcp_listener_unittests.obj `if test -f 'tcp_listener_unittests.cc'; then $(CYGPATH_W) 'tcp_listener_unittests.cc'; else $(CYGPATH_W) '$(srcdir)/tcp_listener_unittests.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/run_unittests-tcp_listener_unittests.Tpo $(DEPDIR)/run_unittests-tcp_listener_unittests.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='tcp_listener_unittests.cc' object='run_unittests-tcp_listener_unittests.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -c -o run_unittests-tcp_listener_unittests.obj `if test -f 'tcp_listener_unittests.cc'; then $(CYGPATH_W) 'tcp_listener_unittests.cc'; else $(CYGPATH_W) '$(srcdir)/tcp_listener_unittests.cc'; fi` + +run_unittests-mt_tcp_listener_mgr_unittests.o: mt_tcp_listener_mgr_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -MT run_unittests-mt_tcp_listener_mgr_unittests.o -MD -MP -MF $(DEPDIR)/run_unittests-mt_tcp_listener_mgr_unittests.Tpo -c -o run_unittests-mt_tcp_listener_mgr_unittests.o `test -f 'mt_tcp_listener_mgr_unittests.cc' || echo '$(srcdir)/'`mt_tcp_listener_mgr_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/run_unittests-mt_tcp_listener_mgr_unittests.Tpo $(DEPDIR)/run_unittests-mt_tcp_listener_mgr_unittests.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='mt_tcp_listener_mgr_unittests.cc' object='run_unittests-mt_tcp_listener_mgr_unittests.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -c -o run_unittests-mt_tcp_listener_mgr_unittests.o `test -f 'mt_tcp_listener_mgr_unittests.cc' || echo '$(srcdir)/'`mt_tcp_listener_mgr_unittests.cc + +run_unittests-mt_tcp_listener_mgr_unittests.obj: mt_tcp_listener_mgr_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -MT run_unittests-mt_tcp_listener_mgr_unittests.obj -MD -MP -MF $(DEPDIR)/run_unittests-mt_tcp_listener_mgr_unittests.Tpo -c -o run_unittests-mt_tcp_listener_mgr_unittests.obj `if test -f 'mt_tcp_listener_mgr_unittests.cc'; then $(CYGPATH_W) 'mt_tcp_listener_mgr_unittests.cc'; else $(CYGPATH_W) '$(srcdir)/mt_tcp_listener_mgr_unittests.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/run_unittests-mt_tcp_listener_mgr_unittests.Tpo $(DEPDIR)/run_unittests-mt_tcp_listener_mgr_unittests.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='mt_tcp_listener_mgr_unittests.cc' object='run_unittests-mt_tcp_listener_mgr_unittests.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -c -o run_unittests-mt_tcp_listener_mgr_unittests.obj `if test -f 'mt_tcp_listener_mgr_unittests.cc'; then $(CYGPATH_W) 'mt_tcp_listener_mgr_unittests.cc'; else $(CYGPATH_W) '$(srcdir)/mt_tcp_listener_mgr_unittests.cc'; fi` + +run_unittests-tls_listener_unittests.o: tls_listener_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -MT run_unittests-tls_listener_unittests.o -MD -MP -MF $(DEPDIR)/run_unittests-tls_listener_unittests.Tpo -c -o run_unittests-tls_listener_unittests.o `test -f 'tls_listener_unittests.cc' || echo '$(srcdir)/'`tls_listener_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/run_unittests-tls_listener_unittests.Tpo $(DEPDIR)/run_unittests-tls_listener_unittests.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='tls_listener_unittests.cc' object='run_unittests-tls_listener_unittests.o' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -c -o run_unittests-tls_listener_unittests.o `test -f 'tls_listener_unittests.cc' || echo '$(srcdir)/'`tls_listener_unittests.cc + +run_unittests-tls_listener_unittests.obj: tls_listener_unittests.cc +@am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -MT run_unittests-tls_listener_unittests.obj -MD -MP -MF $(DEPDIR)/run_unittests-tls_listener_unittests.Tpo -c -o run_unittests-tls_listener_unittests.obj `if test -f 'tls_listener_unittests.cc'; then $(CYGPATH_W) 'tls_listener_unittests.cc'; else $(CYGPATH_W) '$(srcdir)/tls_listener_unittests.cc'; fi` +@am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/run_unittests-tls_listener_unittests.Tpo $(DEPDIR)/run_unittests-tls_listener_unittests.Po +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='tls_listener_unittests.cc' object='run_unittests-tls_listener_unittests.obj' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(run_unittests_CPPFLAGS) $(CPPFLAGS) $(run_unittests_CXXFLAGS) $(CXXFLAGS) -c -o run_unittests-tls_listener_unittests.obj `if test -f 'tls_listener_unittests.cc'; then $(CYGPATH_W) 'tls_listener_unittests.cc'; else $(CYGPATH_W) '$(srcdir)/tls_listener_unittests.cc'; fi` + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +check-TESTS: $(TESTS) + @failed=0; all=0; xfail=0; xpass=0; skip=0; \ + srcdir=$(srcdir); export srcdir; \ + list=' $(TESTS) '; \ + $(am__tty_colors); \ + if test -n "$$list"; then \ + for tst in $$list; do \ + if test -f ./$$tst; then dir=./; \ + elif test -f $$tst; then dir=; \ + else dir="$(srcdir)/"; fi; \ + if $(TESTS_ENVIRONMENT) $${dir}$$tst $(AM_TESTS_FD_REDIRECT); then \ + all=`expr $$all + 1`; \ + case " $(XFAIL_TESTS) " in \ + *[\ \ ]$$tst[\ \ ]*) \ + xpass=`expr $$xpass + 1`; \ + failed=`expr $$failed + 1`; \ + col=$$red; res=XPASS; \ + ;; \ + *) \ + col=$$grn; res=PASS; \ + ;; \ + esac; \ + elif test $$? -ne 77; then \ + all=`expr $$all + 1`; \ + case " $(XFAIL_TESTS) " in \ + *[\ \ ]$$tst[\ \ ]*) \ + xfail=`expr $$xfail + 1`; \ + col=$$lgn; res=XFAIL; \ + ;; \ + *) \ + failed=`expr $$failed + 1`; \ + col=$$red; res=FAIL; \ + ;; \ + esac; \ + else \ + skip=`expr $$skip + 1`; \ + col=$$blu; res=SKIP; \ + fi; \ + echo "$${col}$$res$${std}: $$tst"; \ + done; \ + if test "$$all" -eq 1; then \ + tests="test"; \ + All=""; \ + else \ + tests="tests"; \ + All="All "; \ + fi; \ + if test "$$failed" -eq 0; then \ + if test "$$xfail" -eq 0; then \ + banner="$$All$$all $$tests passed"; \ + else \ + if test "$$xfail" -eq 1; then failures=failure; else failures=failures; fi; \ + banner="$$All$$all $$tests behaved as expected ($$xfail expected $$failures)"; \ + fi; \ + else \ + if test "$$xpass" -eq 0; then \ + banner="$$failed of $$all $$tests failed"; \ + else \ + if test "$$xpass" -eq 1; then passes=pass; else passes=passes; fi; \ + banner="$$failed of $$all $$tests did not behave as expected ($$xpass unexpected $$passes)"; \ + fi; \ + fi; \ + dashes="$$banner"; \ + skipped=""; \ + if test "$$skip" -ne 0; then \ + if test "$$skip" -eq 1; then \ + skipped="($$skip test was not run)"; \ + else \ + skipped="($$skip tests were not run)"; \ + fi; \ + test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \ + dashes="$$skipped"; \ + fi; \ + report=""; \ + if test "$$failed" -ne 0 && test -n "$(PACKAGE_BUGREPORT)"; then \ + report="Please report to $(PACKAGE_BUGREPORT)"; \ + test `echo "$$report" | wc -c` -le `echo "$$banner" | wc -c` || \ + dashes="$$report"; \ + fi; \ + dashes=`echo "$$dashes" | sed s/./=/g`; \ + if test "$$failed" -eq 0; then \ + col="$$grn"; \ + else \ + col="$$red"; \ + fi; \ + echo "$${col}$$dashes$${std}"; \ + echo "$${col}$$banner$${std}"; \ + test -z "$$skipped" || echo "$${col}$$skipped$${std}"; \ + test -z "$$report" || echo "$${col}$$report$${std}"; \ + echo "$${col}$$dashes$${std}"; \ + test "$$failed" -eq 0; \ + else :; fi + +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am + $(MAKE) $(AM_MAKEFLAGS) check-TESTS +check: check-am +all-am: Makefile $(PROGRAMS) $(SCRIPTS) +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool clean-noinstPROGRAMS \ + mostlyclean-am + +distclean: distclean-am + -rm -f ./$(DEPDIR)/run_unittests-mt_tcp_listener_mgr_unittests.Po + -rm -f ./$(DEPDIR)/run_unittests-run_unittests.Po + -rm -f ./$(DEPDIR)/run_unittests-tcp_listener_unittests.Po + -rm -f ./$(DEPDIR)/run_unittests-tls_listener_unittests.Po + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f ./$(DEPDIR)/run_unittests-mt_tcp_listener_mgr_unittests.Po + -rm -f ./$(DEPDIR)/run_unittests-run_unittests.Po + -rm -f ./$(DEPDIR)/run_unittests-tcp_listener_unittests.Po + -rm -f ./$(DEPDIR)/run_unittests-tls_listener_unittests.Po + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: + +.MAKE: check-am install-am install-strip + +.PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-TESTS \ + check-am clean clean-generic clean-libtool \ + clean-noinstPROGRAMS cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am + +.PRECIOUS: Makefile + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/src/lib/tcp/tests/mt_tcp_listener_mgr_unittests.cc b/src/lib/tcp/tests/mt_tcp_listener_mgr_unittests.cc new file mode 100644 index 0000000..ab561c6 --- /dev/null +++ b/src/lib/tcp/tests/mt_tcp_listener_mgr_unittests.cc @@ -0,0 +1,984 @@ +// Copyright (C) 2022-2023 Internet Systems Consortium, Inc. ("ISC") +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +using namespace isc; +using namespace isc::asiolink; +using namespace isc::asiolink::test; +using namespace isc::config; +using namespace isc::data; +using namespace boost::asio::ip; +using namespace isc::tcp; +using namespace isc::util; +namespace ph = std::placeholders; + +namespace { + +/// @brief IP address to which TCP service is bound. +const std::string SERVER_ADDRESS = "127.0.0.1"; + +/// @brief Port number to which TCP service is bound. +const unsigned short SERVER_PORT = 18123; + +/// @brief Test timeout (ms). +const long TEST_TIMEOUT = 10000; + +/// @brief Test fixture class for @ref MtTcpListenerMgr. +class MtTcpListenerMgrTest : public ::testing::Test { +public: + + /// @brief Constructor. + /// + /// Starts test timer which detects timeouts, and enables multi-threading mode. + MtTcpListenerMgrTest() + : mt_listener_mgr_(), io_service_(), test_timer_(io_service_), + run_io_service_timer_(io_service_), clients_(), num_threads_(), + num_clients_(), num_in_progress_(0), num_finished_(0), chunk_size_(0), + pause_cnt_(0), response_handler_(0) { + test_timer_.setup(std::bind(&MtTcpListenerMgrTest::timeoutHandler, this, true), + TEST_TIMEOUT, IntervalTimer::ONE_SHOT); + + // Enable multi-threading. + MultiThreadingMgr::instance().setMode(true); + } + + /// @brief Destructor. + /// + /// Removes TCP clients and disables MT. + virtual ~MtTcpListenerMgrTest() { + // Wipe out the listener. + mt_listener_mgr_.reset(); + + // Destroy all remaining clients. + for (auto const& client : clients_) { + client->close(); + } + + // Disable multi-threading. + MultiThreadingMgr::instance().setMode(false); + } + + /// @brief Replaces the test's listener with a new listener + /// + /// @param num_threads Number of threads the listener should use. + /// @param response_handler Response handler connections should use + void createMtTcpListenerMgr(size_t num_threads, + TcpTestConnection::ResponseHandler response_handler = 0) { + // Create a listener with prescribed number of threads. + ASSERT_NO_THROW_LOG(mt_listener_mgr_.reset(new MtTcpListenerMgr( + std::bind(&MtTcpListenerMgrTest::listenerFactory, this, + ph::_1, ph::_2, ph::_3, ph::_4, ph::_5, ph::_6), + IOAddress(SERVER_ADDRESS), + SERVER_PORT, num_threads))); + + ASSERT_TRUE(mt_listener_mgr_); + setResponseHandler(response_handler); + } + + /// @brief Return the inner TcpTestListener's audit trail + AuditTrailPtr getAuditTrail() { + TcpListenerPtr l = mt_listener_mgr_->getTcpListener(); + if (!l) { + isc_throw(Unexpected, "Test is broken? Listener is null?"); + } + + TcpTestListenerPtr listener = boost::dynamic_pointer_cast( + mt_listener_mgr_->getTcpListener()); + if (!listener) { + isc_throw(Unexpected, "Test is broken? Listener is not a TcpTestListener"); + } + + return (listener->audit_trail_); + } + + /// @brief TcpListener factory for MtTcpListener to instantiate new listeners. + TcpListenerPtr listenerFactory(asiolink::IOService& io_service, + const asiolink::IOAddress& server_address, + const unsigned short server_port, + const asiolink::TlsContextPtr& tls_context, + const TcpListener::IdleTimeout& idle_timeout, + const TcpConnectionFilterCallback& connection_filter) { + TcpTestListenerPtr listener(new TcpTestListener(io_service, + server_address, + server_port, + tls_context, + idle_timeout, + connection_filter)); + // Set the response handler the listener will pass into each connection. + listener->setResponseHandler(response_handler_); + return (listener); + } + + /// @brief Callback function each client invokes when done. + /// + /// It stops the IO service + /// + /// @param fail_on_timeout Specifies if test failure should be reported. + void clientDone() { + io_service_.stop(); + } + + /// @brief Initiates a command via a new TCP client. + /// + /// This method creates a TcpTestClient instance, adds the + /// client to the list of clients, and starts a request. + /// The client will run on the main thread and be driven by + /// the test's IOService instance. + /// + /// @param request_str String containing the request + /// to be sent. + void startRequest(const std::string& request_str) { + // Instantiate the client. + TcpTestClientPtr client(new TcpTestClient(io_service_, + std::bind(&MtTcpListenerMgrTest::clientDone, this), + TlsContextPtr(), + SERVER_ADDRESS, SERVER_PORT)); + // Add it to the list of clients. + clients_.push_back(client); + + // Start the request. Note, nothing happens until the IOService runs. + client->startRequest(request_str); + } + + /// @brief Initiates a "thread" command via a new TCP client. + /// + /// This method creates a TcpTestClient instance, adds the + /// client to the list of clients, and starts a request based + /// on the given command. The client will run on the main + /// thread and be driven by the test's IOService instance. + /// + /// The command has a single argument, "client-ptr". The function creates + /// the value for this argument from the pointer address of client instance + /// it creates. This argument should be echoed back in the response, along + /// with the thread-id of the MtTcpListener thread which handled the + /// command. The response body should look this: + /// + /// ``` + /// [ { "arguments": { "client-ptr": "xxxxx", "thread-id": "zzzzz" }, "result": 0} ] + /// ``` + void startThreadCommand(std::string request_str) { + // Create a new client. + TcpTestClientPtr client(new TcpTestClient(io_service_, + std::bind(&MtTcpListenerMgrTest::clientDone, this), + TlsContextPtr(), + SERVER_ADDRESS, SERVER_PORT)); + + // Construct the "thread" command post including the argument, + // "client-ptr", whose value is the stringified pointer to the + // newly created client. + std::stringstream request_body; + request_body << "{\"command\": \"thread\", \"arguments\": { \"client-ptr\": \"" + << client << "\", \"request\": \"" << request_str << "\" } }"; + + // Add it to the list of clients. + clients_.push_back(client); + + // Start the request. Note, nothing happens until the IOService runs. + ASSERT_NO_THROW_LOG(client->startRequest(request_body.str())); + } + + /// @brief Callback function invoke upon test timeout. + /// + /// It stops the IO service and reports test timeout. + /// + /// @param fail_on_timeout Specifies if test failure should be reported. + void timeoutHandler(const bool fail_on_timeout) { + if (fail_on_timeout) { + ADD_FAILURE() << "Timeout occurred while running the test!"; + } + io_service_.stop(); + } + + /// @brief Runs IO service with optional timeout. + /// + /// We iterate over calls to asio::io_service.run(), until + /// all the clients have completed their requests. We do it this way + /// because the test clients stop the io_service when they're + /// through with a request. + /// + /// @param request_limit Desired number of requests the function should wait + /// to be processed before returning. + void runIOService(size_t request_limit = 0) { + if (!request_limit) { + request_limit = clients_.size(); + } + + // Loop until the clients are done, an error occurs, or the time runs out. + size_t num_done = 0; + while (num_done != request_limit) { + // Always call restart() before we call run(); + io_service_.restart(); + + // Run until a client stops the service. + io_service_.run(); + + // If all the clients are done receiving, the test is done. + num_done = 0; + for (auto const& client : clients_) { + if (client->receiveDone()) { + ++num_done; + } + } + } + } + + /// @brief Set the response handler use by each connection. + /// + /// Sets the response handler invoked by requestReceived. + /// + /// @param response_handler Handler function to invoke + void setResponseHandler(TcpTestConnection::ResponseHandler response_handler) { + response_handler_ = response_handler; + }; + + /// @brief Response handler for the 'thread' command. + /// + /// @param request JSON text containing thread command and arguments + /// which should contain one string element, "client-ptr", whose value is + /// the stringified pointer to the client that issued the command. + /// + /// @return Returns JSON text containing the response which should include + /// a string value 'thread-id': + std::string synchronizedCommandHandler(const std::string& request) { + // If the number of in progress commands is less than the number + // of threads, then wait here until we're notified. Otherwise, + // notify everyone and finish. The idea is to force each thread + // to handle the same number of requests over the course of the + // test, making verification reliable. + { + std::unique_lock lck(mutex_); + ++num_in_progress_; + if (num_in_progress_ == chunk_size_) { + num_finished_ = 0; + cv_.notify_all(); + } else { + bool ret = cv_.wait_for(lck, std::chrono::seconds(10), + [&]() { return (num_in_progress_ == chunk_size_); }); + if (!ret) { + ADD_FAILURE() << "clients failed to start work"; + } + } + } + + // Create the map of response arguments. + ElementPtr arguments = Element::createMap(); + + // Parse the command. + ConstElementPtr command = Element::fromJSON(request); + ConstElementPtr command_arguments; + std::string command_str = parseCommand(command_arguments, command); + + // First we echo the client-ptr command argument. + ConstElementPtr client_ptr = command_arguments->get("client-ptr"); + if (!client_ptr) { + return (createAnswerString(CONTROL_RESULT_ERROR, "missing client-ptr")); + } + + arguments->set("client-ptr", client_ptr); + + // Now we add the thread-id. + std::stringstream ss; + ss << std::this_thread::get_id(); + arguments->set("thread-id", Element::create(ss.str())); + arguments->set("sign-off", Element::create("good bye")); + + { + std::unique_lock lck(mutex_); + num_finished_++; + if (num_finished_ == chunk_size_) { + // We're all done, notify the others and finish. + num_in_progress_ = 0; + cv_.notify_all(); + } else { + // I'm done but others aren't wait here. + bool ret = cv_.wait_for(lck, std::chrono::seconds(10), + [&]() { return (num_finished_ == chunk_size_); }); + if (!ret) { + ADD_FAILURE() << "clients failed to finish work"; + } + } + } + + EXPECT_THROW(mt_listener_mgr_->start(), InvalidOperation); + EXPECT_THROW(mt_listener_mgr_->pause(), MultiThreadingInvalidOperation); + EXPECT_THROW(mt_listener_mgr_->resume(), MultiThreadingInvalidOperation); + EXPECT_THROW(mt_listener_mgr_->stop(), MultiThreadingInvalidOperation); + + // We're done, ship it! + std::string str = createAnswerString(CONTROL_RESULT_SUCCESS, arguments); + return (str); + } + + /// @brief Create a response string of JSON + /// + /// @param status_code Indicates outcome of the command + /// @param arguments Element tree of response arguments + /// + /// @return JSON text containing the response + std::string createAnswerString(const int status_code, std::string text) { + ConstElementPtr answer = createAnswer(status_code, text); + std::stringstream os; + answer->toJSON(os); + return(os.str()); + } + + /// @brief Create a response string of JSON + /// + /// @param status_code Indicates outcome of the command + /// @param arguments Element tree of response arguments + /// + /// @return JSON text containing the response + std::string createAnswerString(const int status_code, + ConstElementPtr arguments) { + ConstElementPtr answer = createAnswer(status_code, arguments); + std::stringstream os; + answer->toJSON(os); + return(os.str()); + } + + /// @brief Simple response handler for the 'thread' command. + /// + /// @param command_name Command name, i.e. 'thread'. + /// @param command_arguments Command arguments should contain + /// one string element, "client-ptr", whose value is the stringified + /// pointer to the client that issued the command. + /// + /// @return Returns response with map of arguments containing + /// a string value 'thread-id': + std::string simpleCommandHandler(const std::string& request) { + // Create the map of response arguments. + ElementPtr arguments = Element::createMap(); + + // Parse the command. + ConstElementPtr command = Element::fromJSON(request); + ConstElementPtr command_arguments; + std::string command_str = parseCommand(command_arguments, command); + + // First we echo the client-ptr command argument. + ConstElementPtr client_ptr = command_arguments->get("client-ptr"); + if (!client_ptr) { + return (createAnswerString(CONTROL_RESULT_ERROR, "missing client-ptr")); + } + + arguments->set("client-ptr", client_ptr); + + // Now we add the thread-id. + std::stringstream ss; + ss << std::this_thread::get_id(); + arguments->set("thread-id", Element::create(ss.str())); + arguments->set("sign-off", Element::create("good bye")); + + // We're done, ship it! + std::string str = createAnswerString(CONTROL_RESULT_SUCCESS, arguments); + return (str); + } + + /// @brief Submits one or more thread commands to a MtTcpListener. + /// + /// This function command will create a MtTcpListener + /// with the given number of threads, initiates the given + /// number of clients, each requesting the "thread" command, + /// and then iteratively runs the test's IOService until all + /// the clients have received their responses or an error occurs. + /// + /// It requires that the number of clients, when greater than the + /// number of threads, be a multiple of the number of threads. The + /// thread command handler is structured in such a way as to ensure + /// (we hope) that each thread handles the same number of commands. + /// + /// @param num_threads - the number of threads the MtTcpListener + /// should use. Must be greater than 0. + /// @param num_clients - the number of clients that should issue the + /// thread command. Each client is used to carry out a single thread + /// command request. Must be greater than 0 and a multiple of num_threads + /// if it is greater than num_threads. + void threadListenAndRespond(size_t num_threads, size_t num_clients) { + // First we makes sure the parameter rules apply. + ASSERT_TRUE(num_threads); + ASSERT_TRUE(num_clients); + ASSERT_TRUE((num_clients < num_threads) || (num_clients % num_threads == 0)); + + num_threads_ = num_threads; + num_clients_ = num_clients; + chunk_size_ = num_threads_; + if (num_clients_ < chunk_size_) { + chunk_size_ = num_clients_; + } + + // Create an MtTcpListenerMgr with prescribed number of threads. + createMtTcpListenerMgr(num_threads, + std::bind(&MtTcpListenerMgrTest::synchronizedCommandHandler, + this, ph::_1)); + + // Start it and verify it is running. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->start()); + ASSERT_TRUE(mt_listener_mgr_->isRunning()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), num_threads); + + // Maps the number of clients served by a given thread-id. + std::map clients_per_thread; + + // Initiate the prescribed number of command requests. + num_in_progress_ = 0; + while (clients_.size() < num_clients) { + ASSERT_NO_THROW_LOG(startThreadCommand("I am done")); + } + + // Now we run the client-side IOService until all requests are done, + // errors occur or the test times out. + ASSERT_NO_FATAL_FAILURE(runIOService()); + + // Stop the listener and then verify it has stopped. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->stop()); + ASSERT_TRUE(mt_listener_mgr_->isStopped()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 0); + + // Iterate over the clients, checking their outcomes. + size_t total_responses = 0; + for (auto const& client : clients_) { + // Client should have completed its receive successfully. + ASSERT_TRUE(client->receiveDone()); + + // Now we walk the element tree to get the response data. It should look + // this: + // + // { + // "arguments": { "client-ptr": "xxxxx", + // "thread-id": "zzzzz" }, + // "result": 0 + // ] + // + // We expect 1 response. + auto responses = client->getResponses(); + ASSERT_EQ(responses.size(), 1); + + // First we turn it into an Element tree. + ConstElementPtr answer; + ASSERT_NO_THROW_LOG(answer = Element::fromJSON(responses.front())); + + // Answer should be a map containing "arguments" and "results". + ASSERT_EQ(answer->getType(), Element::map); + + // "result" should be 0. + ConstElementPtr result = answer->get("result"); + ASSERT_TRUE(result); + ASSERT_EQ(result->getType(), Element::integer); + ASSERT_EQ(result->intValue(), 0); + + // "arguments" is a map containing "client-ptr" and "thread-id". + ConstElementPtr arguments = answer->get("arguments"); + ASSERT_TRUE(arguments); + ASSERT_EQ(arguments->getType(), Element::map); + + // "client-ptr" is a string. + ConstElementPtr client_ptr = arguments->get("client-ptr"); + ASSERT_TRUE(client_ptr); + ASSERT_EQ(client_ptr->getType(), Element::string); + + // "thread-id" is a string. + ConstElementPtr thread_id = arguments->get("thread-id"); + ASSERT_TRUE(thread_id); + ASSERT_EQ(thread_id->getType(), Element::string); + std::string thread_id_str = thread_id->stringValue(); + + // Make sure the response received was for this client. + std::stringstream ss; + ss << client; + ASSERT_EQ(client_ptr->stringValue(), ss.str()); + + // Bump the client count for the given thread-id. + auto it = clients_per_thread.find(thread_id_str); + if (it != clients_per_thread.end()) { + clients_per_thread[thread_id_str] = it->second + 1; + } else { + clients_per_thread[thread_id_str] = 1; + } + ++total_responses; + } + + // We should have responses for all our clients. + EXPECT_EQ(total_responses, num_clients); + + // Verify we have the expected number of entries in our map. + size_t expected_thread_count = (num_clients < num_threads ? + num_clients : num_threads); + + ASSERT_EQ(clients_per_thread.size(), expected_thread_count); + + // Each thread-id ought to have handled the same number of clients. + for (auto const& it : clients_per_thread) { + EXPECT_EQ(it.second, num_clients / clients_per_thread.size()) + << "thread-id: " << it.first + << ", clients: " << it.second << std::endl; + } + } + + /// @brief Pauses and resumes a MtTcpListener while it processes command + /// requests. + /// + /// This function command will create a MtTcpListenerMgr + /// with the given number of threads, initiates the given + /// number of clients, each requesting the "thread" command, + /// and then iteratively runs the test's IOService until all + /// the clients have received their responses or an error occurs. + /// It will pause and resume the listener at intervals governed + /// by the given number of pauses. + /// + /// @param num_threads - the number of threads the MtTcpListener + /// should use. Must be greater than 0. + /// @param num_clients - the number of clients that should issue the + /// thread command. Each client is used to carry out a single thread + /// command request. Must be greater than 0. + /// @param num_pauses Desired number of times the listener should be + /// paused during the test. Must be greater than 0. + void workPauseAndResume(size_t num_threads, size_t num_clients, + size_t num_pauses) { + // First we makes sure the parameter rules apply. + ASSERT_TRUE(num_threads); + ASSERT_TRUE(num_clients); + ASSERT_TRUE(num_pauses); + num_threads_ = num_threads; + num_clients_ = num_clients; + + // Create an MtTcpListenerMgr with prescribed number of threads and the + // simple handler. + createMtTcpListenerMgr(num_threads, + std::bind(&MtTcpListenerMgrTest::simpleCommandHandler, + this, ph::_1)); + + ASSERT_TRUE(mt_listener_mgr_); + + // Start it and verify it is running. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->start()); + ASSERT_TRUE(mt_listener_mgr_->isRunning()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), num_threads); + + // Initiate the prescribed number of command requests. + num_in_progress_ = 0; + while (clients_.size() < num_clients) { + ASSERT_NO_THROW_LOG(startThreadCommand("I am done")); + } + + // Now we run the client-side IOService until all requests are done, + // errors occur or the test times out. We'll pause and resume the + // number of times given by num_pauses. + size_t num_done = 0; + size_t total_requests = clients_.size(); + while (num_done < total_requests) { + // Calculate how many more requests to process before we pause again. + // We divide the number of outstanding requests by the number of pauses + // and stop after we've done at least that many more requests. + size_t request_limit = (pause_cnt_ < num_pauses ? + (num_done + ((total_requests - num_done) / num_pauses)) + : total_requests); + + // Run test IOService until we hit the limit. + runIOService(request_limit); + + // If we've done all our pauses we should be through. + if (pause_cnt_ == num_pauses) { + break; + } + + // Pause the client. + ASSERT_NO_THROW(mt_listener_mgr_->pause()); + ASSERT_TRUE(mt_listener_mgr_->isPaused()); + ++pause_cnt_; + + // Check our progress. + num_done = 0; + for (auto const& client : clients_) { + if (client->receiveDone()) { + ++num_done; + } + } + + // We should completed at least as many as our + // target limit. + ASSERT_GE(num_done, request_limit); + + // Resume the listener. + ASSERT_NO_THROW(mt_listener_mgr_->resume()); + ASSERT_TRUE(mt_listener_mgr_->isRunning()); + } + + // Stop the listener and then verify it has stopped. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->stop()); + ASSERT_TRUE(mt_listener_mgr_->isStopped()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 0); + + // Iterate over the clients, checking their outcomes. + size_t total_responses = 0; + for (auto const& client : clients_) { + // Client should have completed its receive successfully. + ASSERT_TRUE(client->receiveDone()); + + // Now we walk the element tree to get the response data. It should look + // this: + // + // { + // "arguments": { "client-ptr": "xxxxx", + // "sign-off": "good bye", + // "thread-id": "zzzzz" }, + // "result": 0 + // } + // + // We expect one response. + auto responses = client->getResponses(); + ASSERT_EQ(responses.size(), 1); + + // First we turn it into an Element tree. + ConstElementPtr answer; + ASSERT_NO_THROW_LOG(answer = Element::fromJSON(responses.front())); + + // Answer should be a map containing "arguments" and "results". + ASSERT_EQ(answer->getType(), Element::map); + + // "result" should be 0. + ConstElementPtr result = answer->get("result"); + ASSERT_TRUE(result); + ASSERT_EQ(result->getType(), Element::integer); + ASSERT_EQ(result->intValue(), 0); + + // "arguments" is a map containing "client-ptr" and "thread-id". + ConstElementPtr arguments = answer->get("arguments"); + ASSERT_TRUE(arguments); + ASSERT_EQ(arguments->getType(), Element::map); + + // "client-ptr" is a string. + ConstElementPtr client_ptr = arguments->get("client-ptr"); + ASSERT_TRUE(client_ptr); + ASSERT_EQ(client_ptr->getType(), Element::string); + + // "thread-id" is a string. + ConstElementPtr thread_id = arguments->get("thread-id"); + ASSERT_TRUE(thread_id); + ASSERT_EQ(thread_id->getType(), Element::string); + std::string thread_id_str = thread_id->stringValue(); + + // Make sure the response received was for this client. + std::stringstream ss; + ss << client; + ASSERT_EQ(client_ptr->stringValue(), ss.str()); + + ++total_responses; + } + + // We should have responses for all our clients. + EXPECT_EQ(total_responses, num_clients); + + // We should have had the expected number of pauses. + if (!num_pauses) { + ASSERT_EQ(pause_cnt_, 0); + } else { + // We allow a range on pauses of +-1. + ASSERT_TRUE((num_pauses - 1) <= pause_cnt_ && + (pause_cnt_ <= (num_pauses + 1))) + << " num_pauses: " << num_pauses + << ", pause_cnt_" << pause_cnt_; + } + } + + /// @brief MtTcpListenerMgr instance under test. + MtTcpListenerMgrPtr mt_listener_mgr_; + + /// @brief IO service used in drive the test and test clients. + IOService io_service_; + + /// @brief Asynchronous timer service to detect timeouts. + IntervalTimer test_timer_; + + /// @brief Asynchronous timer for running IO service for a specified amount + /// of time. + IntervalTimer run_io_service_timer_; + + /// @brief List of client connections. + std::list clients_; + + /// @brief Number of threads the listener should use for the test. + size_t num_threads_; + + /// @brief Number of client requests to make during the test. + size_t num_clients_; + + /// @brief Number of requests currently in progress. + size_t num_in_progress_; + + /// @brief Number of requests that have finished. + size_t num_finished_; + + /// @brief Chunk size of requests that need to be processed in parallel. + /// + /// This can either be the number of threads (if the number of requests is + /// greater than the number of threads) or the number of requests (if the + /// number of threads is greater than the number of requests). + size_t chunk_size_; + + /// @brief Mutex used to lock during thread coordination. + std::mutex mutex_; + + /// @brief Condition variable used to coordinate threads. + std::condition_variable cv_; + + /// @brief Number of times client has been paused during the test. + size_t pause_cnt_; + + /// @brief Number of clients that have completed their assignment or + /// failed + size_t clients_done_; + + /// @brief Response Handler passed down to each connection. + TcpTestConnection::ResponseHandler response_handler_; +}; + +/// Verifies the construction, starting, stopping, pausing, resuming, +/// and destruction of MtTcpListener. +TEST_F(MtTcpListenerMgrTest, basics) { + // Make sure multi-threading is off. + MultiThreadingMgr::instance().setMode(false); + IOAddress address(SERVER_ADDRESS); + uint16_t port = SERVER_PORT; + + // Make sure we can create one. + ASSERT_NO_THROW_LOG(mt_listener_mgr_.reset( + new MtTcpListenerMgr( + std::bind(&MtTcpListenerMgrTest::listenerFactory, this, + ph::_1, ph::_2, ph::_3, ph::_4, ph::_5, ph::_6), + address, port))); + + ASSERT_TRUE(mt_listener_mgr_); + + // Verify the getters do what we expect. + EXPECT_EQ(mt_listener_mgr_->getAddress(), address); + EXPECT_EQ(mt_listener_mgr_->getPort(), port); + EXPECT_EQ(mt_listener_mgr_->getThreadPoolSize(), 1); + EXPECT_FALSE(mt_listener_mgr_->getTlsContext()); + + // It should not have an IOService, should not be listening and + // should have no threads. + ASSERT_FALSE(mt_listener_mgr_->getThreadIOService()); + EXPECT_TRUE(mt_listener_mgr_->isStopped()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 0); + + // Verify that we cannot start it when multi-threading is disabled. + ASSERT_FALSE(MultiThreadingMgr::instance().getMode()); + ASSERT_THROW_MSG(mt_listener_mgr_->start(), InvalidOperation, + "MtTcpListenerMgr cannot be started" + " when multi-threading is disabled"); + + // It should still not be listening and have no threads. + EXPECT_TRUE(mt_listener_mgr_->isStopped()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 0); + + // Enable multi-threading. + MultiThreadingMgr::instance().setMode(true); + + // Make sure we can start it and it's listening with 1 thread. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->start()); + ASSERT_TRUE(mt_listener_mgr_->isRunning()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 1); + ASSERT_TRUE(mt_listener_mgr_->getThreadIOService()); + EXPECT_FALSE(mt_listener_mgr_->getThreadIOService()->stopped()); + + // Trying to start it again should fail. + ASSERT_THROW_MSG(mt_listener_mgr_->start(), InvalidOperation, + "MtTcpListenerMgr already started!"); + + // Stop it and verify we're no longer listening. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->stop()); + ASSERT_TRUE(mt_listener_mgr_->isStopped()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 0); + ASSERT_FALSE(mt_listener_mgr_->getThreadIOService()); + + // Make sure we can call stop again without problems. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->stop()); + + // We should be able to restart it. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->start()); + ASSERT_TRUE(mt_listener_mgr_->isRunning()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 1); + ASSERT_TRUE(mt_listener_mgr_->getThreadIOService()); + EXPECT_FALSE(mt_listener_mgr_->getThreadIOService()->stopped()); + + // Destroying it should also stop it. + // If the test timeouts we know it didn't! + ASSERT_NO_THROW_LOG(mt_listener_mgr_.reset()); + + // Verify we can construct with more than one thread. + ASSERT_NO_THROW_LOG(mt_listener_mgr_.reset( + new MtTcpListenerMgr( + std::bind(&MtTcpListenerMgrTest::listenerFactory, this, + ph::_1, ph::_2, ph::_3, ph::_4, ph::_5, ph::_6), + address, port, 4))); + + ASSERT_NO_THROW_LOG(mt_listener_mgr_->start()); + EXPECT_EQ(mt_listener_mgr_->getAddress(), address); + EXPECT_EQ(mt_listener_mgr_->getPort(), port); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 4); + EXPECT_EQ(mt_listener_mgr_->getThreadPoolSize(), 4); + ASSERT_TRUE(mt_listener_mgr_->isRunning()); + ASSERT_TRUE(mt_listener_mgr_->getThreadIOService()); + EXPECT_FALSE(mt_listener_mgr_->getThreadIOService()->stopped()); + + // Verify we can pause it. We should still be listening, threads intact, + // IOService stopped, state set to PAUSED. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->pause()); + ASSERT_TRUE(mt_listener_mgr_->isPaused()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 4); + EXPECT_EQ(mt_listener_mgr_->getThreadPoolSize(), 4); + ASSERT_TRUE(mt_listener_mgr_->getThreadIOService()); + EXPECT_TRUE(mt_listener_mgr_->getThreadIOService()->stopped()); + + // Verify we can resume it. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->resume()); + ASSERT_TRUE(mt_listener_mgr_->isRunning()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 4); + EXPECT_EQ(mt_listener_mgr_->getThreadPoolSize(), 4); + ASSERT_TRUE(mt_listener_mgr_->getThreadIOService()); + EXPECT_FALSE(mt_listener_mgr_->getThreadIOService()->stopped()); + + // Stop it and verify we're no longer listening. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->stop()); + ASSERT_TRUE(mt_listener_mgr_->isStopped()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 0); + EXPECT_EQ(mt_listener_mgr_->getThreadPoolSize(), 4); + ASSERT_FALSE(mt_listener_mgr_->getThreadIOService()); + EXPECT_TRUE(mt_listener_mgr_->isStopped()); +} + +// Now we'll run some permutations of the number of listener threads +// and the number of client requests. + +// One thread, one client. +TEST_F(MtTcpListenerMgrTest, oneByOne) { + size_t num_threads = 1; + size_t num_clients = 1; + threadListenAndRespond(num_threads, num_clients); +} + +// One thread, four clients. +TEST_F(MtTcpListenerMgrTest, oneByFour) { + size_t num_threads = 1; + size_t num_clients = 4; + threadListenAndRespond(num_threads, num_clients); +} + +// Four threads, one clients. +TEST_F(MtTcpListenerMgrTest, fourByOne) { + size_t num_threads = 4; + size_t num_clients = 1; + threadListenAndRespond(num_threads, num_clients); +} + +// Four threads, four clients. +TEST_F(MtTcpListenerMgrTest, fourByFour) { + size_t num_threads = 4; + size_t num_clients = 4; + threadListenAndRespond(num_threads, num_clients); +} + +// Four threads, eight clients. +TEST_F(MtTcpListenerMgrTest, fourByEight) { + size_t num_threads = 4; + size_t num_clients = 8; + threadListenAndRespond(num_threads, num_clients); +} + +// Six threads, eighteen clients. +TEST_F(MtTcpListenerMgrTest, sixByEighteen) { + size_t num_threads = 6; + size_t num_clients = 18; + threadListenAndRespond(num_threads, num_clients); +} + +// Pauses and resumes the listener while it is processing +// requests. +TEST_F(MtTcpListenerMgrTest, pauseAndResume) { + size_t num_threads = 6; + size_t num_clients = 18; + size_t num_pauses = 3; + workPauseAndResume(num_threads, num_clients, num_pauses); +} + +// Check if a TLS listener can be created. +TEST_F(MtTcpListenerMgrTest, tls) { + IOAddress address(SERVER_ADDRESS); + uint16_t port = SERVER_PORT; + TlsContextPtr context; + configServer(context); + + // Make sure we can create the listener. + ASSERT_NO_THROW_LOG( + mt_listener_mgr_.reset(new MtTcpListenerMgr( + std::bind(&MtTcpListenerMgrTest::listenerFactory, + this, + ph::_1, ph::_2, ph::_3, ph::_4, ph::_5, ph::_6), + IOAddress(SERVER_ADDRESS), SERVER_PORT, 1, context)) + ); + + EXPECT_EQ(mt_listener_mgr_->getAddress(), address); + EXPECT_EQ(mt_listener_mgr_->getPort(), port); + EXPECT_EQ(mt_listener_mgr_->getThreadPoolSize(), 1); + EXPECT_EQ(mt_listener_mgr_->getTlsContext(), context); + EXPECT_TRUE(mt_listener_mgr_->isStopped()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 0); + + // Make sure we can start it and it's listening with 1 thread. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->start()); + ASSERT_TRUE(mt_listener_mgr_->isRunning()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 1); + ASSERT_TRUE(mt_listener_mgr_->getThreadIOService()); + EXPECT_FALSE(mt_listener_mgr_->getThreadIOService()->stopped()); + + // Stop it. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->stop()); + ASSERT_TRUE(mt_listener_mgr_->isStopped()); + EXPECT_EQ(mt_listener_mgr_->getThreadCount(), 0); + EXPECT_EQ(mt_listener_mgr_->getThreadPoolSize(), 1); + ASSERT_FALSE(mt_listener_mgr_->getThreadIOService()); + EXPECT_TRUE(mt_listener_mgr_->isStopped()); +} + +/// Verifies that idle timeout can be passed down to the internal listener. +TEST_F(MtTcpListenerMgrTest, idleTimeout) { + // Create an MtTcpListenerMgr. + createMtTcpListenerMgr(1, std::bind(&MtTcpListenerMgrTest::synchronizedCommandHandler, + this, ph::_1)); + // Verify the default timeout value. + EXPECT_EQ(TCP_IDLE_CONNECTION_TIMEOUT, mt_listener_mgr_->getIdleTimeout()); + + // Set a new timeout value. + mt_listener_mgr_->setIdleTimeout(200); + EXPECT_EQ(200, mt_listener_mgr_->getIdleTimeout()); + + // Start the listener, which should instantiate the internal listener. + ASSERT_NO_THROW_LOG(mt_listener_mgr_->start()); + ASSERT_TRUE(mt_listener_mgr_->isRunning()); + + // Verify the internal listener's timeout value. + auto tcp_listener = mt_listener_mgr_->getTcpListener(); + ASSERT_TRUE(tcp_listener); + EXPECT_EQ(200, tcp_listener->getIdleTimeout()); +} + +} // end of anonymous namespace diff --git a/src/lib/tcp/tests/run_unittests.cc b/src/lib/tcp/tests/run_unittests.cc new file mode 100644 index 0000000..55589a6 --- /dev/null +++ b/src/lib/tcp/tests/run_unittests.cc @@ -0,0 +1,20 @@ +// Copyright (C) 2022 Internet Systems Consortium, Inc. ("ISC") +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include +#include + +#include + +int +main(int argc, char* argv[]) { + ::testing::InitGoogleTest(&argc, argv); + isc::log::initLogger(); + + int result = RUN_ALL_TESTS(); + + return (result); +} diff --git a/src/lib/tcp/tests/tcp_listener_unittests.cc b/src/lib/tcp/tests/tcp_listener_unittests.cc new file mode 100644 index 0000000..90be50a --- /dev/null +++ b/src/lib/tcp/tests/tcp_listener_unittests.cc @@ -0,0 +1,603 @@ +// Copyright (C) 2022-2023 Internet Systems Consortium, Inc. ("ISC") +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include +#include +#include +#include +#include + +#include + +#include + +using namespace boost::asio::ip; +using namespace isc::asiolink; +using namespace isc::tcp; + +namespace ph = std::placeholders; + +std::ostream& +operator<<(std::ostream& os, const AuditEntry& entry) { + os << "{ " << entry.connection_id_ << ", " + << (entry.direction_ == AuditEntry::INBOUND ? "I" : "O") << ", " + << entry.data_ << " }"; + return (os); +} + +namespace { + +/// @brief IP address to which service is bound. +const std::string SERVER_ADDRESS = "127.0.0.1"; + +/// @brief IPv6 address to whch service is bound. +const std::string IPV6_SERVER_ADDRESS = "::1"; + +/// @brief Port number to which service is bound. +const unsigned short SERVER_PORT = 18123; + +/// @brief Request Timeout used in most of the tests (ms). +const long REQUEST_TIMEOUT = 10000; + +/// @brief Connection idle timeout used in tests where idle connections +/// are tested (ms). +const long SHORT_REQUEST_TIMEOUT = 200; + +/// @brief Connection idle timeout used in most of the tests (ms). +const long IDLE_TIMEOUT = 10000; + +/// @brief Connection idle timeout used in tests where idle connections +/// are tested (ms). +const long SHORT_IDLE_TIMEOUT = 200; + +/// @brief Test timeout (ms). +const long TEST_TIMEOUT = 10000; + +/// @brief Test fixture class for @ref TcpListener. +class TcpListenerTest : public ::testing::Test { +public: + + /// @brief Constructor. + /// + /// Starts test timer which detects timeouts. + TcpListenerTest() + : io_service_(), test_timer_(io_service_), + run_io_service_timer_(io_service_), + clients_(), clients_done_(0) { + test_timer_.setup(std::bind(&TcpListenerTest::timeoutHandler, this, true), + TEST_TIMEOUT, + IntervalTimer::ONE_SHOT); + } + + /// @brief Destructor. + /// + /// Removes active clients. + virtual ~TcpListenerTest() { + for (auto client : clients_) { + client->close(); + } + } + + /// @brief Create a new client. + /// + /// This method creates TcpTestClient instance and retains it in + /// the clients_ list. + /// @param tls_context TLS context to assign to the client. + TcpTestClientPtr createClient(TlsContextPtr tls_context = TlsContextPtr()) { + TcpTestClientPtr client(new TcpTestClient(io_service_, + std::bind(&TcpListenerTest::clientDone, this), + tls_context)); + clients_.push_back(client); + return (client); + } + + /// @brief Connect to the endpoint and send a request. + /// + /// This method creates TcpTestClient instance and retains it in + /// the clients_ list. + /// + /// @param request String containing the request to be sent. + /// @param tls_context TLS context to assign to the client. + void startRequest(const std::string& request, + TlsContextPtr tls_context = TlsContextPtr()) { + TcpTestClientPtr client = createClient(tls_context); + client->startRequest(request); + } + + /// @brief Connect to the endpoint and send a list of requests. + /// + /// This method creates a TcpTestClient instance and initiates a + /// series of requests. + /// + /// @param request String containing the request to be sent. + /// @param tls_context TLS context to assign to the client. + void startRequests(const std::list& requests, + TlsContextPtr tls_context = TlsContextPtr()) { + TcpTestClientPtr client = createClient(tls_context); + client->startRequests(requests); + } + + /// @brief Callback function invoke upon test timeout. + /// + /// It stops the IO service and reports test timeout. + /// + /// @param fail_on_timeout Specifies if test failure should be reported. + void timeoutHandler(const bool fail_on_timeout) { + if (fail_on_timeout) { + ADD_FAILURE() << "Timeout occurred while running the test!"; + } + io_service_.stop(); + } + + /// @brief Callback function each client invokes when done. + /// + /// It stops the IO service when all clients are done. + /// + /// @param fail_on_timeout Specifies if test failure should be reported. + void clientDone() { + ++clients_done_; + if (clients_done_ >= clients_.size()) { + // They're all done or dead. Stop the service. + io_service_.stop(); + } + } + + /// @brief Runs IO service with optional timeout. + /// + /// @param timeout Optional value specifying for how long the io service + /// should be ran. + void runIOService(long timeout = 0) { + io_service_.get_io_service().reset(); + + if (timeout > 0) { + run_io_service_timer_.setup(std::bind(&TcpListenerTest::timeoutHandler, + this, false), + timeout, + IntervalTimer::ONE_SHOT); + } + io_service_.run(); + io_service_.get_io_service().reset(); + io_service_.poll(); + } + + /// @brief Filter that denies every other connection. + /// + /// @param remote_endpoint_address ip address of the remote end of + /// a connection. + bool connectionFilter(const boost::asio::ip::tcp::endpoint& remote_endpoint) { + static size_t count = 0; + // If the address doesn't match, something hinky is going on, so + // we'll reject them all. If it does match, then cool, it works + // as expected. + if ((count++ % 2) || + (remote_endpoint.address().to_string() != SERVER_ADDRESS)) { + // Reject every other connection; + return (false); + } + + return (true); + } + + /// @brief IO service used in the tests. + IOService io_service_; + + /// @brief Asynchronous timer service to detect timeouts. + IntervalTimer test_timer_; + + /// @brief Asynchronous timer for running IO service for a specified amount + /// of time. + IntervalTimer run_io_service_timer_; + + /// @brief List of client connections. + std::list clients_; + + /// @brief Counts the number of clients that have reported as done. + size_t clients_done_; +}; + +// This test verifies that a TCP connection can be established and used to +// transmit a streamed request and receive a streamed response. +TEST_F(TcpListenerTest, listen) { + const std::string request = "I am done"; + + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + TlsContextPtr(), + TcpListener::IdleTimeout(IDLE_TIMEOUT)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + ASSERT_NO_THROW(startRequest(request)); + ASSERT_NO_THROW(runIOService()); + ASSERT_EQ(1, clients_.size()); + TcpTestClientPtr client = *clients_.begin(); + ASSERT_TRUE(client); + EXPECT_TRUE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + + // Verify the audit trail for the connection. + // Sanity check to make sure we don't have more entries than we expect. + ASSERT_EQ(listener.audit_trail_->entries_.size(), 2); + + // Create the list of expected entries. + std::list expected_entries { + { 1, AuditEntry::INBOUND, "I am done" }, + { 1, AuditEntry::OUTBOUND, "good bye" } + }; + + // Verify the audit trail. + ASSERT_EQ(expected_entries, listener.audit_trail_->getConnectionTrail(1)); + + listener.stop(); + io_service_.poll(); +} + +// This test verifies that a TCP connection can receive a complete +// message that spans multiple socket reads. +TEST_F(TcpListenerTest, splitReads) { + const std::string request = "I am done"; + + // Read at most one byte at a time. + size_t read_max = 1; + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + TlsContextPtr(), + TcpListener::IdleTimeout(IDLE_TIMEOUT), + 0, + read_max); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + ASSERT_NO_THROW(startRequest(request)); + ASSERT_NO_THROW(runIOService()); + + // Fetch the client. + ASSERT_EQ(1, clients_.size()); + TcpTestClientPtr client = *clients_.begin(); + ASSERT_TRUE(client); + EXPECT_TRUE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + + listener.stop(); + io_service_.poll(); +} + +// This test verifies that a TCP connection can be established and used to +// transmit a streamed request and receive a streamed response. +TEST_F(TcpListenerTest, idleTimeoutTest) { + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + TlsContextPtr(), + TcpListener::IdleTimeout(SHORT_IDLE_TIMEOUT)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + // Start a client with an empty request. Empty requests tell the client to read + // without sending anything and expect the read to fail when the listener idle + // times out the socket. + ASSERT_NO_THROW(startRequest("")); + + // Run until idle timer expires. + ASSERT_NO_THROW(runIOService()); + + ASSERT_EQ(1, clients_.size()); + TcpTestClientPtr client = *clients_.begin(); + EXPECT_FALSE(client->receiveDone()); + EXPECT_TRUE(client->expectedEof()); + + listener.stop(); + io_service_.poll(); +} + +TEST_F(TcpListenerTest, multipleClientsListen) { + const std::string request = "I am done"; + + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + TlsContextPtr(), + TcpListener::IdleTimeout(IDLE_TIMEOUT)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + size_t num_clients = 5; + for (auto i = 0; i < num_clients; ++i) { + ASSERT_NO_THROW(startRequest(request)); + } + + ASSERT_NO_THROW(runIOService()); + ASSERT_EQ(num_clients, clients_.size()); + + size_t connection_id = 1; + for (auto client : clients_) { + EXPECT_TRUE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + // Create the list of expected entries. + std::list expected_entries { + { connection_id, AuditEntry::INBOUND, "I am done" }, + { connection_id, AuditEntry::OUTBOUND, "good bye" } + }; + + // Fetch the entries for this connection. + auto entries = listener.audit_trail_->getConnectionTrail(connection_id); + ASSERT_EQ(expected_entries, entries); + ++connection_id; + } + + listener.stop(); + io_service_.poll(); +} + +// Verify that the listener handles multiple requests for multiple +// clients. +TEST_F(TcpListenerTest, multipleRequetsPerClients) { + std::listrequests{ "one", "two", "three", "I am done"}; + + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + TlsContextPtr(), + TcpListener::IdleTimeout(IDLE_TIMEOUT)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + size_t num_clients = 5; + for (auto i = 0; i < num_clients; ++i) { + ASSERT_NO_THROW(startRequests(requests)); + } + + ASSERT_NO_THROW(runIOService()); + ASSERT_EQ(num_clients, clients_.size()); + + std::listexpected_responses{ "echo one", "echo two", + "echo three", "good bye"}; + size_t connection_id = 1; + for (auto client : clients_) { + EXPECT_TRUE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + EXPECT_EQ(expected_responses, client->getResponses()); + + // Verify the connection's audit trail. + // Create the list of expected entries. + std::list expected_entries { + { connection_id, AuditEntry::INBOUND, "one" }, + { connection_id, AuditEntry::OUTBOUND, "echo one" }, + { connection_id, AuditEntry::INBOUND, "two" }, + { connection_id, AuditEntry::OUTBOUND, "echo two" }, + { connection_id, AuditEntry::INBOUND, "three" }, + { connection_id, AuditEntry::OUTBOUND, "echo three" }, + { connection_id, AuditEntry::INBOUND, "I am done" }, + { connection_id, AuditEntry::OUTBOUND, "good bye" } + }; + + // Fetch the entries for this connection. + auto entries = listener.audit_trail_->getConnectionTrail(connection_id); + ASSERT_EQ(expected_entries, entries); + ++connection_id; + } + + listener.stop(); + io_service_.poll(); +} + +// Verify that connection filtering can eliminate specific connections. +TEST_F(TcpListenerTest, filterClientsTest) { + const std::string request = "I am done"; + + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + TlsContextPtr(), + TcpListener::IdleTimeout(IDLE_TIMEOUT), + std::bind(&TcpListenerTest::connectionFilter, this, ph::_1)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + size_t num_clients = 5; + for (auto i = 0; i < num_clients; ++i) { + // Every other client sends nothing (i.e. waits for EOF) as + // we expect the filter to reject them. + if (i % 2 == 0) { + ASSERT_NO_THROW(startRequest("I am done")); + } else { + ASSERT_NO_THROW(startRequest("")); + } + } + + ASSERT_NO_THROW(runIOService()); + ASSERT_EQ(num_clients, clients_.size()); + + size_t i = 0; + for (auto client : clients_) { + if (i % 2 == 0) { + // These clients should have been accepted and received responses. + EXPECT_TRUE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + + // Now verify the AuditTrail. + // Create the list of expected entries. + std::list expected_entries { + { i+1, AuditEntry::INBOUND, "I am done" }, + { i+1, AuditEntry::OUTBOUND, "good bye" } + }; + + auto entries = listener.audit_trail_->getConnectionTrail(i+1); + ASSERT_EQ(expected_entries, entries); + + } else { + // These clients should have been rejected and gotten EOF'd. + EXPECT_FALSE(client->receiveDone()); + EXPECT_TRUE(client->expectedEof()); + + // Verify connection recorded no audit entries. + auto entries = listener.audit_trail_->getConnectionTrail(i+1); + ASSERT_EQ(entries.size(), 0); + } + + ++i; + } + + listener.stop(); + io_service_.poll(); +} + +// Exercises TcpStreamRequest::postBuffer() through various +// data permutations. +TEST(TcpStreamRequst, postBufferTest) { + // Struct describing a test scenario. + struct Scenario { + const std::string desc_; + // List of input buffers to submit to post. + std::list> input_buffers_; + // List of expected "request" strings conveyed. + std::list expected_strings_; + }; + + std::list scenarios{ + { + "1. Two complete messages in their own buffers", + { + { 0x00, 0x04, 0x31, 0x32, 0x33, 0x34 }, + { 0x00, 0x03, 0x35, 0x36, 0x37 }, + }, + { "1234", "567" } + }, + { + "2. Three messages: first two are in the same buffer", + { + { 0x00, 0x04, 0x31, 0x32, 0x33, 0x34, 0x00, 0x02, 0x35, 0x36 }, + { 0x00, 0x03, 0x37, 0x38, 0x39 }, + }, + { "1234", "56", "789" } + }, + { + "3. One message across three buffers", + { + { 0x00, 0x09, 0x31, 0x32, 0x33 }, + { 0x34, 0x35, 0x36, 0x37 }, + { 0x38, 0x39 }, + }, + { "123456789" } + + }, + { + "4. One message, length and data split across buffers", + { + { 0x00 }, + { 0x09, 0x31, 0x32, 0x33 }, + { 0x34, 0x35, 0x36, 0x37 }, + { 0x38, 0x39 }, + }, + { "123456789" } + } + }; + + // Extend the second case with 3 messages to all possible splits + // into one to four chunks. + std::string desc = "N. Three messages"; + std::vector buffer = { + 0x00, 0x04, 0x31, 0x32, 0x33, 0x34, + 0x00, 0x02, 0x35, 0x36, + 0x00, 0x03, 0x37, 0x38, 0x39 + }; + std::list expected = { "1234", "56", "789" }; + // No cut. + scenarios.push_back(Scenario{ desc, { buffer }, expected }); + // One cut. + for (size_t i = 1; i < buffer.size() - 1; ++i) { + std::ostringstream sdesc; + sdesc << desc << " cut at " << i; + std::list> buffers; + buffers.push_back(std::vector(buffer.cbegin(), + buffer.cbegin() + i)); + buffers.push_back(std::vector(buffer.cbegin() + i, + buffer.cend())); + scenarios.push_back(Scenario{ sdesc.str(), buffers, expected }); + } + // Two cuts. + for (size_t i = 1; i < buffer.size() - 2; ++i) { + for (size_t j = i + 1; j < buffer.size() - 1; ++j) { + std::ostringstream sdesc; + sdesc << desc << " cut at " << i << " and " << j; + std::list> buffers; + buffers.push_back(std::vector(buffer.cbegin(), + buffer.cbegin() + i)); + buffers.push_back(std::vector(buffer.cbegin() + i, + buffer.cbegin() + j)); + buffers.push_back(std::vector(buffer.cbegin() + j, + buffer.cend())); + scenarios.push_back(Scenario{ sdesc.str(), buffers, expected }); + } + } + // Three cuts. + for (size_t i = 1; i < buffer.size() - 3; ++i) { + for (size_t j = i + 1; j < buffer.size() - 2; ++j) { + for (size_t k = j + 1; k < buffer.size() - 1; ++k) { + std::ostringstream sdesc; + sdesc << desc << " cut at " << i << ", " << j << " and " << k; + std::list> buffers; + buffers.push_back(std::vector(buffer.cbegin(), + buffer.cbegin() + i)); + buffers.push_back(std::vector(buffer.cbegin() + i, + buffer.cbegin() + j)); + buffers.push_back(std::vector(buffer.cbegin() + j, + buffer.cbegin() + k)); + buffers.push_back(std::vector(buffer.cbegin() + k, + buffer.cend())); + scenarios.push_back(Scenario{ sdesc.str(), buffers, expected }); + } + } + } + + for (auto scenario : scenarios ) { + SCOPED_TRACE(scenario.desc_); + std::list requests; + TcpStreamRequestPtr request; + for (auto input_buf : scenario.input_buffers_) { + // Copy the input buffer. + std::vector buf = input_buf; + + // While there is data left to use, use it. + while (buf.size()) { + // If we need a new request make one. + if (!request) { + request.reset(new TcpStreamRequest()); + } + + size_t bytes_used = request->postBuffer(buf.data(), + buf.size()); + if (!request->needData()) { + // Request is complete, save it. + requests.push_back(request); + request.reset(); + } + + // Consume bytes used. + if (bytes_used) { + buf.erase(buf.begin(), buf.begin() + bytes_used); + } + } + } + + ASSERT_EQ(requests.size(), scenario.expected_strings_.size()); + auto exp_string = scenario.expected_strings_.begin(); + for (auto recvd_request : requests) { + ASSERT_NO_THROW(recvd_request->unpack()); + EXPECT_EQ(*exp_string++, recvd_request->getRequestString()); + } + } +} + +} diff --git a/src/lib/tcp/tests/tcp_test_client.h b/src/lib/tcp/tests/tcp_test_client.h new file mode 100644 index 0000000..2e1b30b --- /dev/null +++ b/src/lib/tcp/tests/tcp_test_client.h @@ -0,0 +1,437 @@ +// Copyright (C) 2022-2023 Internet Systems Consortium, Inc. ("ISC") +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef TCP_TEST_CLIENT_H +#define TCP_TEST_CLIENT_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/// @brief Entity which can connect to the TCP server endpoint with or +/// or without TLS. +class TcpTestClient : public boost::noncopyable { + +private: + /// @brief Type of the function implementing a callback invoked by the + /// @c SocketCallback functor. + typedef std::function + SocketCallbackFunction; + + /// @brief Functor associated with the socket object. + /// + /// This functor calls a callback function specified in the constructor. + class SocketCallback { + public: + + /// @brief Constructor. + /// + /// @param socket_callback Callback to be invoked by the functor upon + /// an event associated with the socket. + SocketCallback(SocketCallbackFunction socket_callback) + : callback_(socket_callback) { + } + + /// @brief Operator called when event associated with a socket occurs. + /// + /// This operator returns immediately when received error code is + /// @c boost::system::error_code is equal to + /// @c boost::asio::error::operation_aborted, i.e. the callback is not + /// invoked. + /// + /// @param ec Error code. + /// @param length Data length. + void operator()(boost::system::error_code ec, size_t length = 0) { + if (ec.value() == boost::asio::error::operation_aborted) { + return; + } + + callback_(ec, length); + } + + private: + /// @brief Supplied callback. + SocketCallbackFunction callback_; + }; + +public: + + /// @brief Constructor. + /// + /// This constructor creates new socket instance. It doesn't connect. Call + /// start() to connect to the server. + /// + /// @param io_service IO service to be stopped on error or completion. + /// @param done_callback Function cient should invoke when it has finished + /// all its requests or failed. + /// @param tls_context + /// @param server_address string containing the IP address of the server. + /// @param port port number of the server. + explicit TcpTestClient(isc::asiolink::IOService& io_service, + std::function done_callback, + isc::asiolink::TlsContextPtr tls_context = + isc::asiolink::TlsContextPtr(), + const std::string& server_address = "127.0.0.1", + uint16_t port = 18123) + : io_service_(io_service.get_io_service()), + tls_context_(tls_context), + tcp_socket_(), tls_socket_(), + done_callback_(done_callback), + server_address_(server_address), server_port_(port), + buf_(), response_(), + receive_done_(false), expected_eof_(false), handshake_failed_(false) { + if (!tls_context_) { + tcp_socket_.reset(new isc::asiolink::TCPSocket(io_service)); + } else { + tls_socket_.reset(new isc::asiolink::TLSSocket(io_service, + tls_context)); + } + } + + bool useTls() { + return (!!tls_context_); + } + + /// @brief Destructor. + /// + /// Closes the underlying socket if it is open. + virtual ~TcpTestClient() { + close(); + } + + /// @brief Connect to the listener and initiate request processing. + /// + /// Upon successful connection, carry out the TLS handshake. If the handshake + /// completes successful start sending requests. + void start() { + isc::asiolink::TCPEndpoint endpoint(boost::asio::ip::address::from_string(server_address_), server_port_); + SocketCallback socket_cb( + [this](boost::system::error_code ec, size_t /*length */) { + receive_done_ = false; + expected_eof_ = false; + handshake_failed_ = false; + if (ec) { + // One would expect that open wouldn't return + // EINPROGRESS error code, but simply wait for the connection + // to get established before the handler is invoked. It turns out, + // however, that on some OSes the connect handler may receive this + // error code which doesn't necessarily indicate a problem. + // Making an attempt to write and read from this socket will + // typically succeed. So, we ignore this error. + if (ec.value() != boost::asio::error::in_progress) { + ADD_FAILURE() << "error occurred while connecting: " + << ec.message(); + done_callback_(); + } + } + + if (useTls()) { + SocketCallback socket_cb( + [this](boost::system::error_code ec, size_t /*length */) { + if (ec) { + handshake_failed_ = true; + done_callback_(); + } else { + sendNextRequest(); + } + }); + + tls_socket_->handshake(socket_cb); + } else { + sendNextRequest(); + } + }); + + if (useTls()) { + tls_socket_->open(&endpoint, socket_cb); + } else { + tcp_socket_->open(&endpoint, socket_cb); + } + } + + /// @brief Send request specified in textual format. + /// + /// @param request request in the textual format. + void startRequest(const std::string& request) { + requests_to_send_.push_back(request); + start(); + } + + /// @brief Send request specified in textual format. + /// + /// @param request request in the textual format. + void startRequests(const std::list& requests) { + requests_to_send_ = requests; + start(); + } + + /// @brief Sends the next request from the list of requests to send. + void sendNextRequest() { + // If there are any requests left to send, send them. + if (!requests_to_send_.empty()) { + std::string request = requests_to_send_.front(); + requests_to_send_.pop_front(); + if (request.empty()) { + waitForEof(); + } else { + sendRequest(request); + } + } + } + + /// @brief Send a stream request. + /// + /// @param request request data to send textual format. + /// @param send_length number of bytes to send. If not zero, can be used + /// to truncate the amount of data sent. + void sendRequest(const std::string& request, const size_t send_length = 0) { + // Prepend the length of the request. + uint16_t size = static_cast(request.size()); + isc::tcp::WireData wire_request; + if (!request.empty()) { + wire_request.push_back(static_cast((size & 0xff00U) >> 8)); + wire_request.push_back(static_cast(size & 0x00ffU)); + wire_request.insert(wire_request.end(), request.begin(), request.end()); + } + + sendPartialRequest(wire_request, send_length); + } + + /// @brief Wait for a server to close the connection. + void waitForEof() { + stream_response_.reset(new isc::tcp::TcpStreamRequest()); + receivePartialResponse(true); + } + + /// @brief Send part of the request. + /// + /// @param request part of the request to be sent. + /// @param send_length number of bytes to send. If not zero, can be used + /// to truncate the amount of data sent. + void sendPartialRequest(isc::tcp::WireData& wire_request, size_t send_length = 0) { + if (!send_length) { + send_length = wire_request.size(); + } else { + ASSERT_LE(send_length, wire_request.size()) + << "broken test, send_length exceeds wire size"; + } + + SocketCallback socket_cb( + [this, wire_request](boost::system::error_code ec, size_t bytes_transferred) mutable { + if (ec) { + if (ec.value() == boost::asio::error::operation_aborted) { + return; + + } else if ((ec.value() == boost::asio::error::try_again) || + (ec.value() == boost::asio::error::would_block)) { + // If we should try again make sure there is no garbage in the + // bytes_transferred. + bytes_transferred = 0; + } else { + ADD_FAILURE() << "error occurred while connecting: " + << ec.message(); + done_callback_(); + return; + } + } + + // Remove the part of the request which has been sent. + if (bytes_transferred > 0 && (wire_request.size() <= bytes_transferred)) { + wire_request.erase(wire_request.begin(), + (wire_request.begin() + bytes_transferred)); + } + + // Continue sending request data if there are still some data to be + // sent. + if (!wire_request.empty()) { + sendPartialRequest(wire_request); + } else { + // Request has been sent. Start receiving response. + receivePartialResponse(); + } + }); + + if (useTls()) { + tls_socket_->asyncSend(static_cast(wire_request.data()), + send_length, socket_cb); + } else { + tcp_socket_->asyncSend(static_cast(wire_request.data()), + send_length, socket_cb); + } + } + + /// @brief Receive response from the server. + void receivePartialResponse(bool expect_eof = false) { + SocketCallback socket_cb( + [this, expect_eof](const boost::system::error_code& ec, + std::size_t bytes_transferred) { + if (!stream_response_) { + stream_response_.reset(new isc::tcp::TcpStreamRequest()); + } + + if (ec) { + // IO service stopped so simply return. + if (ec.value() == boost::asio::error::operation_aborted) { + return; + } else if ((ec.value() == boost::asio::error::try_again) || + (ec.value() == boost::asio::error::would_block)) { + // If we should try again, make sure that there is no garbage + // in the bytes_transferred. + bytes_transferred = 0; + } else if (expect_eof) { + expected_eof_ = true; + done_callback_(); + return; + } else { + // Error occurred, bail... + ADD_FAILURE() << "client: " << this + << " error occurred while receiving TCP" + << " response from the server: " << ec.message(); + done_callback_(); + return; + } + } + + // Post received data to the current response. + if (bytes_transferred > 0) { + stream_response_->postBuffer(buf_.data(), bytes_transferred); + } + + if (stream_response_->needData()) { + // Response is incomplete, keep reading. + receivePartialResponse(); + } else { + // Response is complete, process it. + responseReceived(); + } + }); + + isc::asiolink::TCPEndpoint from; + if (useTls()) { + tls_socket_->asyncReceive(static_cast(buf_.data()), buf_.size(), 0, + &from, socket_cb); + } else { + tcp_socket_->asyncReceive(static_cast(buf_.data()), buf_.size(), 0, + &from, socket_cb); + } + } + + /// @brief Process a completed response received from the server. + virtual void responseReceived() { + /// Unpack wire data into a string. + ASSERT_NO_THROW(stream_response_->unpack()); + std::string response = stream_response_->getRequestString(); + responses_received_.push_back(response); + + // Quit if server tells us "good bye". + if (response.find("good bye", 0) != std::string::npos) { + receive_done_ = true; + done_callback_(); + return; + } + + // Clear out for the next one. + stream_response_.reset(); + sendNextRequest(); + } + + /// @brief Close connection. + void close() { + if (useTls()) { + tls_socket_->close(); + } else { + tcp_socket_->close(); + } + } + + /// @brief Returns true if the receive completed without error. + /// + /// @return True if the receive completed successfully, false + /// otherwise. + bool receiveDone() { + return (receive_done_); + } + + /// @brief Returns true if the receive ended with expected EOF + /// + /// @return True if the receive ended with EOF, false otherwise + bool expectedEof() { + return (expected_eof_); + } + + /// @brief Returns the list of received responses. + /// + /// @return list of string responses. + const std::list& getResponses() { + return (responses_received_); + } + + bool handshakeFailed() { + return(handshake_failed_); + } + +private: + + /// @brief Holds reference to the IO service. + boost::asio::io_service& io_service_; + + /// @brief TLS context. + isc::asiolink::TlsContextPtr tls_context_; + + /// @brief TCP socket used by this connection. + std::unique_ptr > tcp_socket_; + + /// @brief TLS socket used by this connection. + std::unique_ptr > tls_socket_; + + /// @brief Callback to invoke when the client has finished its work or + /// failed. + std::function done_callback_; + + /// @brief IP address of the server. + std::string server_address_; + + /// @brief IP port of the server. + uint16_t server_port_; + + /// @brief Buffer into which response is written. + std::array buf_; + + /// @brief Response in the textual format. + std::string response_; + + /// @brief Set to true when the receive has completed successfully. + bool receive_done_; + + /// @brief Set to true when the receive ended in EOF as expected. In other + /// words, the server closed the connection while we were reading as we + /// expected it to do. + bool expected_eof_; + + /// @brief Set to true if the TLS handshake failed. + bool handshake_failed_; + + /// @brief Pointer to the server response currently being received. + isc::tcp::TcpStreamRequestPtr stream_response_; + + /// @brief List of string requests to send. + std::list requests_to_send_; + + /// @brief List of string responses received. + std::list responses_received_; +}; + +/// @brief Pointer to the TcpTestClient. +typedef boost::shared_ptr TcpTestClientPtr; + +#endif diff --git a/src/lib/tcp/tests/tcp_test_listener.h b/src/lib/tcp/tests/tcp_test_listener.h new file mode 100644 index 0000000..5522484 --- /dev/null +++ b/src/lib/tcp/tests/tcp_test_listener.h @@ -0,0 +1,315 @@ +// Copyright (C) 2022 Internet Systems Consortium, Inc. ("ISC") +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +#ifndef TCP_TEST_LISTENER_H +#define TCP_TEST_LISTENER_H + +#include +#include +#include +#include +#include +#include + +#include + +#include + +using namespace boost::asio::ip; +using namespace isc::asiolink; +using namespace isc::tcp; + +/// @brief Describes stream message sent over a connection. +class AuditEntry { +public: + enum Direction { + INBOUND, // data received + OUTBOUND // data sent + }; + + /// @brief Constructor + /// + /// @param connection_id Id of the client to whom the entry pertains + /// @param direction INBOUND for data received, OUTBOUND for data sent + /// @param data string form of the data involved + AuditEntry(size_t connection_id, + const AuditEntry::Direction& direction, + const std::string& data) + : connection_id_(connection_id), direction_(direction), data_(data) { + } + + /// @brief Equality operator. + /// + /// @param other value to be compared. + bool operator==(const AuditEntry& other) const { + return ((connection_id_ == other.connection_id_) && + (direction_ == other.direction_) && + (data_ == other.data_)); + } + + /// @brief Unique client identifier. + size_t connection_id_; + + /// @brief Indicates which direction the data traveled + Direction direction_; + + /// @brief Contains the data sent or received. + std::string data_; +}; + +std::ostream& +operator<<(std::ostream& os, const AuditEntry& entry); + +/// @brief Contains the data receipt/transmission history for an arbitrary +/// number of connections. +class AuditTrail { +public: + /// @brief Adds an entry to the audit trail. + /// + /// @param connection_id Id of the client to whom the entry pertains + /// @param direction INBOUND for data received, OUTBOUND for data sent + /// @param data string form of the data involved + void addEntry(size_t connection_id, + const AuditEntry::Direction& direction, + const std::string& data) { + std::unique_lock lck(mutex_); + entries_.push_back(AuditEntry(connection_id, direction, data)); + } + + /// @brief Returns a list of AuditEntry(s) for a given connection. + /// + /// @param connection_id Id of the desired connection + /// @return A list of entries for the connection or an empty list if none are found. + std::list getConnectionTrail(size_t connection_id) { + std::unique_lock lck(mutex_); + std::list conn_entries; + for (auto entry : entries_) { + if (entry.connection_id_ == connection_id) { + conn_entries.push_back(entry); + } + } + + return (conn_entries); + } + + /// @brief Dumps the audit trail as a string. + std::string dump() { + std::unique_lock lck(mutex_); + std::stringstream ss; + for (auto entry : entries_) { + ss << entry << std::endl; + } + + return (ss.str()); + } + + /// @brief Contains the audit entries. + std::list entries_; + + /// @brief Mutex used to lock during access. + std::mutex mutex_; +}; + +/// @brief Defines a pointer to an AuditTrail +typedef boost::shared_ptr AuditTrailPtr; + +/// @brief Derivation of TcpConnection used for testing. +class TcpTestConnection : public TcpConnection { +public: + typedef std::function ResponseHandler; + + /// @brief Constructor + TcpTestConnection(IOService& io_service, + const TcpConnectionAcceptorPtr& acceptor, + const TlsContextPtr& tls_context, + TcpConnectionPool& connection_pool, + const TcpConnectionAcceptorCallback& acceptor_callback, + const TcpConnectionFilterCallback& filter_callback, + const long idle_timeout, + size_t connection_id, + AuditTrailPtr audit_trail, + ResponseHandler response_handler) + : TcpConnection(io_service, acceptor, tls_context, connection_pool, + acceptor_callback, filter_callback, idle_timeout), + connection_id_(connection_id), audit_trail_(audit_trail), + response_handler_(response_handler) { + } + + /// @brief Creates a new empty request ready to receive data. + virtual TcpRequestPtr createRequest() { + return (TcpStreamRequestPtr(new TcpStreamRequest())); + } + + /// @brief Processes a completely received request. + /// + /// Adds the request to the audit trail, then forms and sends a response. + /// If the request is "I am done", the response is "good bye" which should + /// instruct the client to disconnect. + /// + /// @param request Request to process. + virtual void requestReceived(TcpRequestPtr request) { + TcpStreamRequestPtr stream_req = boost::dynamic_pointer_cast(request); + if (!stream_req) { + isc_throw(isc::Unexpected, "request not a TcpStreamRequest"); + } + + // Unpack the request and add it to the audit trail. + stream_req->unpack(); + auto request_str = stream_req->getRequestString(); + audit_trail_->addEntry(connection_id_, AuditEntry::INBOUND, request_str); + + // Create the response. + std::string response_str; + + // If there's a response handler, use it + if (response_handler_) { + response_str = response_handler_(request_str); + } else { + std::ostringstream os; + if (request_str.find("I am done", 0) != std::string::npos) { + os << "good bye"; + } else { + os << "echo " << request_str; + } + + response_str = os.str(); + } + + // Ship the response if it's not empty. + TcpStreamResponsePtr response; + if (!response_str.empty()) { + response.reset(new TcpStreamResponse()); + response->setResponseData(response_str); + response->pack(); + asyncSendResponse(response); + } + } + + /// @brief Processes a response once it has been sent. + /// + /// Adds the response to the audit trail and returns true, signifying + /// that the connection should start the idle timer. + /// + /// @param response Response that was sent to the remote endpoint. + virtual bool responseSent(TcpResponsePtr response) { + TcpStreamResponsePtr resp = boost::dynamic_pointer_cast(response); + if (!resp) { + isc_throw(isc::Unexpected, "resp not a TcpStreamResponse"); + } + + audit_trail_->addEntry(connection_id_, AuditEntry::OUTBOUND, resp->getResponseString()); + return (true); + } + + /// @brief Set the response handler + /// + /// Sets the response handler invoked by requestReceived. + /// + /// @param response_handler Handler function to invoke + void setResponseHandler(ResponseHandler response_handler) { + response_handler_ = response_handler; + }; + +private: + /// @brief Id of this connection. + size_t connection_id_; + + /// @brief Provides request/response history. + AuditTrailPtr audit_trail_; + + /// @brief Reponse handler to pass into each connection. + ResponseHandler response_handler_; +}; + +/// @brief Defines a shared pointer to a TcpTestConnection. +typedef boost::shared_ptr TcpTestConnectionPtr; + +/// @brief Implementation of the TCPListener used in tests. +/// +/// Implements simple stream in/out listener. +class TcpTestListener : public TcpListener { +public: + /// @brief Constructor + TcpTestListener(IOService& io_service, + const IOAddress& server_address, + const unsigned short server_port, + const TlsContextPtr& tls_context, + const IdleTimeout& idle_timeout, + const TcpConnectionFilterCallback& filter_callback = 0, + const size_t read_max = 32 * 1024) + : TcpListener(io_service, server_address, server_port, + tls_context, idle_timeout, filter_callback), + read_max_(read_max), next_connection_id_(0), + audit_trail_(new AuditTrail()) { + } + +protected: + /// @brief Creates an instance of the @c TcpConnection. + /// + /// @param callback Callback invoked when new connection is accepted. + /// @param connection_filter Callback invoked during connection acceptance + /// that can allow or deny connections based on the remote endpoint. + /// @return Pointer to the created connection. + virtual TcpConnectionPtr createConnection( + const TcpConnectionAcceptorCallback& acceptor_callback, + const TcpConnectionFilterCallback& connection_filter) { + return(createTestConnection(acceptor_callback, connection_filter, response_handler_)); + } + + /// @brief Creates an instance of the @c TcpTestConnection. + /// + /// @param acceptor_callback Callback invoked when new connection is accepted. + /// @param connection_filter Callback invoked during connection acceptance + /// that can allow or deny connections based on the remote endpoint. + /// @param callback invoked by requestReceived() to build a response + /// + /// @return Pointer to the created connection. + virtual TcpTestConnectionPtr createTestConnection( + const TcpConnectionAcceptorCallback& acceptor_callback, + const TcpConnectionFilterCallback& connection_filter, + TcpTestConnection::ResponseHandler response_handler) { + TcpTestConnectionPtr conn(new TcpTestConnection(io_service_, + acceptor_, + tls_context_, + connections_, + acceptor_callback, + connection_filter, + idle_timeout_, + ++next_connection_id_, + audit_trail_, + response_handler)); + conn->setReadMax(read_max_); + return (conn); + } + + /// @brief Maximum size of a single socket read + size_t read_max_; + + /// @brief Id to use for the next connection. + size_t next_connection_id_; + + /// @brief Callback connection invokes in requestReceived to construct a response. + TcpTestConnection::ResponseHandler response_handler_; + +public: + + /// @brief Set the response handler + /// + /// Sets the response handler invoked by requestReceived. + /// + /// @param response_handler Handler function to invoke + void setResponseHandler(TcpTestConnection::ResponseHandler response_handler) { + response_handler_ = response_handler; + }; + + + /// @brief Tracks the input/output history of all connections. + AuditTrailPtr audit_trail_; +}; + +/// @brief Defines a pointer to a TcpTestListener. +typedef boost::shared_ptr TcpTestListenerPtr; + +#endif // TCP_TEST_LISTENER_H diff --git a/src/lib/tcp/tests/tls_listener_unittests.cc b/src/lib/tcp/tests/tls_listener_unittests.cc new file mode 100644 index 0000000..f628680 --- /dev/null +++ b/src/lib/tcp/tests/tls_listener_unittests.cc @@ -0,0 +1,498 @@ +// Copyright (C) 2023 Internet Systems Consortium, Inc. ("ISC") +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +using namespace boost::asio::ip; +using namespace isc::asiolink; +using namespace isc::asiolink::test; +using namespace isc::tcp; + +namespace ph = std::placeholders; + +namespace { + +/// @brief IP address to which service is bound. +const std::string SERVER_ADDRESS = "127.0.0.1"; + +/// @brief IPv6 address to whch service is bound. +const std::string IPV6_SERVER_ADDRESS = "::1"; + +/// @brief Port number to which service is bound. +const unsigned short SERVER_PORT = 18123; + +/// @brief Request Timeout used in most of the tests (ms). +const long REQUEST_TIMEOUT = 10000; + +/// @brief Connection idle timeout used in tests where idle connections +/// are tested (ms). +const long SHORT_REQUEST_TIMEOUT = 200; + +/// @brief Connection idle timeout used in most of the tests (ms). +const long IDLE_TIMEOUT = 10000; + +/// @brief Connection idle timeout used in tests where idle connections +/// are tested (ms). +const long SHORT_IDLE_TIMEOUT = 200; + +/// @brief Test timeout (ms). +const long TEST_TIMEOUT = 10000; + +/// @brief Test fixture class for @ref TcpListener that uses TLS. +class TlsListenerTest : public ::testing::Test { +public: + + /// @brief Constructor. + /// + /// Starts test timer which detects timeouts. + TlsListenerTest() + : io_service_(), test_timer_(io_service_), + run_io_service_timer_(io_service_), + clients_(), clients_done_(0) { + test_timer_.setup(std::bind(&TlsListenerTest::timeoutHandler, this, true), + TEST_TIMEOUT, + IntervalTimer::ONE_SHOT); + } + + /// @brief Destructor. + /// + /// Removes active clients. + virtual ~TlsListenerTest() { + for (auto client : clients_) { + client->close(); + } + } + + /// @brief Fetch the server TLS context. + TlsContextPtr serverContext() { + TlsContextPtr tls_context; + configServer(tls_context); + return(tls_context); + } + + /// @brief Fetch a client TLS context that works with the server context. + TlsContextPtr clientContext() { + TlsContextPtr tls_context; + configClient(tls_context); + return(tls_context); + } + + /// @brief Create a new client. + /// + /// This method creates TcpTestClient instance and retains it in + /// the clients_ list. + /// @param tls_context TLS context to assign to the client. + TcpTestClientPtr createClient(TlsContextPtr tls_context) { + TcpTestClientPtr client(new TcpTestClient(io_service_, + std::bind(&TlsListenerTest::clientDone, this), + tls_context)); + clients_.push_back(client); + return (client); + } + + /// @brief Connect to the endpoint and send a request. + /// + /// This method creates TcpTestClient instance and retains it in + /// the clients_ list. + /// + /// @param request String containing the request to be sent. + /// @param tls_context TLS context to assign to the client. + void startRequest(const std::string& request, TlsContextPtr tls_context) { + ASSERT_TRUE(tls_context); + TcpTestClientPtr client = createClient(tls_context); + client->startRequest(request); + } + + /// @brief Connect to the endpoint and send a list of requests. + /// + /// This method creates a TcpTestClient instance and initiates a + /// series of requests. + /// + /// @param request String containing the request to be sent. + /// @param tls_context TLS context to assign to the client. + void startRequests(const std::list& requests, + TlsContextPtr tls_context) { + ASSERT_TRUE(tls_context); + TcpTestClientPtr client = createClient(tls_context); + client->startRequests(requests); + } + + /// @brief Callback function invoke upon test timeout. + /// + /// It stops the IO service and reports test timeout. + /// + /// @param fail_on_timeout Specifies if test failure should be reported. + void timeoutHandler(const bool fail_on_timeout) { + if (fail_on_timeout) { + ADD_FAILURE() << "Timeout occurred while running the test!"; + } + io_service_.stop(); + } + + /// @brief Callback function each client invokes when done. + /// + /// It stops the IO service when all clients are done. + /// + /// @param fail_on_timeout Specifies if test failure should be reported. + void clientDone() { + ++clients_done_; + if (clients_done_ >= clients_.size()) { + // They're all done or dead. Stop the service. + io_service_.stop(); + } + } + + /// @brief Runs IO service with optional timeout. + /// + /// @param timeout Optional value specifying for how long the io service + /// should be ran. + void runIOService(long timeout = 0) { + io_service_.get_io_service().reset(); + + if (timeout > 0) { + run_io_service_timer_.setup(std::bind(&TlsListenerTest::timeoutHandler, + this, false), + timeout, + IntervalTimer::ONE_SHOT); + } + io_service_.run(); + io_service_.get_io_service().reset(); + io_service_.poll(); + } + + /// @brief Filter that denies every other connection. + /// + /// @param remote_endpoint_address ip address of the remote end of + /// a connection. + bool connectionFilter(const boost::asio::ip::tcp::endpoint& remote_endpoint) { + static size_t count = 0; + // If the address doesn't match, something hinky is going on, so + // we'll reject them all. If it does match, then cool, it works + // as expected. + if ((count++ % 2) || + (remote_endpoint.address().to_string() != SERVER_ADDRESS)) { + // Reject every other connection; + return (false); + } + + return (true); + } + + /// @brief IO service used in the tests. + IOService io_service_; + + /// @brief Asynchronous timer service to detect timeouts. + IntervalTimer test_timer_; + + /// @brief Asynchronous timer for running IO service for a specified amount + /// of time. + IntervalTimer run_io_service_timer_; + + /// @brief List of client connections. + std::list clients_; + + /// @brief Counts the number of clients that have reported as done. + size_t clients_done_; +}; + +// This test verifies that a TLS connection can be established with a client +// with valid TLS credentials. +TEST_F(TlsListenerTest, listen) { + const std::string request = "I am done"; + + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + serverContext(), + TcpListener::IdleTimeout(IDLE_TIMEOUT)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + ASSERT_NO_THROW(startRequest(request, clientContext())); + ASSERT_NO_THROW(runIOService()); + ASSERT_EQ(1, clients_.size()); + TcpTestClientPtr client = *clients_.begin(); + ASSERT_TRUE(client); + EXPECT_TRUE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + + // Verify the audit trail for the connection. + // Sanity check to make sure we don't have more entries than we expect. + ASSERT_EQ(listener.audit_trail_->entries_.size(), 2); + + // Create the list of expected entries. + std::list expected_entries { + { 1, AuditEntry::INBOUND, "I am done" }, + { 1, AuditEntry::OUTBOUND, "good bye" } + }; + + // Verify the audit trail. + ASSERT_EQ(expected_entries, listener.audit_trail_->getConnectionTrail(1)); + + listener.stop(); + io_service_.poll(); +} + +// This test verifies that a TLS connection is denied to a client +// with invalid TLS credentials. +TEST_F(TlsListenerTest, badClient) { + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + serverContext(), + TcpListener::IdleTimeout(IDLE_TIMEOUT)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + + TlsContextPtr bad_client_ctx; + configSelf(bad_client_ctx); + ASSERT_NO_THROW(startRequest("", bad_client_ctx)); + + ASSERT_NO_THROW(runIOService()); + + ASSERT_EQ(1, clients_.size()); + TcpTestClientPtr client = *clients_.begin(); + ASSERT_TRUE(client); + EXPECT_FALSE(client->receiveDone()); + + // Either we failed during handshake or we EOF'd as expected. OpenSSL fails + // after handshake, Botan before it. + EXPECT_TRUE(client->expectedEof() || client->handshakeFailed()); +} + +// This test verifies that a TLS connection can receive a complete +// message that spans multiple socket reads. +TEST_F(TlsListenerTest, splitReads) { + const std::string request = "I am done"; + + // Read at most one byte at a time. + size_t read_max = 1; + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + serverContext(), + TcpListener::IdleTimeout(IDLE_TIMEOUT), + 0, + read_max); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + ASSERT_NO_THROW(startRequest(request, clientContext())); + ASSERT_NO_THROW(runIOService()); + + // Fetch the client. + ASSERT_EQ(1, clients_.size()); + TcpTestClientPtr client = *clients_.begin(); + ASSERT_TRUE(client); + EXPECT_TRUE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + + listener.stop(); + io_service_.poll(); +} + +// This test verifies that a TLS connection can be established and used to +// transmit a streamed request and receive a streamed response. +TEST_F(TlsListenerTest, idleTimeoutTest) { + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + serverContext(), + TcpListener::IdleTimeout(SHORT_IDLE_TIMEOUT)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + // Start a client with an empty request. Empty requests tell the client + // to read without sending anything and expect the read to fail when + // the listener idle times out the socket. + ASSERT_NO_THROW(startRequest("", clientContext())); + + // Run until idle timer expires. + ASSERT_NO_THROW(runIOService()); + + ASSERT_EQ(1, clients_.size()); + TcpTestClientPtr client = *clients_.begin(); + EXPECT_FALSE(client->receiveDone()); + EXPECT_TRUE(client->expectedEof()); + + listener.stop(); + io_service_.poll(); +} + +// This test verifies that TLS connections with multiple clients. +TEST_F(TlsListenerTest, multipleClientsListen) { + const std::string request = "I am done"; + + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + serverContext(), + TcpListener::IdleTimeout(IDLE_TIMEOUT)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + size_t num_clients = 5; + for (auto i = 0; i < num_clients; ++i) { + ASSERT_NO_THROW(startRequest(request, clientContext())); + } + + ASSERT_NO_THROW(runIOService()); + ASSERT_EQ(num_clients, clients_.size()); + + size_t connection_id = 1; + for (auto client : clients_) { + EXPECT_TRUE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + // Create the list of expected entries. + std::list expected_entries { + { connection_id, AuditEntry::INBOUND, "I am done" }, + { connection_id, AuditEntry::OUTBOUND, "good bye" } + }; + + // Fetch the entries for this connection. + auto entries = listener.audit_trail_->getConnectionTrail(connection_id); + ASSERT_EQ(expected_entries, entries); + ++connection_id; + } + + listener.stop(); + io_service_.poll(); +} + +// Verify that the listener handles multiple requests for multiple +// clients. +TEST_F(TlsListenerTest, multipleRequetsPerClients) { + std::listrequests{ "one", "two", "three", "I am done"}; + + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + serverContext(), + TcpListener::IdleTimeout(IDLE_TIMEOUT)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + size_t num_clients = 5; + for (auto i = 0; i < num_clients; ++i) { + ASSERT_NO_THROW(startRequests(requests, clientContext())); + } + + ASSERT_NO_THROW(runIOService()); + ASSERT_EQ(num_clients, clients_.size()); + + std::listexpected_responses{ "echo one", "echo two", + "echo three", "good bye"}; + size_t connection_id = 1; + for (auto client : clients_) { + EXPECT_TRUE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + EXPECT_EQ(expected_responses, client->getResponses()); + + // Verify the connection's audit trail. + // Create the list of expected entries. + std::list expected_entries { + { connection_id, AuditEntry::INBOUND, "one" }, + { connection_id, AuditEntry::OUTBOUND, "echo one" }, + { connection_id, AuditEntry::INBOUND, "two" }, + { connection_id, AuditEntry::OUTBOUND, "echo two" }, + { connection_id, AuditEntry::INBOUND, "three" }, + { connection_id, AuditEntry::OUTBOUND, "echo three" }, + { connection_id, AuditEntry::INBOUND, "I am done" }, + { connection_id, AuditEntry::OUTBOUND, "good bye" } + }; + + // Fetch the entries for this connection. + auto entries = listener.audit_trail_->getConnectionTrail(connection_id); + ASSERT_EQ(expected_entries, entries); + ++connection_id; + } + + listener.stop(); + io_service_.poll(); +} + +// Verify that connection filtering can eliminate specific connections. +TEST_F(TlsListenerTest, filterClientsTest) { + TcpTestListener listener(io_service_, + IOAddress(SERVER_ADDRESS), + SERVER_PORT, + serverContext(), + TcpListener::IdleTimeout(IDLE_TIMEOUT), + std::bind(&TlsListenerTest::connectionFilter, this, ph::_1)); + + ASSERT_NO_THROW(listener.start()); + ASSERT_EQ(SERVER_ADDRESS, listener.getLocalAddress().toText()); + ASSERT_EQ(SERVER_PORT, listener.getLocalPort()); + size_t num_clients = 5; + for (auto i = 0; i < num_clients; ++i) { + // Every other client sends nothing (i.e. waits for EOF) as + // we expect the filter to reject them. + if (i % 2 == 0) { + ASSERT_NO_THROW(startRequest("I am done", clientContext())); + } else { + ASSERT_NO_THROW(startRequest("", clientContext())); + } + } + + ASSERT_NO_THROW(runIOService()); + ASSERT_EQ(num_clients, clients_.size()); + + size_t i = 0; + for (auto client : clients_) { + if (i % 2 == 0) { + // These clients should have been accepted and received responses. + EXPECT_TRUE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + EXPECT_FALSE(client->handshakeFailed()); + + // Now verify the AuditTrail. + // Create the list of expected entries. + std::list expected_entries { + { i+1, AuditEntry::INBOUND, "I am done" }, + { i+1, AuditEntry::OUTBOUND, "good bye" } + }; + + auto entries = listener.audit_trail_->getConnectionTrail(i+1); + ASSERT_EQ(expected_entries, entries); + + } else { + // Connection filtering closes the connection before the client + // initiates the handshake, causing the subsequent handshake attempt + // to fail. + EXPECT_FALSE(client->receiveDone()); + EXPECT_FALSE(client->expectedEof()); + EXPECT_TRUE(client->handshakeFailed()); + + // Verify connection recorded no audit entries. + auto entries = listener.audit_trail_->getConnectionTrail(i+1); + ASSERT_EQ(entries.size(), 0); + } + + ++i; + } + + listener.stop(); + io_service_.poll(); +} + +} -- cgit v1.2.3