diff options
Diffstat (limited to 'src/lib/util/io')
-rw-r--r-- | src/lib/util/io/Makefile.am | 14 | ||||
-rw-r--r-- | src/lib/util/io/Makefile.in | 890 | ||||
-rw-r--r-- | src/lib/util/io/fd.cc | 78 | ||||
-rw-r--r-- | src/lib/util/io/fd.h | 53 | ||||
-rw-r--r-- | src/lib/util/io/fd_share.cc | 166 | ||||
-rw-r--r-- | src/lib/util/io/fd_share.h | 61 | ||||
-rw-r--r-- | src/lib/util/io/pktinfo_utilities.h | 43 | ||||
-rw-r--r-- | src/lib/util/io/sockaddr_util.h | 76 | ||||
-rw-r--r-- | src/lib/util/io/socketsession.cc | 438 | ||||
-rw-r--r-- | src/lib/util/io/socketsession.h | 495 |
10 files changed, 2314 insertions, 0 deletions
diff --git a/src/lib/util/io/Makefile.am b/src/lib/util/io/Makefile.am new file mode 100644 index 0000000..b5659b9 --- /dev/null +++ b/src/lib/util/io/Makefile.am @@ -0,0 +1,14 @@ +SUBDIRS = . +AM_CXXFLAGS = $(KEA_CXXFLAGS) + +AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib +AM_CPPFLAGS += $(BOOST_INCLUDES) + +lib_LTLIBRARIES = libkea-util-io.la +libkea_util_io_la_SOURCES = fd.h fd.cc fd_share.h fd_share.cc +libkea_util_io_la_SOURCES += socketsession.h socketsession.cc sockaddr_util.h +libkea_util_io_la_SOURCES += pktinfo_utilities.h +libkea_util_io_la_LIBADD = $(top_builddir)/src/lib/exceptions/libkea-exceptions.la +libkea_util_io_la_LDFLAGS = -no-undefined -version-info 0:1:0 + +CLEANFILES = *.gcno *.gcda diff --git a/src/lib/util/io/Makefile.in b/src/lib/util/io/Makefile.in new file mode 100644 index 0000000..ee32b5f --- /dev/null +++ b/src/lib/util/io/Makefile.in @@ -0,0 +1,890 @@ +# 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@ +subdir = src/lib/util/io +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_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_sysrepo.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 = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libdir)" +LTLIBRARIES = $(lib_LTLIBRARIES) +libkea_util_io_la_DEPENDENCIES = \ + $(top_builddir)/src/lib/exceptions/libkea-exceptions.la +am_libkea_util_io_la_OBJECTS = fd.lo fd_share.lo socketsession.lo +libkea_util_io_la_OBJECTS = $(am_libkea_util_io_la_OBJECTS) +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 = +libkea_util_io_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX \ + $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ + $(AM_CXXFLAGS) $(CXXFLAGS) $(libkea_util_io_la_LDFLAGS) \ + $(LDFLAGS) -o $@ +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)/fd.Plo ./$(DEPDIR)/fd_share.Plo \ + ./$(DEPDIR)/socketsession.Plo +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 = $(libkea_util_io_la_SOURCES) +DIST_SOURCES = $(libkea_util_io_la_SOURCES) +RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ + ctags-recursive dvi-recursive html-recursive info-recursive \ + install-data-recursive install-dvi-recursive \ + install-exec-recursive install-html-recursive \ + install-info-recursive install-pdf-recursive \ + install-ps-recursive install-recursive installcheck-recursive \ + installdirs-recursive pdf-recursive ps-recursive \ + tags-recursive uninstall-recursive +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +am__recursive_targets = \ + $(RECURSIVE_TARGETS) \ + $(RECURSIVE_CLEAN_TARGETS) \ + $(am__extra_recursive_targets) +AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ + distdir distdir-am +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 +DIST_SUBDIRS = $(SUBDIRS) +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/depcomp +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +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_GTEST_CONFIGURE_FLAG = @DISTCHECK_GTEST_CONFIGURE_FLAG@ +DISTCHECK_KEA_SHELL_CONFIGURE_FLAG = @DISTCHECK_KEA_SHELL_CONFIGURE_FLAG@ +DISTCHECK_LOG4CPLUS_CONFIGURE_FLAG = @DISTCHECK_LOG4CPLUS_CONFIGURE_FLAG@ +DISTCHECK_PERFDHCP_CONFIGURE_FLAG = @DISTCHECK_PERFDHCP_CONFIGURE_FLAG@ +DISTCHECK_PREMIUM_CONFIGURE_FLAG = @DISTCHECK_PREMIUM_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_SYSREPO = @HAVE_SYSREPO@ +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@ +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_REPO_PATH = @SR_REPO_PATH@ +STRIP = @STRIP@ +SYSREPOCPP_VERSION = @SYSREPOCPP_VERSION@ +SYSREPO_CPPFLAGS = @SYSREPO_CPPFLAGS@ +SYSREPO_INCLUDEDIR = @SYSREPO_INCLUDEDIR@ +SYSREPO_LIBS = @SYSREPO_LIBS@ +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@ +SUBDIRS = . +AM_CXXFLAGS = $(KEA_CXXFLAGS) +AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib \ + $(BOOST_INCLUDES) +lib_LTLIBRARIES = libkea-util-io.la +libkea_util_io_la_SOURCES = fd.h fd.cc fd_share.h fd_share.cc \ + socketsession.h socketsession.cc sockaddr_util.h \ + pktinfo_utilities.h +libkea_util_io_la_LIBADD = $(top_builddir)/src/lib/exceptions/libkea-exceptions.la +libkea_util_io_la_LDFLAGS = -no-undefined -version-info 0:1:0 +CLEANFILES = *.gcno *.gcda +all: all-recursive + +.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/util/io/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/lib/util/io/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): + +install-libLTLIBRARIES: $(lib_LTLIBRARIES) + @$(NORMAL_INSTALL) + @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ + } + +uninstall-libLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ + done + +clean-libLTLIBRARIES: + -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) + @list='$(lib_LTLIBRARIES)'; \ + locs=`for p in $$list; do echo $$p; done | \ + sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ + sort -u`; \ + test -z "$$locs" || { \ + echo rm -f $${locs}; \ + rm -f $${locs}; \ + } + +libkea-util-io.la: $(libkea_util_io_la_OBJECTS) $(libkea_util_io_la_DEPENDENCIES) $(EXTRA_libkea_util_io_la_DEPENDENCIES) + $(AM_V_CXXLD)$(libkea_util_io_la_LINK) -rpath $(libdir) $(libkea_util_io_la_OBJECTS) $(libkea_util_io_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fd.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fd_share.Plo@am__quote@ # am--include-marker +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socketsession.Plo@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 $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +# This directory's subdirectories are mostly independent; you can cd +# into them and run 'make' without going through this Makefile. +# To change the values of 'make' variables: instead of editing Makefiles, +# (1) if the variable is set in 'config.status', edit 'config.status' +# (which will cause the Makefiles to be regenerated when you run 'make'); +# (2) otherwise, pass the desired values on the 'make' command line. +$(am__recursive_targets): + @fail=; \ + if $(am__make_keepgoing); then \ + failcom='fail=yes'; \ + else \ + failcom='exit 1'; \ + fi; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-recursive +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + $(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-recursive + +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-recursive + +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 + +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 + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + $(am__make_dryrun) \ + || test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile $(LTLIBRARIES) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(libdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +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) + +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-recursive + +clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ + mostlyclean-am + +distclean: distclean-recursive + -rm -f ./$(DEPDIR)/fd.Plo + -rm -f ./$(DEPDIR)/fd_share.Plo + -rm -f ./$(DEPDIR)/socketsession.Plo + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: install-libLTLIBRARIES + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f ./$(DEPDIR)/fd.Plo + -rm -f ./$(DEPDIR)/fd_share.Plo + -rm -f ./$(DEPDIR)/socketsession.Plo + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-libLTLIBRARIES + +.MAKE: $(am__recursive_targets) install-am install-strip + +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ + am--depfiles check check-am clean clean-generic \ + clean-libLTLIBRARIES clean-libtool 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-libLTLIBRARIES install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs installdirs-am \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-libLTLIBRARIES + +.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/util/io/fd.cc b/src/lib/util/io/fd.cc new file mode 100644 index 0000000..9d89485 --- /dev/null +++ b/src/lib/util/io/fd.cc @@ -0,0 +1,78 @@ +// Copyright (C) 2011-2015 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 <config.h> + +#include <util/io/fd.h> + +#include <unistd.h> +#include <cerrno> + +namespace isc { +namespace util { +namespace io { + +bool +write_data(const int fd, const void *buffer_v, const size_t length) { + const unsigned char* buffer(static_cast<const unsigned char*>(buffer_v)); + size_t remaining = length; // Amount remaining to be written + + // Just keep writing until all is written + while (remaining > 0) { + const int written = write(fd, buffer, remaining); + if (written == -1) { + if (errno == EINTR) { // Just keep going + continue; + } else { + return (false); + } + + } else if (written > 0) { + // Wrote "written" bytes from the buffer + remaining -= written; + buffer += written; + + } else { + // Wrote zero bytes from the buffer. We should not get here as any + // error that causes zero bytes to be written should have returned + // -1. However, write(2) can return 0, and in this case we + // interpret it as an error. + return (false); + } + } + return (true); +} + +ssize_t +read_data(const int fd, void *buffer_v, const size_t length) { + unsigned char* buffer(static_cast<unsigned char*>(buffer_v)); + size_t remaining = length; // Amount remaining to be read + + while (remaining > 0) { + const int amount = read(fd, buffer, remaining); + if (amount == -1) { + if (errno == EINTR) { // Continue on interrupted call + continue; + } else { + return (-1); + } + } else if (amount > 0) { + // Read "amount" bytes into the buffer + remaining -= amount; + buffer += amount; + } else { + // EOF - end the read + break; + } + } + + // Return total number of bytes read + return (static_cast<ssize_t>(length - remaining)); +} + +} +} +} diff --git a/src/lib/util/io/fd.h b/src/lib/util/io/fd.h new file mode 100644 index 0000000..b647425 --- /dev/null +++ b/src/lib/util/io/fd.h @@ -0,0 +1,53 @@ +// Copyright (C) 2011-2015 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 UTIL_IO_FD_H +#define UTIL_IO_FD_H 1 + +#include <unistd.h> + +/** + * @file fd.h + * @short Wrappers around common unix fd manipulation functions. + */ + +namespace isc { +namespace util { +namespace io { + +/* + * \short write() that writes everything. + * Wrapper around write(). The difference is, it never writes less data + * and looks successful (eg. it blocks until all data are written). + * Retries on signals. + * + * \return True if successful, false otherwise. The errno variable is left + * intact. + * \param fd Where to write. + * \param data The buffer to write. + * \param length How much data is there to write. + */ +bool +write_data(const int fd, const void *data, const size_t length); + +/* + * \short read() that reads everything. + * Wrapper around read(). It does not do short reads, if it returns less, + * it means there was EOF. It retries on signals. + * + * \return Number of bytes read or -1 on error. + * \param fd Where to read data from. + * \param data Where to put the data. + * \param length How many of them. + */ +ssize_t +read_data(const int fd, void *buffer, const size_t length); + +} +} +} + +#endif // UTIL_IO_FD_H diff --git a/src/lib/util/io/fd_share.cc b/src/lib/util/io/fd_share.cc new file mode 100644 index 0000000..6edffd3 --- /dev/null +++ b/src/lib/util/io/fd_share.cc @@ -0,0 +1,166 @@ +// Copyright (C) 2010-2019 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 <config.h> + +#include <cstring> +#include <cstdlib> + +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/uio.h> +#include <errno.h> +#include <stdlib.h> // for malloc and free +#include <unistd.h> +#include <util/io/fd_share.h> + +namespace isc { +namespace util { +namespace io { + +namespace { +// Not all OSes support advanced CMSG macros: CMSG_LEN and CMSG_SPACE. +// In order to ensure as much portability as possible, we provide wrapper +// functions of these macros. +// Note that cmsg_space() could run slow on OSes that do not have +// CMSG_SPACE. +inline socklen_t +cmsg_len(const socklen_t len) { +#ifdef CMSG_LEN + return (CMSG_LEN(len)); +#else + // Cast NULL so that any pointer arithmetic performed by CMSG_DATA + // is correct. + const uintptr_t hdrlen = (uintptr_t)CMSG_DATA(((struct cmsghdr*)NULL)); + return (hdrlen + len); +#endif +} + +inline socklen_t +cmsg_space(const socklen_t len) { +#ifdef CMSG_SPACE + return (CMSG_SPACE(len)); +#else + struct msghdr msg; + struct cmsghdr* cmsgp; + // XXX: The buffer length is an ad hoc value, but should be enough + // in a practical sense. + char dummybuf[sizeof(struct cmsghdr) + 1024]; + + memset(&msg, 0, sizeof(msg)); + msg.msg_control = dummybuf; + msg.msg_controllen = sizeof(dummybuf); + + cmsgp = (struct cmsghdr*)dummybuf; + cmsgp->cmsg_len = cmsg_len(len); + + cmsgp = CMSG_NXTHDR(&msg, cmsgp); + if (cmsgp != NULL) { + return ((char*)cmsgp - (char*)msg.msg_control); + } else { + return (0); + } +#endif // CMSG_SPACE +} +} + +int +recv_fd(const int sock) { + struct msghdr msghdr; + struct iovec iov_dummy; + unsigned char dummy_data; + + iov_dummy.iov_base = &dummy_data; + iov_dummy.iov_len = sizeof(dummy_data); + msghdr.msg_name = NULL; + msghdr.msg_namelen = 0; + msghdr.msg_iov = &iov_dummy; + msghdr.msg_iovlen = 1; + msghdr.msg_flags = 0; + msghdr.msg_controllen = cmsg_space(sizeof(int)); + msghdr.msg_control = malloc(msghdr.msg_controllen); + if (msghdr.msg_control == NULL) { + return (FD_SYSTEM_ERROR); + } + + const int cc = recvmsg(sock, &msghdr, 0); + if (cc <= 0) { + free(msghdr.msg_control); + if (cc == 0) { + errno = ECONNRESET; + } + return (FD_SYSTEM_ERROR); + } + const struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msghdr); + int fd = FD_OTHER_ERROR; + if (cmsg != NULL && cmsg->cmsg_len == cmsg_len(sizeof(int)) && + cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { +// Some systems (e.g. recent NetBSD) converted all CMSG access macros +// to static_cast when used in C++ code. As cmsg is declared const +// this makes the CMSG_DATA macro to not compile. But fortunately +// these systems provide a const alternative named CCMSG_DATA. +#ifdef CCMSG_DATA + std::memcpy(&fd, CCMSG_DATA(cmsg), sizeof(int)); +#else + std::memcpy(&fd, CMSG_DATA(cmsg), sizeof(int)); +#endif + } + free(msghdr.msg_control); + int new_fd = -1; + int close_error = -1; + if (fd >= 0) { + // It is strange, but the call can return the same file descriptor as + // one returned previously, even if that one is not closed yet. So, + // we just re-number every one we get, so they are unique. + new_fd = dup(fd); + close_error = close(fd); + } + if (close_error == -1 || new_fd == -1) { + // We need to return an error, because something failed. But in case + // it was the previous close, we at least try to close the duped FD. + if (new_fd != -1) { + close(new_fd); // If this fails, nothing but returning error can't + // be done and we are doing that anyway. + } + return (FD_SYSTEM_ERROR); + } + return (new_fd); +} + +int +send_fd(const int sock, const int fd) { + struct msghdr msghdr; + struct iovec iov_dummy; + unsigned char dummy_data = 0; + + iov_dummy.iov_base = &dummy_data; + iov_dummy.iov_len = sizeof(dummy_data); + msghdr.msg_name = NULL; + msghdr.msg_namelen = 0; + msghdr.msg_iov = &iov_dummy; + msghdr.msg_iovlen = 1; + msghdr.msg_flags = 0; + msghdr.msg_controllen = cmsg_space(sizeof(int)); + msghdr.msg_control = malloc(msghdr.msg_controllen); + if (msghdr.msg_control == NULL) { + return (FD_OTHER_ERROR); + } + std::memset(msghdr.msg_control, 0, msghdr.msg_controllen); + + struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msghdr); + cmsg->cmsg_len = cmsg_len(sizeof(int)); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + std::memcpy(CMSG_DATA(cmsg), &fd, sizeof(int)); + + const int ret = sendmsg(sock, &msghdr, 0); + free(msghdr.msg_control); + return (ret >= 0 ? 0 : FD_SYSTEM_ERROR); +} + +} // End for namespace io +} // End for namespace util +} // End for namespace isc diff --git a/src/lib/util/io/fd_share.h b/src/lib/util/io/fd_share.h new file mode 100644 index 0000000..36d0d5f --- /dev/null +++ b/src/lib/util/io/fd_share.h @@ -0,0 +1,61 @@ +// Copyright (C) 2011-2015 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 FD_SHARE_H_ +#define FD_SHARE_H_ + +/** + * \file fd_share.h + * \short Support to transfer file descriptors between processes. + * \todo This interface is very C-ish. Should we have some kind of exceptions? + */ + +namespace isc { +namespace util { +namespace io { + +const int FD_SYSTEM_ERROR = -2; +const int FD_OTHER_ERROR = -1; + +/** + * \short Receives a file descriptor. + * This receives a file descriptor sent over an unix domain socket. This + * is the counterpart of send_fd(). + * + * \return FD_SYSTEM_ERROR when there's an error at the operating system + * level (such as a system call failure). The global 'errno' variable + * indicates the specific error. FD_OTHER_ERROR when there's a different + * error. + * + * \param sock The unix domain socket to read from. Tested and it does + * not work with a pipe. + */ +int recv_fd(const int sock); + +/** + * \short Sends a file descriptor. + * This sends a file descriptor over an unix domain socket. This is the + * counterpart of recv_fd(). + * + * \return FD_SYSTEM_ERROR when there's an error at the operating system + * level (such as a system call failure). The global 'errno' variable + * indicates the specific error. + * \param sock The unix domain socket to send to. Tested and it does not + * work with a pipe. + * \param fd The file descriptor to send. It should work with any valid + * file descriptor. + */ +int send_fd(const int sock, const int fd); + +} // End for namespace io +} // End for namespace util +} // End for namespace isc + +#endif + +// Local Variables: +// mode: c++ +// End: diff --git a/src/lib/util/io/pktinfo_utilities.h b/src/lib/util/io/pktinfo_utilities.h new file mode 100644 index 0000000..2625008 --- /dev/null +++ b/src/lib/util/io/pktinfo_utilities.h @@ -0,0 +1,43 @@ +// Copyright (C) 2012-2015 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 PKTINFO_UTIL_H +#define PKTINFO_UTIL_H 1 + +#include <sys/socket.h> +#include <netinet/in.h> + +// These definitions in this file are for the convenience of internal +// implementation and test code, and are not intended to be used publicly. +// The namespace "internal" indicates the intent. + +namespace isc { +namespace util { +namespace io { +namespace internal { + +// Lower level C-APIs require conversion between char* pointers +// (like structures returned by CMSG_DATA macro) and in6_pktinfo, +// which is not friendly with C++. The following templates +// are a shortcut of common workaround conversion in such cases. +inline struct in6_pktinfo* +convertPktInfo6(char* pktinfo) { + return (static_cast<struct in6_pktinfo*>(static_cast<void*>(pktinfo))); +} + +inline struct in6_pktinfo* +convertPktInfo6(unsigned char* pktinfo) { + return (static_cast<struct in6_pktinfo*>(static_cast<void*>(pktinfo))); +} + +/// @todo: Do we need const versions as well? + +} +} +} +} + +#endif // PKTINFO_UTIL_H diff --git a/src/lib/util/io/sockaddr_util.h b/src/lib/util/io/sockaddr_util.h new file mode 100644 index 0000000..1cb31f2 --- /dev/null +++ b/src/lib/util/io/sockaddr_util.h @@ -0,0 +1,76 @@ +// Copyright (C) 2011-2020 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 SOCKADDR_UTIL_H +#define SOCKADDR_UTIL_H 1 + +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> + +#include <exceptions/isc_assert.h> + +// These definitions in this file are for the convenience of internal +// implementation and test code, and are not intended to be used publicly. +// The namespace "internal" indicates the intent. + +namespace isc { +namespace util { +namespace io { +namespace internal { + +inline socklen_t +getSALength(const struct sockaddr& sa) { + if (sa.sa_family == AF_INET) { + return (sizeof(struct sockaddr_in)); + } else { + isc_throw_assert(sa.sa_family == AF_INET6); + return (sizeof(struct sockaddr_in6)); + } +} + +// Lower level C-APIs require conversion between various variants of +// sockaddr's, which is not friendly with C++. The following templates +// are a shortcut of common workaround conversion in such cases. + +template <typename SAType> +const struct sockaddr* +convertSockAddr(const SAType* sa) { + const void* p = sa; + return (static_cast<const struct sockaddr*>(p)); +} + +template <typename SAType> +const SAType* +convertSockAddr(const struct sockaddr* sa) { + const void* p = sa; + return (static_cast<const SAType*>(p)); +} + +template <typename SAType> +struct sockaddr* +convertSockAddr(SAType* sa) { + void* p = sa; + return (static_cast<struct sockaddr*>(p)); +} + +template <typename SAType> +SAType* +convertSockAddr(struct sockaddr* sa) { + void* p = sa; + return (static_cast<SAType*>(p)); +} + +} +} +} +} + +#endif // SOCKADDR_UTIL_H + +// Local Variables: +// mode: c++ +// End: diff --git a/src/lib/util/io/socketsession.cc b/src/lib/util/io/socketsession.cc new file mode 100644 index 0000000..88f2b1e --- /dev/null +++ b/src/lib/util/io/socketsession.cc @@ -0,0 +1,438 @@ +// Copyright (C) 2011-2021 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 <config.h> + +#include <unistd.h> + +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/uio.h> +#include <sys/un.h> + +#include <netinet/in.h> + +#include <fcntl.h> +#include <stdint.h> + +#include <cerrno> +#include <csignal> +#include <cstddef> +#include <cstring> + +#include <string> +#include <vector> + +#include <boost/noncopyable.hpp> + +#include <exceptions/exceptions.h> +#include <exceptions/isc_assert.h> + +#include <util/buffer.h> + +#include <util/io/fd_share.h> +#include <util/io/socketsession.h> +#include <util/io/sockaddr_util.h> + +using namespace std; + +namespace isc { +namespace util { +namespace io { + +using namespace internal; + +// The expected max size of the session header: 2-byte header length, +// 6 32-bit fields, and 2 sockaddr structure. (see the SocketSessionUtility +// overview description in the header file). sizeof sockaddr_storage +// should be the possible max of any sockaddr structure +const size_t DEFAULT_HEADER_BUFLEN = sizeof(uint16_t) + sizeof(uint32_t) * 6 + + sizeof(struct sockaddr_storage) * 2; + +// The allowable maximum size of data passed with the socket FD. For now +// we use a fixed value of 65535, the largest possible size of valid DNS +// messages. We may enlarge it or make it configurable as we see the need +// for more flexibility. +const int MAX_DATASIZE = 65535; + +// The initial buffer size for receiving socket session data in the receiver. +// This value is the maximum message size of DNS messages carried over UDP +// (without EDNS). In our expected usage (at the moment) this should be +// sufficiently large (the expected data is AXFR/IXFR query or an UPDATE +// requests. The former should be generally quite small. While the latter +// could be large, it would often be small enough for a single UDP message). +// If it turns out that there are many exceptions, we may want to extend +// the class so that this value can be customized. Note that the buffer +// will be automatically extended for longer data and this is only about +// efficiency. +const size_t INITIAL_BUFSIZE = 512; + +// The (default) socket buffer size for the forwarder and receiver. This is +// chosen to be sufficiently large to store two full-size DNS messages. We +// may want to customize this value in future. +const int SOCKSESSION_BUFSIZE = (DEFAULT_HEADER_BUFLEN + MAX_DATASIZE) * 2; + +struct SocketSessionForwarder::ForwarderImpl { + ForwarderImpl() : sock_un_len_(0), fd_(-1), buf_(DEFAULT_HEADER_BUFLEN) { + memset(&sock_un_, 0, sizeof(sock_un_)); + } + + struct sockaddr_un sock_un_; + socklen_t sock_un_len_; + int fd_; + OutputBuffer buf_; +}; + +SocketSessionForwarder::SocketSessionForwarder(const std::string& unix_file) : + impl_(NULL) +{ + // We need to filter SIGPIPE for subsequent push(). See the class + // description. + if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { + isc_throw(Unexpected, "Failed to filter SIGPIPE: " << strerror(errno)); + } + + ForwarderImpl impl; + if (sizeof(impl.sock_un_.sun_path) - 1 < unix_file.length()) { + isc_throw(SocketSessionError, + "File name for a UNIX domain socket is too long: " << + unix_file); + } + impl.sock_un_.sun_family = AF_UNIX; + // the copy should be safe due to the above check, but we'd be rather + // paranoid about making it 100% sure even if the check has a bug (with + // triggering the assertion in the worse case) + memset(&impl.sock_un_.sun_path, 0, sizeof(impl.sock_un_.sun_path)); + strncpy(impl.sock_un_.sun_path, unix_file.c_str(), + sizeof(impl.sock_un_.sun_path) - 1); + isc_throw_assert(impl.sock_un_.sun_path[sizeof(impl.sock_un_.sun_path) - 1] == '\0'); + impl.sock_un_len_ = offsetof(struct sockaddr_un, sun_path) + + unix_file.length(); +#ifdef HAVE_SA_LEN + impl.sock_un_.sun_len = impl.sock_un_len_; +#endif + impl.fd_ = -1; + + impl_ = new ForwarderImpl; + *impl_ = impl; +} + +SocketSessionForwarder::~SocketSessionForwarder() { + if (impl_->fd_ != -1) { + close(); + } + delete impl_; +} + +void +SocketSessionForwarder::connectToReceiver() { + if (impl_->fd_ != -1) { + isc_throw(BadValue, "Duplicate connect to UNIX domain " + "endpoint " << impl_->sock_un_.sun_path); + } + + impl_->fd_ = socket(AF_UNIX, SOCK_STREAM, 0); + if (impl_->fd_ == -1) { + isc_throw(SocketSessionError, "Failed to create a UNIX domain socket: " + << strerror(errno)); + } + // Make the socket non blocking + int fcntl_flags = fcntl(impl_->fd_, F_GETFL, 0); + if (fcntl_flags != -1) { + fcntl_flags |= O_NONBLOCK; + fcntl_flags = fcntl(impl_->fd_, F_SETFL, fcntl_flags); + } + if (fcntl_flags == -1) { + close(); // note: this is the internal method, not ::close() + isc_throw(SocketSessionError, + "Failed to make UNIX domain socket non blocking: " << + strerror(errno)); + } + // Ensure the socket send buffer is large enough. If we can't get the + // current size, simply set the sufficient size. + int sndbuf_size; + socklen_t sndbuf_size_len = sizeof(sndbuf_size); + if (getsockopt(impl_->fd_, SOL_SOCKET, SO_SNDBUF, &sndbuf_size, + &sndbuf_size_len) == -1 || + sndbuf_size < SOCKSESSION_BUFSIZE) { + if (setsockopt(impl_->fd_, SOL_SOCKET, SO_SNDBUF, &SOCKSESSION_BUFSIZE, + sizeof(SOCKSESSION_BUFSIZE)) == -1) { + close(); + isc_throw(SocketSessionError, + "Failed to set send buffer size to " << + SOCKSESSION_BUFSIZE); + } + } + if (connect(impl_->fd_, convertSockAddr(&impl_->sock_un_), + impl_->sock_un_len_) == -1) { + close(); + isc_throw(SocketSessionError, "Failed to connect to UNIX domain " + "endpoint " << impl_->sock_un_.sun_path << ": " << + strerror(errno)); + } +} + +void +SocketSessionForwarder::close() { + if (impl_->fd_ == -1) { + isc_throw(BadValue, "Attempt of close before connect"); + } + ::close(impl_->fd_); + impl_->fd_ = -1; +} + +void +SocketSessionForwarder::push(int sock, int family, int type, int protocol, + const struct sockaddr& local_end, + const struct sockaddr& remote_end, + const void* data, size_t data_len) +{ + if (impl_->fd_ == -1) { + isc_throw(BadValue, "Attempt of push before connect"); + } + if ((local_end.sa_family != AF_INET && local_end.sa_family != AF_INET6) || + (remote_end.sa_family != AF_INET && remote_end.sa_family != AF_INET6)) + { + isc_throw(BadValue, "Invalid address family: must be " + "AF_INET or AF_INET6; " << + static_cast<int>(local_end.sa_family) << ", " << + static_cast<int>(remote_end.sa_family) << " given"); + } + if (family != local_end.sa_family || family != remote_end.sa_family) { + isc_throw(BadValue, "Inconsistent address family: must be " + << static_cast<int>(family) << "; " + << static_cast<int>(local_end.sa_family) << ", " + << static_cast<int>(remote_end.sa_family) << " given"); + } + if (data_len == 0 || data == NULL) { + isc_throw(BadValue, "Data for a socket session must not be empty"); + } + if (data_len > MAX_DATASIZE) { + isc_throw(BadValue, "Invalid socket session data size: " << + data_len << ", must not exceed " << MAX_DATASIZE); + } + + if (send_fd(impl_->fd_, sock) != 0) { + isc_throw(SocketSessionError, "FD passing failed: " << + strerror(errno)); + } + + impl_->buf_.clear(); + // Leave the space for the header length + impl_->buf_.skip(sizeof(uint16_t)); + // Socket properties: family, type, protocol + impl_->buf_.writeUint32(static_cast<uint32_t>(family)); + impl_->buf_.writeUint32(static_cast<uint32_t>(type)); + impl_->buf_.writeUint32(static_cast<uint32_t>(protocol)); + // Local endpoint + impl_->buf_.writeUint32(static_cast<uint32_t>(getSALength(local_end))); + impl_->buf_.writeData(&local_end, getSALength(local_end)); + // Remote endpoint + impl_->buf_.writeUint32(static_cast<uint32_t>(getSALength(remote_end))); + impl_->buf_.writeData(&remote_end, getSALength(remote_end)); + // Data length. Must be fit uint32 due to the range check above. + const uint32_t data_len32 = static_cast<uint32_t>(data_len); + isc_throw_assert(data_len == data_len32); // shouldn't cause overflow. + impl_->buf_.writeUint32(data_len32); + // Write the resulting header length at the beginning of the buffer + impl_->buf_.writeUint16At(impl_->buf_.getLength() - sizeof(uint16_t), 0); + + const struct iovec iov[2] = { + { const_cast<void*>(impl_->buf_.getData()), impl_->buf_.getLength() }, + { const_cast<void*>(data), data_len } + }; + const int cc = writev(impl_->fd_, iov, 2); + if (cc != impl_->buf_.getLength() + data_len) { + if (cc < 0) { + isc_throw(SocketSessionError, + "Write failed in forwarding a socket session: " << + strerror(errno)); + } + isc_throw(SocketSessionError, + "Incomplete write in forwarding a socket session: " << cc << + "/" << (impl_->buf_.getLength() + data_len)); + } +} + +SocketSession::SocketSession(int sock, int family, int type, int protocol, + const sockaddr* local_end, + const sockaddr* remote_end, + const void* data, size_t data_len) : + sock_(sock), family_(family), type_(type), protocol_(protocol), + local_end_(local_end), remote_end_(remote_end), + data_(data), data_len_(data_len) +{ + if (local_end == NULL || remote_end == NULL) { + isc_throw(BadValue, "sockaddr must be non NULL for SocketSession"); + } + if (data_len == 0) { + isc_throw(BadValue, "data_len must be non 0 for SocketSession"); + } + if (data == NULL) { + isc_throw(BadValue, "data must be non NULL for SocketSession"); + } +} + +struct SocketSessionReceiver::ReceiverImpl { + ReceiverImpl(int fd) : fd_(fd), + sa_local_(convertSockAddr(&ss_local_)), + sa_remote_(convertSockAddr(&ss_remote_)), + header_buf_(DEFAULT_HEADER_BUFLEN), + data_buf_(INITIAL_BUFSIZE) + { + memset(&ss_local_, 0, sizeof(ss_local_)); + memset(&ss_remote_, 0, sizeof(ss_remote_)); + + if (setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &SOCKSESSION_BUFSIZE, + sizeof(SOCKSESSION_BUFSIZE)) == -1) { + isc_throw(SocketSessionError, + "Failed to set receive buffer size to " << + SOCKSESSION_BUFSIZE); + } + } + + const int fd_; + struct sockaddr_storage ss_local_; // placeholder for local endpoint + struct sockaddr* const sa_local_; + struct sockaddr_storage ss_remote_; // placeholder for remote endpoint + struct sockaddr* const sa_remote_; + + // placeholder for session header and data + vector<uint8_t> header_buf_; + vector<uint8_t> data_buf_; +}; + +SocketSessionReceiver::SocketSessionReceiver(int fd) : + impl_(new ReceiverImpl(fd)) +{ +} + +SocketSessionReceiver::~SocketSessionReceiver() { + delete impl_; +} + +namespace { +// A shortcut to throw common exception on failure of recv(2) +void +readFail(int actual_len, int expected_len) { + if (expected_len < 0) { + isc_throw(SocketSessionError, "Failed to receive data from " + "SocketSessionForwarder: " << strerror(errno)); + } + isc_throw(SocketSessionError, "Incomplete data from " + "SocketSessionForwarder: " << actual_len << "/" << + expected_len); +} + +// A helper container for a (socket) file descriptor used in +// SocketSessionReceiver::pop that ensures the socket is closed unless it +// can be safely passed to the caller via release(). +struct ScopedSocket : boost::noncopyable { + ScopedSocket(int fd) : fd_(fd) {} + ~ScopedSocket() { + if (fd_ >= 0) { + close(fd_); + } + } + int release() { + const int fd = fd_; + fd_ = -1; + return (fd); + } + int fd_; +}; +} + +SocketSession +SocketSessionReceiver::pop() { + ScopedSocket passed_sock(recv_fd(impl_->fd_)); + if (passed_sock.fd_ == FD_SYSTEM_ERROR) { + isc_throw(SocketSessionError, "Receiving a forwarded FD failed: " << + strerror(errno)); + } else if (passed_sock.fd_ < 0) { + isc_throw(SocketSessionError, "No FD forwarded"); + } + + uint16_t header_len; + const int cc_hlen = recv(impl_->fd_, &header_len, sizeof(header_len), + MSG_WAITALL); + if (cc_hlen < sizeof(header_len)) { + readFail(cc_hlen, sizeof(header_len)); + } + header_len = InputBuffer(&header_len, sizeof(header_len)).readUint16(); + if (header_len > DEFAULT_HEADER_BUFLEN) { + isc_throw(SocketSessionError, "Too large header length: " << + header_len); + } + impl_->header_buf_.clear(); + impl_->header_buf_.resize(header_len); + const int cc_hdr = recv(impl_->fd_, &impl_->header_buf_[0], header_len, + MSG_WAITALL); + if (cc_hdr < header_len) { + readFail(cc_hdr, header_len); + } + + InputBuffer ibuffer(&impl_->header_buf_[0], header_len); + try { + const int family = static_cast<int>(ibuffer.readUint32()); + if (family != AF_INET && family != AF_INET6) { + isc_throw(SocketSessionError, + "Unsupported address family is passed: " << family); + } + const int type = static_cast<int>(ibuffer.readUint32()); + const int protocol = static_cast<int>(ibuffer.readUint32()); + const socklen_t local_end_len = ibuffer.readUint32(); + const socklen_t endpoint_minlen = (family == AF_INET) ? + sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6); + if (local_end_len < endpoint_minlen || + local_end_len > sizeof(impl_->ss_local_)) { + isc_throw(SocketSessionError, "Invalid local SA length: " << + local_end_len); + } + ibuffer.readData(&impl_->ss_local_, local_end_len); + const socklen_t remote_end_len = ibuffer.readUint32(); + if (remote_end_len < endpoint_minlen || + remote_end_len > sizeof(impl_->ss_remote_)) { + isc_throw(SocketSessionError, "Invalid remote SA length: " << + remote_end_len); + } + ibuffer.readData(&impl_->ss_remote_, remote_end_len); + if (family != impl_->sa_local_->sa_family || + family != impl_->sa_remote_->sa_family) { + isc_throw(SocketSessionError, "SA family inconsistent: " << + static_cast<int>(impl_->sa_local_->sa_family) << ", " << + static_cast<int>(impl_->sa_remote_->sa_family) << + " given, must be " << family); + } + const size_t data_len = ibuffer.readUint32(); + if (data_len == 0 || data_len > MAX_DATASIZE) { + isc_throw(SocketSessionError, + "Invalid socket session data size: " << data_len << + ", must be > 0 and <= " << MAX_DATASIZE); + } + + impl_->data_buf_.clear(); + impl_->data_buf_.resize(data_len); + const int cc_data = recv(impl_->fd_, &impl_->data_buf_[0], data_len, + MSG_WAITALL); + if (cc_data < data_len) { + readFail(cc_data, data_len); + } + + return (SocketSession(passed_sock.release(), family, type, protocol, + impl_->sa_local_, impl_->sa_remote_, + &impl_->data_buf_[0], data_len)); + } catch (const InvalidBufferPosition& ex) { + // We catch the case where the given header is too short and convert + // the exception to SocketSessionError. + isc_throw(SocketSessionError, "bogus socket session header: " << + ex.what()); + } +} + +} +} +} diff --git a/src/lib/util/io/socketsession.h b/src/lib/util/io/socketsession.h new file mode 100644 index 0000000..52e33de --- /dev/null +++ b/src/lib/util/io/socketsession.h @@ -0,0 +1,495 @@ +// Copyright (C) 2011-2015 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 SOCKETSESSION_H +#define SOCKETSESSION_H 1 + +#include <boost/noncopyable.hpp> + +#include <exceptions/exceptions.h> + +#include <string> + +#include <sys/socket.h> + +namespace isc { +namespace util { +namespace io { + +/// \page SocketSessionUtility Socket session utility +/// +/// \note This class is currently unused. Once we get to the implementation +/// of the remote parts of the management API, we will evaluate whether +/// this code is useful or not and either start using it or remove it. +/// +/// This utility defines a set of classes that support forwarding a +/// "socket session" from one process to another. A socket session is a +/// conceptual tuple of the following elements: +/// - A network socket +/// - The local and remote endpoints of a (IP) communication taking place on +/// the socket. In practice an endpoint is a pair of an IP address and +/// TCP or UDP port number. +/// - Some amount of data sent from the remote endpoint and received on the +/// socket. We call it (socket) session data in this documentation. +/// +/// Note that this is a conceptual definition. Depending on the underlying +/// implementation and/or the network protocol, some of the elements could be +/// part of others; for example, if it's an established TCP connection, +/// the local and remote endpoints would be able to be retrieved from the +/// socket using the standard \c getsockname() and \c getpeername() system +/// calls. But in this definition we separate these to be more generic. +/// Also, as a matter of fact our intended usage includes non-connected UDP +/// communications, in which case at least the remote endpoint should be +/// provided separately from the socket. +/// +/// In the actual implementation we represent a socket as a tuple of +/// socket's file descriptor, address family (e.g. \c AF_INET6), +/// socket type (e.g. \c SOCK_STREAM), and protocol (e.g. \c IPPROTO_TCP). +/// The latter three are included in the representation of a socket in order +/// to provide complete information of how the socket would be created +/// by the \c socket(2) system call. More specifically in practice, these +/// parameters could be used to construct a Python socket object from the +/// file descriptor. +/// +/// We use the standard \c sockaddr structure to represent endpoints. +/// +/// Socket session data is an opaque memory region of an arbitrary length +/// (possibly with some reasonable upper limit). +/// +/// To forward a socket session between processes, we use connected UNIX +/// domain sockets established between the processes. The file descriptor +/// will be forwarded through the sockets as an ancillary data item of +/// type \c SCM_RIGHTS. Other elements of the session will be transferred +/// as normal data over the connection. +/// +/// We provide three classes to help applications forward socket sessions: +/// \c SocketSessionForwarder is the sender of the UNIX domain connection, +/// while \c SocketSessionReceiver is the receiver (this interface assumes +/// one direction of forwarding); \c SocketSession represents a single +/// socket session. +/// +/// \c SocketSessionForwarder and \c SocketSessionReceiver objects use a +/// straightforward protocol to pass elements of socket sessions. +/// Once the connection is established, the forwarder object first forwards +/// the file descriptor with 1-byte dummy data. It then forwards a +/// "(socket) session header", which contains all other elements of the session +/// except the file descriptor (already forwarded) and session data. +/// The wire format of the header is as follows: +/// - The length of the header (16-bit unsigned integer) +/// - Address family +/// - Socket type +/// - Protocol +/// - Size of the local endpoint in bytes +/// - Local endpoint (a copy of the memory image of the corresponding +/// \c sockaddr) +/// - Size of the remote endpoint in bytes +/// - Remote endpoint (same as local endpoint) +/// - Size of session data in bytes +/// +/// The type of the fields is 32-bit unsigned integer unless explicitly +/// noted, and all fields are formatted in the network byte order. +/// +/// The socket session data immediately follows the session header. +/// +/// Note that the fields do not necessarily be in the network byte order +/// because they are expected to be exchanged on the same machine. Likewise, +/// integer elements such as address family do not necessarily be represented +/// as an fixed-size value (i.e., 32-bit). But fixed size fields are used +/// in order to ensure maximum portability in such a (rare) case where the +/// forwarder and the receiver are built with different compilers that have +/// different definitions of \c int. Also, since \c sockaddr fields are +/// generally formatted in the network byte order, other fields are defined +/// so to be consistent. +/// +/// One basic assumption in the API of this utility is socket sessions should +/// be forwarded without blocking, thus eliminating the need for incremental +/// read/write or blocking other important services such as responding to +/// requests from the application's clients. This assumption should be held +/// as long as both the forwarder and receiver have sufficient resources +/// to handle the forwarding process since the communication is local. +/// But a forward attempt could still block if the receiver is busy (or even +/// hang up) and cannot keep up with the volume of incoming sessions. +/// +/// So, in this implementation, the forwarder uses non blocking writes to +/// forward sessions. If a write attempt could block, it immediately gives +/// up the operation with an exception. The corresponding application is +/// expected to catch it, close the connection, and perform any necessary +/// recovery for that application (that would normally be re-establish the +/// connection with a new receiver, possibly after confirming the receiving +/// side is still alive). On the other hand, the receiver implementation +/// assumes it's possible that it only receive incomplete elements of a +/// session (such as in the case where the forwarder writes part of the +/// entire session and gives up the connection). The receiver implementation +/// throws an exception when it encounters an incomplete session. Like the +/// case of the forwarder application, the receiver application is expected +/// to catch it, close the connection, and perform any necessary recovery +/// steps. +/// +/// Note that the receiver implementation uses blocking read. So it's +/// application's responsibility to ensure that there's at least some data +/// in the connection when the receiver object is requested to receive a +/// session (unless this operation can be blocking, e.g., by the use of +/// a separate thread). Also, if the forwarder implementation or application +/// is malicious or extremely buggy and intentionally sends partial session +/// and keeps the connection, the receiver could block in receiving a session. +/// In general, we assume the forwarder doesn't do intentional blocking +/// as it's a local node and is generally a module of the same (Kea) +/// system. The minimum requirement for the forwarder implementation (and +/// application) is to make sure the connection is closed once it detects +/// an error on it. Even a naive implementation that simply dies due to +/// the exception will meet this requirement. + +/// An exception indicating general errors that takes place in the +/// socket session related class objects. +/// +/// In general the errors are unusual but possible failures such as unexpected +/// connection reset, and suggest the application to close the connection and +/// (if necessary) reestablish it. +class SocketSessionError: public Exception { +public: + SocketSessionError(const char *file, size_t line, const char *what): + isc::Exception(file, line, what) {} +}; + +/// The "base" class of \c SocketSessionForwarder +/// +/// This class defines abstract interfaces of the \c SocketSessionForwarder +/// class. Although \c SocketSessionForwarder is not intended to be used in +/// a polymorphic way, it's not easy to use in tests because it will require +/// various low level network operations. So it would be useful if we +/// provide a framework for defining a fake or mock version of it. +/// An application that needs to use \c SocketSessionForwarder would actually +/// refer to this base class, and tests for the application would define +/// and use a fake version of the forwarder class. +/// +/// Normal applications are not expected to define and use their own derived +/// version of this base class, while it's not prohibited at the API level. +/// +/// See description of \c SocketSessionForwarder for the expected interface. +class BaseSocketSessionForwarder { +protected: + BaseSocketSessionForwarder() {} + +public: + virtual ~BaseSocketSessionForwarder() {} + virtual void connectToReceiver() = 0; + virtual void close() = 0; + virtual void push(int sock, int family, int type, int protocol, + const struct sockaddr& local_end, + const struct sockaddr& remote_end, + const void* data, size_t data_len) = 0; +}; + +/// The forwarder of socket sessions +/// +/// An object of this class maintains a UNIX domain socket (normally expected +/// to be connected to a \c SocketSessionReceiver object) and forwards +/// socket sessions to the receiver. +/// +/// See the description of \ref SocketSessionUtility for other details of how +/// the session forwarding works. +class SocketSessionForwarder : boost::noncopyable, + public BaseSocketSessionForwarder +{ +public: + /// The constructor. + /// + /// It's constructed with path information of the intended receiver, + /// but does not immediately establish a connection to the receiver; + /// \c connectToReceiver() must be called to establish it. These are + /// separated so that an object of class can be initialized (possibly + /// as an attribute of a higher level application class object) without + /// knowing the receiver is ready for accepting new forwarders. The + /// separate connect interface allows the object to be reused when it + /// detects connection failure and tries to re-establish it after closing + /// the failed one. + /// + /// On construction, it also installs a signal filter for SIGPIPE to + /// ignore it. Since this class uses a stream-type connected UNIX domain + /// socket, if the receiver (abruptly) closes the connection a subsequent + /// write operation on the socket would trigger a SIGPIPE signal, which + /// kills the caller process by default. This behavior would be + /// undesirable in many cases, so this implementation always disables + /// the signal. + /// + /// This approach has some drawbacks, however; first, since signal handling + /// is process (or thread) wide, ignoring it may not what the application + /// wants. On the other hand, if the application changes how the signal is + /// handled after instantiating this class, the new behavior affects the + /// class operation. Secondly, even if ignoring the signal is the desired + /// operation, it's a waste to set the filter every time this class object + /// is constructed. It's sufficient to do it once. We still adopt this + /// behavior based on the observation that in most cases applications would + /// like to ignore SIGPIPE (or simply doesn't care about it) and that this + /// class is not instantiated so often (so the wasteful setting overhead + /// should be marginal). On the other hand, doing it every time is + /// beneficial if the application is threaded and different threads + /// create different forwarder objects (and if signals work per thread). + /// + /// \exception SocketSessionError \c unix_file is invalid as a path name + /// of a UNIX domain socket. + /// \exception Unexpected Error in setting a filter for SIGPIPE (see above) + /// \exception std::bad_alloc resource allocation failure + /// + /// \param unix_file Path name of the receiver. + explicit SocketSessionForwarder(const std::string& unix_file); + + /// The destructor. + /// + /// If a connection has been established, it's automatically closed in + /// the destructor. + virtual ~SocketSessionForwarder(); + + /// Establish a connection to the receiver. + /// + /// This method establishes a connection to the receiver at the path + /// given on construction. It makes the underlying UNIX domain socket + /// non blocking, so this method (or subsequent \c push() calls) does not + /// block. + /// + /// \exception BadValue The method is called while an already + /// established connection is still active. + /// \exception SocketSessionError A system error in socket operation. + virtual void connectToReceiver(); + + /// Close the connection to the receiver. + /// + /// The connection must have been established by \c connectToReceiver(). + /// As long as it's met this method is exception free. + /// + /// \exception BadValue The connection hasn't been established. + virtual void close(); + + /// Forward a socket session to the receiver. + /// + /// This method takes a set of parameters that represent a single socket + /// session, renders them in the "wire" format according to the internal + /// protocol (see \ref SocketSessionUtility) and forwards them to + /// the receiver through the UNIX domain connection. + /// + /// The connection must have been established by \c connectToReceiver(). + /// + /// For simplicity and for the convenience of detecting application + /// errors, this method imposes some restrictions on the parameters: + /// - Socket family must be either \c AF_INET or \c AF_INET6 + /// - The address family (\c sa_family) member of the local and remote + /// end points must be equal to the \c family parameter + /// - Socket session data must not be empty (\c data_len must not be 0 + /// and \c data must not be NULL) + /// - Data length must not exceed 65535 + /// These are not architectural limitation, and might be loosened in + /// future versions as we see the need for flexibility. + /// + /// Since the underlying UNIX domain socket is non blocking + /// (see the description for the constructor), a call to this method + /// should either return immediately or result in exception (in case of + /// "would block"). + /// + /// \exception BadValue The method is called before establishing a + /// connection or given parameters are invalid. + /// \exception SocketSessionError A system error in socket operation, + /// including the case where the write operation would block. + /// + /// \param sock The socket file descriptor + /// \param family The address family (such as AF_INET6) of the socket + /// \param type The socket type (such as SOCK_DGRAM) of the socket + /// \param protocol The transport protocol (such as IPPROTO_UDP) of the + /// socket + /// \param local_end The local end point of the session in the form of + /// \c sockaddr. + /// \param remote_end The remote end point of the session in the form of + /// \c sockaddr. + /// \param data A pointer to the beginning of the memory region for the + /// session data + /// \param data_len The size of the session data in bytes. + virtual void push(int sock, int family, int type, int protocol, + const struct sockaddr& local_end, + const struct sockaddr& remote_end, + const void* data, size_t data_len); + +private: + struct ForwarderImpl; + ForwarderImpl* impl_; +}; + +/// Socket session object. +/// +/// The \c SocketSession class provides a convenient encapsulation +/// for the notion of a socket session. It's instantiated with straightforward +/// parameters corresponding to a socket session, and provides read only +/// accessors to the parameters to ensure data integrity. +/// +/// In the initial design and implementation it's only used as a return type +/// of \c SocketSessionReceiver::pop(), but it could also be used by +/// the \c SocketSessionForwarder class or for other purposes. +/// +/// It is assumed that the original owner of a \c SocketSession object +/// (e.g. a class or a function that constructs it) is responsible for validity +/// of the data passed to the object. See the description of +/// \c SocketSessionReceiver::pop() for the specific case of that usage. +class SocketSession { +public: + /// The constructor. + /// + /// This is a trivial constructor, taking a straightforward representation + /// of session parameters and storing them internally to ensure integrity. + /// + /// As long as the given parameters are valid it never throws an exception. + /// + /// \exception BadValue Given parameters don't meet the requirement + /// (see the parameter descriptions). + /// + /// \param sock The socket file descriptor + /// \param family The address family (such as AF_INET6) of the socket + /// \param type The socket type (such as SOCK_DGRAM) of the socket + /// \param protocol The transport protocol (such as IPPROTO_UDP) of the + /// socket. + /// \param local_end The local end point of the session in the form of + /// \c sockaddr. Must not be NULL. + /// \param remote_end The remote end point of the session in the form of + /// \c sockaddr. Must not be NULL. + /// \param data A pointer to the beginning of the memory region for the + /// session data. Must not be NULL, and the subsequent \c data_len bytes + /// must be valid. + /// \param data_len The size of the session data in bytes. Must not be 0. + SocketSession(int sock, int family, int type, int protocol, + const sockaddr* local_end, const sockaddr* remote_end, + const void* data, size_t data_len); + + /// Return the socket file descriptor. + int getSocket() const { return (sock_); } + + /// Return the address family (such as AF_INET6) of the socket. + int getFamily() const { return (family_); } + + /// Return the socket type (such as SOCK_DGRAM) of the socket. + int getType() const { return (type_); } + + /// Return the transport protocol (such as IPPROTO_UDP) of the socket. + int getProtocol() const { return (protocol_); } + + /// Return the local end point of the session in the form of \c sockaddr. + const sockaddr& getLocalEndpoint() const { return (*local_end_); } + + /// Return the remote end point of the session in the form of \c sockaddr. + const sockaddr& getRemoteEndpoint() const { return (*remote_end_); } + + /// Return a pointer to the beginning of the memory region for the session + /// data. + /// + /// In the current implementation it should never be NULL, and the region + /// of the size returned by \c getDataLength() is expected to be valid. + const void* getData() const { return (data_); } + + /// Return the size of the session data in bytes. + /// + /// In the current implementation it should be always larger than 0. + size_t getDataLength() const { return (data_len_); } + +private: + const int sock_; + const int family_; + const int type_; + const int protocol_; + const sockaddr* local_end_; + const sockaddr* remote_end_; + const void* const data_; + const size_t data_len_; +}; + +/// The receiver of socket sessions +/// +/// An object of this class holds a UNIX domain socket for an +/// <em>established connection</em>, receives socket sessions from +/// the remote forwarder, and provides the session to the application +/// in the form of a \c SocketSession object. +/// +/// Note that this class is instantiated with an already connected socket; +/// it's not a listening socket that is accepting connection requests from +/// forwarders. It's application's responsibility to create the listening +/// socket, listen on it and accept connections. Once the connection is +/// established, the application would construct a \c SocketSessionReceiver +/// object with the socket for the newly established connection. +/// This behavior is based on the design decision that the application should +/// decide when it performs (possibly) blocking operations (see \ref +/// SocketSessionUtility for more details). +/// +/// See the description of \ref SocketSessionUtility for other details of how +/// the session forwarding works. +class SocketSessionReceiver : boost::noncopyable { +public: + /// The constructor. + /// + /// \exception SocketSessionError Any error on an operation that is + /// performed on the given socket as part of initialization. + /// \exception std::bad_alloc Resource allocation failure + /// + /// \param fd A UNIX domain socket for an established connection with + /// a forwarder. + explicit SocketSessionReceiver(int fd); + + /// The destructor. + /// + /// The destructor does \c not close the socket given on construction. + /// It's up to the application what to do with it (note that the + /// application would have to maintain the socket itself for detecting + /// the existence of a new socket session asynchronously). + ~SocketSessionReceiver(); + + /// Receive a socket session from the forwarder. + /// + /// This method receives wire-format data (see \ref SocketSessionUtility) + /// for a socket session on the UNIX domain socket, performs some + /// validation on the data, and returns the session information in the + /// form of a \c SocketSession object. + /// + /// The returned SocketSession object is valid only until the next time + /// this method is called or until the \c SocketSessionReceiver object is + /// destroyed. + /// + /// The caller is responsible for closing the received socket (whose + /// file descriptor is accessible via \c SocketSession::getSocket()). + /// If the caller copies the returned \c SocketSession object, it's also + /// responsible for making sure the descriptor is closed at most once. + /// On the other hand, the caller is not responsible for freeing the + /// socket session data (accessible via \c SocketSession::getData()); + /// the \c SocketSessionReceiver object will clean it up automatically. + /// + /// It ensures the following: + /// - The address family is either \c AF_INET or \c AF_INET6 + /// - The address family (\c sa_family) member of the local and remote + /// end points must be equal to the \c family parameter + /// - The socket session data is not empty and does not exceed 65535 + /// bytes. + /// If the validation fails or an unexpected system error happens + /// (including a connection close in the meddle of reception), it throws + /// an SocketSessionError exception. When this happens, it's very + /// unlikely that a subsequent call to this method succeeds, so in reality + /// the application is expected to destruct it and close the socket in + /// such a case. + /// + /// \exception SocketSessionError Invalid data is received or a system + /// error on socket operation happens. + /// \exception std::bad_alloc Resource allocation failure + /// + /// \return A \c SocketSession object corresponding to the extracted + /// socket session. + SocketSession pop(); + +private: + struct ReceiverImpl; + ReceiverImpl* impl_; +}; + +} +} +} + +#endif // SOCKETSESSION_H + +// Local Variables: +// mode: c++ +// End: |