diff options
Diffstat (limited to '')
-rw-r--r-- | lib/tsocket/doxy.config | 1538 | ||||
-rw-r--r-- | lib/tsocket/tests/socketpair_tcp.c | 89 | ||||
-rw-r--r-- | lib/tsocket/tests/socketpair_tcp.h | 29 | ||||
-rw-r--r-- | lib/tsocket/tests/test_bsd_addr.c | 369 | ||||
-rw-r--r-- | lib/tsocket/tests/test_tstream.c | 517 | ||||
-rw-r--r-- | lib/tsocket/tsocket.c | 812 | ||||
-rw-r--r-- | lib/tsocket/tsocket.h | 1319 | ||||
-rw-r--r-- | lib/tsocket/tsocket_bsd.c | 2845 | ||||
-rw-r--r-- | lib/tsocket/tsocket_guide.txt | 481 | ||||
-rw-r--r-- | lib/tsocket/tsocket_helpers.c | 559 | ||||
-rw-r--r-- | lib/tsocket/tsocket_internal.h | 144 | ||||
-rw-r--r-- | lib/tsocket/wscript | 36 |
12 files changed, 8738 insertions, 0 deletions
diff --git a/lib/tsocket/doxy.config b/lib/tsocket/doxy.config new file mode 100644 index 0000000..584ae73 --- /dev/null +++ b/lib/tsocket/doxy.config @@ -0,0 +1,1538 @@ +# Doxyfile 1.6.1 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = tsocket + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = 0.1 + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = doc + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, +# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, +# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it parses. +# With this tag you can assign which parser to use for a given extension. +# Doxygen has a built-in mapping, but you can override or extend it using this tag. +# The format is ext=language, where ext is a file extension, and language is one of +# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, +# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), +# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate getter +# and setter methods for a property. Setting this option to YES (the default) +# will make doxygen to replace the get and set methods by a property in the +# documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penality. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will rougly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols + +SYMBOL_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = NO + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespace are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = YES + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = YES + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. +# This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command <command> <input-file>, where <command> is the value of +# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by +# doxygen. The layout file controls the global structure of the generated output files +# in an output format independent way. The create the layout file that represents +# doxygen's defaults, run doxygen with the -l option. You can optionally specify a +# file name after the option, if omitted DoxygenLayout.xml will be used as the name +# of the layout file. + +LAYOUT_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 + +FILE_PATTERNS = *.cpp \ + *.cc \ + *.c \ + *.h \ + *.hh \ + *.hpp \ + *.dox + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = */.git/* \ + */.svn/* \ + */cmake/* \ + */build/* + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command <filter> <input-file>, where <filter> +# is the value of the INPUT_FILTER tag, and <input-file> is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. +# If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. +# Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. +# The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. +# Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# If the HTML_FOOTER_DESCRIPTION tag is set to YES, Doxygen will +# add generated date, project name and doxygen version to HTML footer. + +HTML_FOOTER_DESCRIPTION= NO + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. For this to work a browser that supports +# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox +# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). + +HTML_DYNAMIC_SECTIONS = NO + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER +# are set, an additional index file will be generated that can be used as input for +# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated +# HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. +# For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see +# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">Qt Help Project / Custom Filters</a>. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's +# filter section matches. +# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">Qt Help Project / Filter Attributes</a>. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NONE + +# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, +# and Class Hierarchy pages using a tree view instead of an ordered list. + +USE_INLINE_TREES = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# When the SEARCHENGINE tag is enable doxygen will generate a search box for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP) or Qt help (GENERATE_QHP) +# there is already a search function so this one should typically +# be disabled. + +SEARCHENGINE = NO + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = YES + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = YES + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. +# This is useful +# if you want to understand what is going on. +# On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = DOXYGEN + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# By default doxygen will write a font called FreeSans.ttf to the output +# directory and reference it in all dot files that doxygen generates. This +# font does not include all possible unicode characters however, so when you need +# these (or just want a differently looking font) you can specify the font name +# using DOT_FONTNAME. You need need to make sure dot is able to find the font, +# which can be done by putting it in a standard location or by setting the +# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory +# containing the font. + +DOT_FONTNAME = FreeSans + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the output directory to look for the +# FreeSans.ttf font (which doxygen will put there itself). If you specify a +# different font using DOT_FONTNAME you can set the path where dot +# can find it using this tag. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = YES + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/lib/tsocket/tests/socketpair_tcp.c b/lib/tsocket/tests/socketpair_tcp.c new file mode 100644 index 0000000..251b8bc --- /dev/null +++ b/lib/tsocket/tests/socketpair_tcp.c @@ -0,0 +1,89 @@ +/* + Unix SMB/CIFS implementation. + Samba utility functions + Copyright (C) Andrew Tridgell 1992-1998 + Copyright (C) Tim Potter 2000-2001 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "system/network.h" +#include "socketpair_tcp.h" + +/******************************************************************* +this is like socketpair but uses tcp. It is used by the Samba +regression test code +The function guarantees that nobody else can attach to the socket, +or if they do that this function fails and the socket gets closed +returns 0 on success, -1 on failure +the resulting file descriptors are symmetrical + ******************************************************************/ +int socketpair_tcp(int fd[2]) +{ + int listener; + struct sockaddr_in sock; + struct sockaddr_in sock2; + socklen_t socklen = sizeof(sock); + int connect_done = 0; + + fd[0] = fd[1] = listener = -1; + + memset(&sock, 0, sizeof(sock)); + + if ((listener = socket(PF_INET, SOCK_STREAM, 0)) == -1) goto failed; + + memset(&sock2, 0, sizeof(sock2)); +#ifdef HAVE_SOCK_SIN_LEN + sock2.sin_len = sizeof(sock2); +#endif + sock2.sin_family = PF_INET; + + if (bind(listener, (struct sockaddr *)&sock2, sizeof(sock2)) != 0) goto failed; + + if (listen(listener, 1) != 0) goto failed; + + if (getsockname(listener, (struct sockaddr *)&sock, &socklen) != 0) goto failed; + + if ((fd[1] = socket(PF_INET, SOCK_STREAM, 0)) == -1) goto failed; + + set_blocking(fd[1], 0); + + sock.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + + if (connect(fd[1], (struct sockaddr *)&sock, socklen) == -1) { + if (errno != EINPROGRESS) goto failed; + } else { + connect_done = 1; + } + + if ((fd[0] = accept(listener, (struct sockaddr *)&sock, &socklen)) == -1) goto failed; + + if (connect_done == 0) { + if (connect(fd[1], (struct sockaddr *)&sock, socklen) != 0 + && errno != EISCONN) goto failed; + } + close(listener); + + set_blocking(fd[1], 1); + + /* all OK! */ + return 0; + + failed: + if (fd[0] != -1) close(fd[0]); + if (fd[1] != -1) close(fd[1]); + if (listener != -1) close(listener); + return -1; +} diff --git a/lib/tsocket/tests/socketpair_tcp.h b/lib/tsocket/tests/socketpair_tcp.h new file mode 100644 index 0000000..dbee4ef --- /dev/null +++ b/lib/tsocket/tests/socketpair_tcp.h @@ -0,0 +1,29 @@ +/* + Unix SMB/CIFS implementation. + Samba utility functions + Copyright (C) Andrew Tridgell 1992-1998 + Copyright (C) Tim Potter 2000-2001 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/******************************************************************* +this is like socketpair but uses tcp. It is used by the Samba +regression test code +The function guarantees that nobody else can attach to the socket, +or if they do that this function fails and the socket gets closed +returns 0 on success, -1 on failure +the resulting file descriptors are symmetrical + ******************************************************************/ +int socketpair_tcp(int fd[2]); diff --git a/lib/tsocket/tests/test_bsd_addr.c b/lib/tsocket/tests/test_bsd_addr.c new file mode 100644 index 0000000..ac6e798 --- /dev/null +++ b/lib/tsocket/tests/test_bsd_addr.c @@ -0,0 +1,369 @@ +/* + * Unix SMB/CIFS implementation. + * + * Copyright (C) 2021 Uri Simchoni <uri@samba.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <errno.h> +#include <setjmp.h> +#include <stdarg.h> +#include <stddef.h> +#include <stdint.h> + +#include <cmocka.h> +#include <tsocket.h> + +static int setup(void **state) +{ + TALLOC_CTX *mem_ctx = talloc_new(NULL); + + assert_non_null(mem_ctx); + *state = mem_ctx; + + return 0; +} + +static int teardown(void **state) +{ + TALLOC_CTX *mem_ctx = *state; + TALLOC_FREE(mem_ctx); + + return 0; +} + +static void test_address_inet_from_strings(void **state) +{ + int rc = 0; + int save_errno; + TALLOC_CTX *mem_ctx = *state; + struct tsocket_address *addr = NULL; + char *addr_s = NULL; + + /* + * Unspecified IP family, given an IPv4 address + */ + rc = tsocket_address_inet_from_strings(mem_ctx, "ip", "1.2.3.4", 1234, + &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv4:1.2.3.4:1234"); + assert_true(tsocket_address_is_inet(addr, "ip")); + assert_true(tsocket_address_is_inet(addr, "ipv4")); + assert_false(tsocket_address_is_inet(addr, "ipv6")); + assert_int_equal(tsocket_address_inet_port(addr), 1234); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * Expecting IPv4, given an IPv4 address + */ + rc = tsocket_address_inet_from_strings(mem_ctx, "ipv4", "1.2.3.4", 1234, + &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv4:1.2.3.4:1234"); + assert_true(tsocket_address_is_inet(addr, "ip")); + assert_true(tsocket_address_is_inet(addr, "ipv4")); + assert_false(tsocket_address_is_inet(addr, "ipv6")); + assert_int_equal(tsocket_address_inet_port(addr), 1234); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * Expecting IPv6, given an IPv4 address + */ + errno = 0; + rc = tsocket_address_inet_from_strings(mem_ctx, "ipv6", "1.2.3.4", 1234, + &addr); + save_errno = errno; + assert_int_equal(rc, -1); + assert_int_not_equal(save_errno, 0); + assert_null(addr); + + /* + * Unspecified IP family, given an IPv6 address + */ + rc = tsocket_address_inet_from_strings(mem_ctx, "ip", "2001::1", 1234, + &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv6:2001::1:1234"); + assert_true(tsocket_address_is_inet(addr, "ip")); + assert_false(tsocket_address_is_inet(addr, "ipv4")); + assert_true(tsocket_address_is_inet(addr, "ipv6")); + assert_int_equal(tsocket_address_inet_port(addr), 1234); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * Expecting IPv4, given an IPv6 address + */ + errno = 0; + rc = tsocket_address_inet_from_strings(mem_ctx, "ipv4", "2001::1", 1234, + &addr); + save_errno = errno; + assert_int_equal(rc, -1); + assert_int_not_equal(save_errno, 0); + assert_null(addr); + + /* + * expecting IPv6, given an IPv6 address + */ + rc = tsocket_address_inet_from_strings(mem_ctx, "ipv6", "2001::1", 1234, + &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv6:2001::1:1234"); + assert_true(tsocket_address_is_inet(addr, "ip")); + assert_false(tsocket_address_is_inet(addr, "ipv4")); + assert_true(tsocket_address_is_inet(addr, "ipv6")); + assert_int_equal(tsocket_address_inet_port(addr), 1234); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * Unspecified IP family, given an illegal address + */ + errno = 0; + rc = tsocket_address_inet_from_strings(mem_ctx, "ip", "localhost", 1234, + &addr); + save_errno = errno; + assert_int_equal(rc, -1); + assert_int_not_equal(save_errno, 0); + assert_null(addr); + + /* + * Illegal IP family + */ + errno = 0; + rc = tsocket_address_inet_from_strings(mem_ctx, "ipx", "1.2.3.4", 1234, + &addr); + save_errno = errno; + assert_int_equal(rc, -1); + assert_int_not_equal(save_errno, 0); + assert_null(addr); + + /* + * Unspecified IP family, given NULL, verify it returns something + */ + rc = tsocket_address_inet_from_strings(mem_ctx, "ip", NULL, 1234, + &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + TALLOC_FREE(addr); + + /* + * IPv4, given NULL, verify it returns 0.0.0.0 + */ + rc = tsocket_address_inet_from_strings(mem_ctx, "ipv4", NULL, 1234, + &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv4:0.0.0.0:1234"); + assert_true(tsocket_address_is_inet(addr, "ip")); + assert_true(tsocket_address_is_inet(addr, "ipv4")); + assert_false(tsocket_address_is_inet(addr, "ipv6")); + assert_int_equal(tsocket_address_inet_port(addr), 1234); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * IPv6, given NULL, verify it returns :: + */ + rc = tsocket_address_inet_from_strings(mem_ctx, "ipv6", NULL, 1234, + &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv6::::1234"); + assert_true(tsocket_address_is_inet(addr, "ip")); + assert_false(tsocket_address_is_inet(addr, "ipv4")); + assert_true(tsocket_address_is_inet(addr, "ipv6")); + assert_int_equal(tsocket_address_inet_port(addr), 1234); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); +} + +static void test_address_inet_from_hostport_strings(void **state) +{ + int rc = 0; + int save_errno; + TALLOC_CTX *mem_ctx = *state; + struct tsocket_address *addr = NULL; + char *addr_s = NULL; + + /* + * IPv4 host:port + */ + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ip", "1.2.3.4:5678", 1234, &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv4:1.2.3.4:5678"); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * IPv4 host + */ + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ip", "1.2.3.4", 1234, &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv4:1.2.3.4:1234"); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * IPv6 [host]:port + */ + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ip", "[2001::1]:5678", 1234, &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv6:2001::1:5678"); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * IPv6 [host] + */ + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ip", "[2001::1]", 1234, &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv6:2001::1:1234"); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * IPv6 host + */ + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ip", "2001::1", 1234, &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv6:2001::1:1234"); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * Given NULL, verify it returns something + */ + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ipv6", NULL, 1234, &addr); + assert_return_code(rc, errno); + assert_non_null(addr); + addr_s = tsocket_address_string(addr, mem_ctx); + assert_non_null(addr_s); + assert_string_equal(addr_s, "ipv6::::1234"); + TALLOC_FREE(addr); + TALLOC_FREE(addr_s); + + /* + * [host]grarbage + */ + errno = 0; + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ip", "[2001::1]garbage", 1234, &addr); + save_errno = errno; + assert_int_equal(rc, -1); + assert_int_not_equal(save_errno, 0); + assert_null(addr); + + /* + * [host]:grarbage + */ + errno = 0; + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ip", "[2001::1]:garbage", 1234, &addr); + save_errno = errno; + assert_int_equal(rc, -1); + assert_int_not_equal(save_errno, 0); + assert_null(addr); + + /* + * host:grarbage + */ + errno = 0; + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ip", "1.2.3.4:garbage", 1234, &addr); + save_errno = errno; + assert_int_equal(rc, -1); + assert_int_not_equal(save_errno, 0); + assert_null(addr); + + /* + * [host]:<port-too-large> + */ + errno = 0; + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ip", "[2001::1]:100000", 1234, &addr); + save_errno = errno; + assert_int_equal(rc, -1); + assert_int_not_equal(save_errno, 0); + assert_null(addr); + + /* + * host:<port-too-large> + */ + errno = 0; + rc = tsocket_address_inet_from_hostport_strings( + mem_ctx, "ip", "1.2.3.4:100000", 1234, &addr); + save_errno = errno; + assert_int_equal(rc, -1); + assert_int_not_equal(save_errno, 0); + assert_null(addr); +} + +int main(int argc, char *argv[]) +{ + int rc; + const struct CMUnitTest tests[] = { + cmocka_unit_test(test_address_inet_from_strings), + cmocka_unit_test(test_address_inet_from_hostport_strings), + }; + + if (argc == 2) { + cmocka_set_test_filter(argv[1]); + } + cmocka_set_message_output(CM_OUTPUT_SUBUNIT); + + rc = cmocka_run_group_tests(tests, setup, teardown); + + return rc; +} diff --git a/lib/tsocket/tests/test_tstream.c b/lib/tsocket/tests/test_tstream.c new file mode 100644 index 0000000..47008bb --- /dev/null +++ b/lib/tsocket/tests/test_tstream.c @@ -0,0 +1,517 @@ +/* + * Unix SMB/CIFS implementation. + * + * Copyright (C) 2022 Andrew Bartlett <abartlet@samba.org> + * Copyright (C) 2021 Andreas Schneider <asn@samba.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include <stdarg.h> +#include <stddef.h> +#include <stdint.h> +#include <setjmp.h> +#include <cmocka.h> +#include "includes.h" +#include "system/network.h" +#include "socketpair_tcp.h" +#include "tsocket.h" + +enum socket_pair_selector { + SOCKET_SERVER = 0, + SOCKET_CLIENT = 1, +}; + +struct socket_pair { + struct tevent_context *ev; + int socket_server; + int socket_client; + + /* for tstream tests */ + int rc; + int sys_errno; + int expected_errno; + struct timeval endtime; + size_t max_loops; + size_t num_loops; +}; + +/* If this is too large, we get EPIPE rather than EAGAIN */ +static const uint8_t TEST_STRING[128] = { 0 }; + +static int sigpipe_setup(void **state) +{ + BlockSignals(true, SIGPIPE); + return 0; +} + +static int setup_socketpair_tcp_context(void **state) +{ + int fd[2]; + struct socket_pair *sp = talloc_zero(NULL, struct socket_pair); + assert_non_null(sp); + + /* Set up a socketpair over TCP to test with */ + assert_return_code(socketpair_tcp(fd), errno); + + sp->socket_server = fd[SOCKET_SERVER]; + sp->socket_client = fd[SOCKET_CLIENT]; + + sp->ev = tevent_context_init(sp); + assert_non_null(sp->ev); + + *state = sp; + return 0; +} + +static int setup_socketpair_context(void **state) +{ + int fd[2]; + struct socket_pair *sp = talloc_zero(NULL, struct socket_pair); + assert_non_null(sp); + + /* Set up a socketpair over TCP to test with */ + assert_return_code(socketpair(AF_UNIX, SOCK_STREAM, 0, fd), errno); + + sp->socket_server = fd[SOCKET_SERVER]; + sp->socket_client = fd[SOCKET_CLIENT]; + + sp->ev = tevent_context_init(sp); + assert_non_null(sp->ev); + + *state = sp; + return 0; +} + +static int teardown_socketpair_context(void **state) +{ + struct socket_pair *sp = *state; + struct socket_pair sp_save = *sp; + + TALLOC_FREE(sp); + + /* + * Close these after the TALLOC_FREE() to allow clean shutdown + * of epoll() in tstream + */ + if (sp_save.socket_client != -1) { + close(sp_save.socket_client); + } + if (sp_save.socket_server != -1) { + close(sp_save.socket_server); + } + return 0; +} + + +/* Test socket behaviour */ +static void test_simple_socketpair(void **state) { + + struct socket_pair *sp = *state; + + char buf[sizeof(TEST_STRING)]; + + assert_int_equal(write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)), + sizeof(TEST_STRING)); + assert_int_equal(read(sp->socket_client, buf, sizeof(buf)), + sizeof(buf)); + + +} + +/* Test socket behaviour */ +static void test_read_client_after_close_server_socket(void **state) { + + struct socket_pair *sp = *state; + int rc; + char buf[sizeof(TEST_STRING)]; + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_return_code(rc, errno); + assert_int_equal(rc, sizeof(TEST_STRING)); + + assert_return_code(close(sp->socket_server), 0); + + rc = read(sp->socket_client, buf, sizeof(buf)); + + assert_return_code(rc, errno); + assert_int_equal(rc, sizeof(buf)); +} + +static void test_write_server_after_close_client_socket(void **state) { + + struct socket_pair *sp = *state; + int rc; + + assert_return_code(close(sp->socket_client), 0); + sp->socket_client = -1; + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_return_code(rc, errno); + assert_int_equal(rc, sizeof(TEST_STRING)); +} + +static void test_fill_socket(int sock) +{ + size_t num_busy = 0; + int rc; + + while (true) { + rc = write(sock, TEST_STRING, sizeof(TEST_STRING)); + if (rc == -1 && errno == EAGAIN) { + /* + * This makes sure we write until we get a whole second + * only with EAGAIN every 50 ms (20 times) + * + * Otherwise the tests are not reliable... + */ + num_busy++; + if (num_busy > 20) { + break; + } + smb_msleep(50); + continue; + } + /* try again next time */ + num_busy = 0; + } + + assert_int_equal(rc, -1); + assert_int_equal(errno, EAGAIN); +} + +static void test_big_write_server(void **state) { + + struct socket_pair *sp = *state; + int rc; + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_return_code(rc, errno); + assert_int_equal(rc, sizeof(TEST_STRING)); + + rc = set_blocking(sp->socket_server, 0); + assert_return_code(rc, errno); + + test_fill_socket(sp->socket_server); +} + +static void test_big_write_server_close_write(void **state) { + + struct socket_pair *sp = *state; + int rc; + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_return_code(rc, errno); + assert_int_equal(rc, sizeof(TEST_STRING)); + + rc = set_blocking(sp->socket_server, 0); + assert_return_code(rc, errno); + + test_fill_socket(sp->socket_server); + + assert_return_code(close(sp->socket_client), 0); + sp->socket_client = -1; + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_int_equal(errno, ECONNRESET); + +} + +static void test_big_write_server_shutdown_wr_write(void **state) { + + struct socket_pair *sp = *state; + int rc; + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_return_code(rc, errno); + assert_int_equal(rc, sizeof(TEST_STRING)); + + rc = set_blocking(sp->socket_server, 0); + assert_return_code(rc, errno); + + test_fill_socket(sp->socket_server); + + assert_return_code(shutdown(sp->socket_client, SHUT_WR), 0); + sp->socket_client = -1; + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_int_equal(rc, -1); + assert_int_equal(errno, EAGAIN); +} + +static void test_big_write_server_shutdown_rd_write(void **state) { + + struct socket_pair *sp = *state; + int rc; + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_return_code(rc, errno); + assert_int_equal(rc, sizeof(TEST_STRING)); + + rc = set_blocking(sp->socket_server, 0); + assert_return_code(rc, errno); + + test_fill_socket(sp->socket_server); + + assert_return_code(shutdown(sp->socket_client, SHUT_RD), 0); + sp->socket_client = -1; + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_int_equal(rc, -1); + assert_int_equal(errno, EAGAIN); +} + +static void test_call_writev_done(struct tevent_req *subreq) +{ + struct socket_pair *sp = + tevent_req_callback_data(subreq, + struct socket_pair); + int rc; + + rc = tstream_writev_recv(subreq, &sp->sys_errno); + TALLOC_FREE(subreq); + + sp->rc = rc; +} + +static void test_tstream_server_spin_client_shutdown(struct socket_pair *sp) +{ + int rc; + + rc = shutdown(sp->socket_client, SHUT_WR); + assert_return_code(rc, errno); + /* + * It should only take a few additional loop to realise that this socket is + * in CLOSE_WAIT + */ + sp->max_loops = sp->num_loops + 2; + sp->expected_errno = ECONNRESET; +} + +static void test_tstream_server_spin_client_write(struct socket_pair *sp) +{ + int rc; + int timeout = 5000; + + sp->endtime = timeval_current_ofs_msec(timeout); + + rc = write(sp->socket_client, TEST_STRING, sizeof(TEST_STRING)); + assert_return_code(rc, errno); + sp->expected_errno = ETIMEDOUT; +} + +static void test_tstream_server_spin_client_tcp_user_timeout(struct socket_pair *sp) +{ + int rc; + int timeout = 5000; + + rc = setsockopt(sp->socket_server, IPPROTO_TCP, TCP_USER_TIMEOUT, &timeout, sizeof(timeout)); + assert_return_code(rc, errno); + + rc = write(sp->socket_client, TEST_STRING, sizeof(TEST_STRING)); + assert_return_code(rc, errno); + sp->expected_errno = ETIMEDOUT; + sp->max_loops = 30; +} + +static void test_tstream_server_spin_client_both_timer(struct tevent_context *ev, + struct tevent_timer *te, + struct timeval current_time, + void *private_data) +{ + struct socket_pair *sp = + talloc_get_type_abort(private_data, + struct socket_pair); + + test_tstream_server_spin_client_shutdown(sp); +} + +static void test_tstream_server_spin_client_both(struct socket_pair *sp) +{ + struct tevent_timer *te = NULL; + struct timeval endtime; + + test_tstream_server_spin_client_write(sp); + + endtime = timeval_current_ofs_msec(2500); + + te = tevent_add_timer(sp->ev, + sp, + endtime, + test_tstream_server_spin_client_both_timer, + sp); + assert_non_null(te); + sp->expected_errno = ENXIO; +} + +static void test_tstream_server_spin(struct socket_pair *sp, + void (*client_fn)(struct socket_pair *sp)) +{ + struct tstream_context *stream = NULL; + struct tevent_req *req = NULL; + struct iovec iov; + int rc; + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_return_code(rc, errno); + assert_int_equal(rc, sizeof(TEST_STRING)); + + rc = set_blocking(sp->socket_server, 0); + assert_return_code(rc, errno); + + test_fill_socket(sp->socket_server); + + /* + * by default we don't expect more then 2 loop iterations + * for a timeout of 5 seconds. + */ + sp->max_loops = 10; + + client_fn(sp); + + rc = write(sp->socket_server, TEST_STRING, sizeof(TEST_STRING)); + assert_int_equal(rc, -1); + assert_int_equal(errno, EAGAIN); + + /* OK, so we now know the socket is in CLOSE_WAIT */ + + rc = tstream_bsd_existing_socket(sp->ev, sp->socket_server, &stream); + assert_return_code(rc, errno); + sp->socket_server = -1; + + iov.iov_base = discard_const_p(char, TEST_STRING); + iov.iov_len = sizeof(TEST_STRING); + + req = tstream_writev_send(stream, sp->ev, stream, &iov, 1); + assert_non_null(req); + if (!timeval_is_zero(&sp->endtime)) { + assert_true(tevent_req_set_endtime(req, sp->ev, sp->endtime)); + } + tevent_req_set_callback(req, test_call_writev_done, sp); + + while (tevent_req_is_in_progress(req)) { + if (sp->num_loops >= sp->max_loops) { + assert_int_not_equal(sp->num_loops, sp->max_loops); + assert_int_equal(sp->num_loops, sp->max_loops); + } + sp->num_loops += 1; + + rc = tevent_loop_once(sp->ev); + assert_int_equal(rc, 0); + } + + assert_int_equal(sp->rc, -1); + assert_int_equal(sp->sys_errno, sp->expected_errno); + return; +} + +/* + * We need two names to run this with the two different setup + * routines + */ +static void test_tstream_disconnected_tcp_client_spin(void **state) +{ + struct socket_pair *sp = *state; + test_tstream_server_spin(sp, test_tstream_server_spin_client_shutdown); +} + +static void test_tstream_disconnected_unix_client_spin(void **state) +{ + struct socket_pair *sp = *state; + test_tstream_server_spin(sp, test_tstream_server_spin_client_shutdown); +} + +static void test_tstream_more_tcp_client_spin(void **state) +{ + struct socket_pair *sp = *state; + test_tstream_server_spin(sp, test_tstream_server_spin_client_write); +} + +static void test_tstream_more_unix_client_spin(void **state) +{ + struct socket_pair *sp = *state; + test_tstream_server_spin(sp, test_tstream_server_spin_client_write); +} + +static void test_tstream_more_disconnect_tcp_client_spin(void **state) +{ + struct socket_pair *sp = *state; + test_tstream_server_spin(sp, test_tstream_server_spin_client_both); +} + +static void test_tstream_more_disconnect_unix_client_spin(void **state) +{ + struct socket_pair *sp = *state; + test_tstream_server_spin(sp, test_tstream_server_spin_client_both); +} + +static void test_tstream_more_tcp_user_timeout_spin(void **state) +{ + struct socket_pair *sp = *state; + if (socket_wrapper_enabled()) { + skip(); + } + test_tstream_server_spin(sp, test_tstream_server_spin_client_tcp_user_timeout); +} + +int main(void) { + const struct CMUnitTest tests[] = { + cmocka_unit_test_setup_teardown(test_simple_socketpair, + setup_socketpair_tcp_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_read_client_after_close_server_socket, + setup_socketpair_tcp_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_write_server_after_close_client_socket, + setup_socketpair_tcp_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_big_write_server, + setup_socketpair_tcp_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_big_write_server_close_write, + setup_socketpair_tcp_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_big_write_server_shutdown_wr_write, + setup_socketpair_tcp_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_big_write_server_shutdown_rd_write, + setup_socketpair_tcp_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_tstream_disconnected_tcp_client_spin, + setup_socketpair_tcp_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_tstream_disconnected_unix_client_spin, + setup_socketpair_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_tstream_more_tcp_client_spin, + setup_socketpair_tcp_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_tstream_more_unix_client_spin, + setup_socketpair_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_tstream_more_disconnect_tcp_client_spin, + setup_socketpair_tcp_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_tstream_more_disconnect_unix_client_spin, + setup_socketpair_context, + teardown_socketpair_context), + cmocka_unit_test_setup_teardown(test_tstream_more_tcp_user_timeout_spin, + setup_socketpair_tcp_context, + teardown_socketpair_context), + }; + + cmocka_set_message_output(CM_OUTPUT_SUBUNIT); + + return cmocka_run_group_tests(tests, sigpipe_setup, NULL); +} diff --git a/lib/tsocket/tsocket.c b/lib/tsocket/tsocket.c new file mode 100644 index 0000000..674858d --- /dev/null +++ b/lib/tsocket/tsocket.c @@ -0,0 +1,812 @@ +/* + Unix SMB/CIFS implementation. + + Copyright (C) Stefan Metzmacher 2009 + + ** NOTE! The following LGPL license applies to the tsocket + ** library. This does NOT imply that all of Samba is released + ** under the LGPL + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see <http://www.gnu.org/licenses/>. +*/ + +#include "replace.h" +#include "system/filesys.h" +#include "tsocket.h" +#include "tsocket_internal.h" + +int tsocket_simple_int_recv(struct tevent_req *req, int *perrno) +{ + enum tevent_req_state state; + uint64_t error; + + if (!tevent_req_is_error(req, &state, &error)) { + return 0; + } + + switch (state) { + case TEVENT_REQ_NO_MEMORY: + *perrno = ENOMEM; + return -1; + case TEVENT_REQ_TIMED_OUT: + *perrno = ETIMEDOUT; + return -1; + case TEVENT_REQ_USER_ERROR: + *perrno = (int)error; + return -1; + default: + break; + } + + *perrno = EIO; + return -1; +} + +struct tsocket_address *_tsocket_address_create(TALLOC_CTX *mem_ctx, + const struct tsocket_address_ops *ops, + void *pstate, + size_t psize, + const char *type, + const char *location) +{ + void **ppstate = (void **)pstate; + struct tsocket_address *addr; + + addr = talloc_zero(mem_ctx, struct tsocket_address); + if (!addr) { + return NULL; + } + addr->ops = ops; + addr->location = location; + addr->private_data = talloc_size(addr, psize); + if (!addr->private_data) { + talloc_free(addr); + return NULL; + } + talloc_set_name_const(addr->private_data, type); + + *ppstate = addr->private_data; + return addr; +} + +char *tsocket_address_string(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx) +{ + if (!addr) { + return talloc_strdup(mem_ctx, "NULL"); + } + return addr->ops->string(addr, mem_ctx); +} + +struct tsocket_address *_tsocket_address_copy(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx, + const char *location) +{ + return addr->ops->copy(addr, mem_ctx, location); +} + +struct tdgram_context { + const char *location; + const struct tdgram_context_ops *ops; + void *private_data; + + struct tevent_req *recvfrom_req; + struct tevent_req *sendto_req; +}; + +static int tdgram_context_destructor(struct tdgram_context *dgram) +{ + if (dgram->recvfrom_req) { + tevent_req_received(dgram->recvfrom_req); + } + + if (dgram->sendto_req) { + tevent_req_received(dgram->sendto_req); + } + + return 0; +} + +struct tdgram_context *_tdgram_context_create(TALLOC_CTX *mem_ctx, + const struct tdgram_context_ops *ops, + void *pstate, + size_t psize, + const char *type, + const char *location) +{ + struct tdgram_context *dgram; + void **ppstate = (void **)pstate; + void *state; + + dgram = talloc(mem_ctx, struct tdgram_context); + if (dgram == NULL) { + return NULL; + } + dgram->location = location; + dgram->ops = ops; + dgram->recvfrom_req = NULL; + dgram->sendto_req = NULL; + + state = talloc_size(dgram, psize); + if (state == NULL) { + talloc_free(dgram); + return NULL; + } + talloc_set_name_const(state, type); + + dgram->private_data = state; + + talloc_set_destructor(dgram, tdgram_context_destructor); + + *ppstate = state; + return dgram; +} + +void *_tdgram_context_data(struct tdgram_context *dgram) +{ + return dgram->private_data; +} + +struct tdgram_recvfrom_state { + const struct tdgram_context_ops *ops; + struct tdgram_context *dgram; + uint8_t *buf; + size_t len; + struct tsocket_address *src; +}; + +static int tdgram_recvfrom_destructor(struct tdgram_recvfrom_state *state) +{ + if (state->dgram) { + state->dgram->recvfrom_req = NULL; + } + + return 0; +} + +static void tdgram_recvfrom_done(struct tevent_req *subreq); + +struct tevent_req *tdgram_recvfrom_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram) +{ + struct tevent_req *req; + struct tdgram_recvfrom_state *state; + struct tevent_req *subreq; + + req = tevent_req_create(mem_ctx, &state, + struct tdgram_recvfrom_state); + if (req == NULL) { + return NULL; + } + + state->ops = dgram->ops; + state->dgram = dgram; + state->buf = NULL; + state->len = 0; + state->src = NULL; + + if (dgram->recvfrom_req) { + tevent_req_error(req, EBUSY); + goto post; + } + dgram->recvfrom_req = req; + + talloc_set_destructor(state, tdgram_recvfrom_destructor); + + subreq = state->ops->recvfrom_send(state, ev, dgram); + if (tevent_req_nomem(subreq, req)) { + goto post; + } + tevent_req_set_callback(subreq, tdgram_recvfrom_done, req); + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tdgram_recvfrom_done(struct tevent_req *subreq) +{ + struct tevent_req *req = tevent_req_callback_data(subreq, + struct tevent_req); + struct tdgram_recvfrom_state *state = tevent_req_data(req, + struct tdgram_recvfrom_state); + ssize_t ret; + int sys_errno; + + ret = state->ops->recvfrom_recv(subreq, &sys_errno, state, + &state->buf, &state->src); + if (ret == -1) { + tevent_req_error(req, sys_errno); + return; + } + + state->len = ret; + + tevent_req_done(req); +} + +ssize_t tdgram_recvfrom_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + uint8_t **buf, + struct tsocket_address **src) +{ + struct tdgram_recvfrom_state *state = tevent_req_data(req, + struct tdgram_recvfrom_state); + ssize_t ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + *buf = talloc_move(mem_ctx, &state->buf); + ret = state->len; + if (src) { + *src = talloc_move(mem_ctx, &state->src); + } + } + + tevent_req_received(req); + return ret; +} + +struct tdgram_sendto_state { + const struct tdgram_context_ops *ops; + struct tdgram_context *dgram; + ssize_t ret; +}; + +static int tdgram_sendto_destructor(struct tdgram_sendto_state *state) +{ + if (state->dgram) { + state->dgram->sendto_req = NULL; + } + + return 0; +} + +static void tdgram_sendto_done(struct tevent_req *subreq); + +struct tevent_req *tdgram_sendto_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram, + const uint8_t *buf, size_t len, + const struct tsocket_address *dst) +{ + struct tevent_req *req; + struct tdgram_sendto_state *state; + struct tevent_req *subreq; + + req = tevent_req_create(mem_ctx, &state, + struct tdgram_sendto_state); + if (req == NULL) { + return NULL; + } + + state->ops = dgram->ops; + state->dgram = dgram; + state->ret = -1; + + if (len == 0) { + tevent_req_error(req, EINVAL); + goto post; + } + + if (dgram->sendto_req) { + tevent_req_error(req, EBUSY); + goto post; + } + dgram->sendto_req = req; + + talloc_set_destructor(state, tdgram_sendto_destructor); + + subreq = state->ops->sendto_send(state, ev, dgram, + buf, len, dst); + if (tevent_req_nomem(subreq, req)) { + goto post; + } + tevent_req_set_callback(subreq, tdgram_sendto_done, req); + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tdgram_sendto_done(struct tevent_req *subreq) +{ + struct tevent_req *req = tevent_req_callback_data(subreq, + struct tevent_req); + struct tdgram_sendto_state *state = tevent_req_data(req, + struct tdgram_sendto_state); + ssize_t ret; + int sys_errno; + + ret = state->ops->sendto_recv(subreq, &sys_errno); + if (ret == -1) { + tevent_req_error(req, sys_errno); + return; + } + + state->ret = ret; + + tevent_req_done(req); +} + +ssize_t tdgram_sendto_recv(struct tevent_req *req, + int *perrno) +{ + struct tdgram_sendto_state *state = tevent_req_data(req, + struct tdgram_sendto_state); + ssize_t ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = state->ret; + } + + tevent_req_received(req); + return ret; +} + +struct tdgram_disconnect_state { + const struct tdgram_context_ops *ops; +}; + +static void tdgram_disconnect_done(struct tevent_req *subreq); + +struct tevent_req *tdgram_disconnect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram) +{ + struct tevent_req *req; + struct tdgram_disconnect_state *state; + struct tevent_req *subreq; + + req = tevent_req_create(mem_ctx, &state, + struct tdgram_disconnect_state); + if (req == NULL) { + return NULL; + } + + state->ops = dgram->ops; + + if (dgram->recvfrom_req || dgram->sendto_req) { + tevent_req_error(req, EBUSY); + goto post; + } + + subreq = state->ops->disconnect_send(state, ev, dgram); + if (tevent_req_nomem(subreq, req)) { + goto post; + } + tevent_req_set_callback(subreq, tdgram_disconnect_done, req); + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tdgram_disconnect_done(struct tevent_req *subreq) +{ + struct tevent_req *req = tevent_req_callback_data(subreq, + struct tevent_req); + struct tdgram_disconnect_state *state = tevent_req_data(req, + struct tdgram_disconnect_state); + int ret; + int sys_errno; + + ret = state->ops->disconnect_recv(subreq, &sys_errno); + if (ret == -1) { + tevent_req_error(req, sys_errno); + return; + } + + tevent_req_done(req); +} + +int tdgram_disconnect_recv(struct tevent_req *req, + int *perrno) +{ + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + + tevent_req_received(req); + return ret; +} + +struct tstream_context { + const char *location; + const struct tstream_context_ops *ops; + void *private_data; + + struct tevent_req *readv_req; + struct tevent_req *writev_req; +}; + +static int tstream_context_destructor(struct tstream_context *stream) +{ + if (stream->readv_req) { + tevent_req_received(stream->readv_req); + } + + if (stream->writev_req) { + tevent_req_received(stream->writev_req); + } + + return 0; +} + +struct tstream_context *_tstream_context_create(TALLOC_CTX *mem_ctx, + const struct tstream_context_ops *ops, + void *pstate, + size_t psize, + const char *type, + const char *location) +{ + struct tstream_context *stream; + void **ppstate = (void **)pstate; + void *state; + + stream = talloc(mem_ctx, struct tstream_context); + if (stream == NULL) { + return NULL; + } + stream->location = location; + stream->ops = ops; + stream->readv_req = NULL; + stream->writev_req = NULL; + + state = talloc_size(stream, psize); + if (state == NULL) { + talloc_free(stream); + return NULL; + } + talloc_set_name_const(state, type); + + stream->private_data = state; + + talloc_set_destructor(stream, tstream_context_destructor); + + *ppstate = state; + return stream; +} + +void *_tstream_context_data(struct tstream_context *stream) +{ + return stream->private_data; +} + +ssize_t tstream_pending_bytes(struct tstream_context *stream) +{ + return stream->ops->pending_bytes(stream); +} + +struct tstream_readv_state { + const struct tstream_context_ops *ops; + struct tstream_context *stream; + int ret; +}; + +static int tstream_readv_destructor(struct tstream_readv_state *state) +{ + if (state->stream) { + state->stream->readv_req = NULL; + } + + return 0; +} + +static void tstream_readv_done(struct tevent_req *subreq); + +struct tevent_req *tstream_readv_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct iovec *vector, + size_t count) +{ + struct tevent_req *req; + struct tstream_readv_state *state; + struct tevent_req *subreq; + int to_read = 0; + size_t i; + + req = tevent_req_create(mem_ctx, &state, + struct tstream_readv_state); + if (req == NULL) { + return NULL; + } + + state->ops = stream->ops; + state->stream = stream; + state->ret = -1; + + /* first check if the input is ok */ +#ifdef IOV_MAX + if (count > IOV_MAX) { + tevent_req_error(req, EMSGSIZE); + goto post; + } +#endif + + for (i=0; i < count; i++) { + int tmp = to_read; + tmp += vector[i].iov_len; + + if (tmp < to_read) { + tevent_req_error(req, EMSGSIZE); + goto post; + } + + to_read = tmp; + } + + if (to_read == 0) { + tevent_req_error(req, EINVAL); + goto post; + } + + if (stream->readv_req) { + tevent_req_error(req, EBUSY); + goto post; + } + stream->readv_req = req; + + talloc_set_destructor(state, tstream_readv_destructor); + + subreq = state->ops->readv_send(state, ev, stream, vector, count); + if (tevent_req_nomem(subreq, req)) { + goto post; + } + tevent_req_set_callback(subreq, tstream_readv_done, req); + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tstream_readv_done(struct tevent_req *subreq) +{ + struct tevent_req *req = tevent_req_callback_data(subreq, + struct tevent_req); + struct tstream_readv_state *state = tevent_req_data(req, + struct tstream_readv_state); + ssize_t ret; + int sys_errno; + + ret = state->ops->readv_recv(subreq, &sys_errno); + TALLOC_FREE(subreq); + if (ret == -1) { + tevent_req_error(req, sys_errno); + return; + } + + state->ret = ret; + + tevent_req_done(req); +} + +int tstream_readv_recv(struct tevent_req *req, + int *perrno) +{ + struct tstream_readv_state *state = tevent_req_data(req, + struct tstream_readv_state); + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = state->ret; + } + + tevent_req_received(req); + return ret; +} + +struct tstream_writev_state { + const struct tstream_context_ops *ops; + struct tstream_context *stream; + int ret; +}; + +static int tstream_writev_destructor(struct tstream_writev_state *state) +{ + if (state->stream) { + state->stream->writev_req = NULL; + } + + return 0; +} + +static void tstream_writev_done(struct tevent_req *subreq); + +struct tevent_req *tstream_writev_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + const struct iovec *vector, + size_t count) +{ + struct tevent_req *req; + struct tstream_writev_state *state; + struct tevent_req *subreq; + int to_write = 0; + size_t i; + + req = tevent_req_create(mem_ctx, &state, + struct tstream_writev_state); + if (req == NULL) { + return NULL; + } + + state->ops = stream->ops; + state->stream = stream; + state->ret = -1; + + /* first check if the input is ok */ +#ifdef IOV_MAX + if (count > IOV_MAX) { + tevent_req_error(req, EMSGSIZE); + goto post; + } +#endif + + for (i=0; i < count; i++) { + int tmp = to_write; + tmp += vector[i].iov_len; + + if (tmp < to_write) { + tevent_req_error(req, EMSGSIZE); + goto post; + } + + to_write = tmp; + } + + if (to_write == 0) { + tevent_req_error(req, EINVAL); + goto post; + } + + if (stream->writev_req) { + tevent_req_error(req, EBUSY); + goto post; + } + stream->writev_req = req; + + talloc_set_destructor(state, tstream_writev_destructor); + + subreq = state->ops->writev_send(state, ev, stream, vector, count); + if (tevent_req_nomem(subreq, req)) { + goto post; + } + tevent_req_set_callback(subreq, tstream_writev_done, req); + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tstream_writev_done(struct tevent_req *subreq) +{ + struct tevent_req *req = tevent_req_callback_data(subreq, + struct tevent_req); + struct tstream_writev_state *state = tevent_req_data(req, + struct tstream_writev_state); + ssize_t ret; + int sys_errno; + + ret = state->ops->writev_recv(subreq, &sys_errno); + if (ret == -1) { + tevent_req_error(req, sys_errno); + return; + } + + state->ret = ret; + + tevent_req_done(req); +} + +int tstream_writev_recv(struct tevent_req *req, + int *perrno) +{ + struct tstream_writev_state *state = tevent_req_data(req, + struct tstream_writev_state); + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = state->ret; + } + + tevent_req_received(req); + return ret; +} + +struct tstream_disconnect_state { + const struct tstream_context_ops *ops; +}; + +static void tstream_disconnect_done(struct tevent_req *subreq); + +struct tevent_req *tstream_disconnect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream) +{ + struct tevent_req *req; + struct tstream_disconnect_state *state; + struct tevent_req *subreq; + + req = tevent_req_create(mem_ctx, &state, + struct tstream_disconnect_state); + if (req == NULL) { + return NULL; + } + + state->ops = stream->ops; + + if (stream->readv_req || stream->writev_req) { + tevent_req_error(req, EBUSY); + goto post; + } + + subreq = state->ops->disconnect_send(state, ev, stream); + if (tevent_req_nomem(subreq, req)) { + goto post; + } + tevent_req_set_callback(subreq, tstream_disconnect_done, req); + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tstream_disconnect_done(struct tevent_req *subreq) +{ + struct tevent_req *req = tevent_req_callback_data(subreq, + struct tevent_req); + struct tstream_disconnect_state *state = tevent_req_data(req, + struct tstream_disconnect_state); + int ret; + int sys_errno; + + ret = state->ops->disconnect_recv(subreq, &sys_errno); + if (ret == -1) { + tevent_req_error(req, sys_errno); + return; + } + + tevent_req_done(req); +} + +int tstream_disconnect_recv(struct tevent_req *req, + int *perrno) +{ + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + + tevent_req_received(req); + return ret; +} + diff --git a/lib/tsocket/tsocket.h b/lib/tsocket/tsocket.h new file mode 100644 index 0000000..07e10c8 --- /dev/null +++ b/lib/tsocket/tsocket.h @@ -0,0 +1,1319 @@ +/* + Unix SMB/CIFS implementation. + + Copyright (C) Stefan Metzmacher 2009 + + ** NOTE! The following LGPL license applies to the tsocket + ** library. This does NOT imply that all of Samba is released + ** under the LGPL + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef _TSOCKET_H +#define _TSOCKET_H + +#include <tevent.h> + +struct samba_sockaddr; +struct tsocket_address; +struct tdgram_context; +struct tstream_context; +struct iovec; + +/** + * @mainpage + * + * The tsocket abstraction is an API ... + */ + +/** + * @defgroup tsocket The tsocket API + * + * The tsocket abstraction is split into two different kinds of + * communication interfaces. + * + * There's the "tstream_context" interface with abstracts the communication + * through a bidirectional byte stream between two endpoints. + * + * And there's the "tdgram_context" interface with abstracts datagram based + * communication between any number of endpoints. + * + * Both interfaces share the "tsocket_address" abstraction for endpoint + * addresses. + * + * The whole library is based on the talloc(3) and 'tevent' libraries and + * provides "tevent_req" based "foo_send()"/"foo_recv()" functions pairs for + * all abstracted methods that need to be async. + * + * @section vsock Virtual Sockets + * + * The abstracted layout of tdgram_context and tstream_context allow + * implementations around virtual sockets for encrypted tunnels (like TLS, + * SASL or GSSAPI) or named pipes over smb. + * + * @section npa Named Pipe Auth (NPA) Sockets + * + * Samba has an implementation to abstract named pipes over smb (within the + * server side). See libcli/named_pipe_auth/npa_tstream.[ch] for the core code. + * The current callers are located in source4/ntvfs/ipc/vfs_ipc.c and + * source4/rpc_server/service_rpc.c for the users. + */ + +/** + * @defgroup tsocket_address The tsocket_address abstraction + * @ingroup tsocket + * + * The tsocket_address represents an socket endpoint generically. + * As it's like an abstract class it has no specific constructor. + * The specific constructors are described in later sections. + * + * @{ + */ + +/** + * @brief Get a string representation of the endpoint. + * + * This function creates a string representation of the endpoint for debugging. + * The output will look as followed: + * prefix:address:port + * + * e.g. + * ipv4:192.168.1.1:143 + * + * Callers should not try to parse the string! The should use additional methods + * of the specific tsocket_address implementation to get more details. + * + * @param[in] addr The address to convert. + * + * @param[in] mem_ctx The talloc memory context to allocate the memory. + * + * @return The address as a string representation, NULL on error. + * + * @see tsocket_address_is_inet() + * @see tsocket_address_inet_addr_string() + * @see tsocket_address_inet_port() + */ +char *tsocket_address_string(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx); + +#ifdef DOXYGEN +/** + * @brief This creates a copy of a tsocket_address. + * + * This is useful when before doing modifications to a socket via additional + * methods of the specific tsocket_address implementation. + * + * @param[in] addr The address to create the copy from. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @return A newly allocated copy of addr (tsocket_address *), NULL + * on error. + */ +struct tsocket_address *tsocket_address_copy(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx); +#else +struct tsocket_address *_tsocket_address_copy(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx, + const char *location); + +#define tsocket_address_copy(addr, mem_ctx) \ + _tsocket_address_copy(addr, mem_ctx, __location__) +#endif + +/** + * @} + */ + +/** + * @defgroup tdgram_context The tdgram_context abstraction + * @ingroup tsocket + * + * The tdgram_context is like an abstract class for datagram based sockets. The + * interface provides async 'tevent_req' based functions on top functionality + * is similar to the recvfrom(2)/sendto(2)/close(2) syscalls. + * + * @note You can always use talloc_free(tdgram) to cleanup the resources + * of the tdgram_context on a fatal error. + * @{ + */ + +/** + * @brief Ask for next available datagram on the abstracted tdgram_context. + * + * It returns a 'tevent_req' handle, where the caller can register + * a callback with tevent_req_set_callback(). The callback is triggered + * when a datagram is available or an error happened. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] ev The tevent_context to run on. + * + * @param[in] dgram The dgram context to work on. + * + * @return Returns a 'tevent_req' handle, where the caller can + * register a callback with tevent_req_set_callback(). + * NULL on fatal error. + * + * @see tdgram_inet_udp_socket() + * @see tdgram_unix_socket() + */ +struct tevent_req *tdgram_recvfrom_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram); + +/** + * @brief Receive the next available datagram on the abstracted tdgram_context. + * + * This function should be called by the callback when a datagram is available + * or an error happened. + * + * The caller can only have one outstanding tdgram_recvfrom_send() at a time + * otherwise the caller will get '*perrno = EBUSY'. + * + * @param[in] req The tevent request from tdgram_recvfrom_send(). + * + * @param[out] perrno The error number, set if an error occurred. + * + * @param[in] mem_ctx The memory context to use. + * + * @param[out] buf This will hold the buffer of the datagram. + * + * @param[out] src The abstracted tsocket_address of the sender of the + * received datagram. + * + * @return The length of the datagram (0 is never returned!), + * -1 on error with perrno set to the actual errno. + * + * @see tdgram_recvfrom_send() + */ +ssize_t tdgram_recvfrom_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + uint8_t **buf, + struct tsocket_address **src); + +/** + * @brief Send a datagram to a destination endpoint. + * + * The function can be called to send a datagram (specified by a buf/len) to a + * destination endpoint (specified by dst). It's not allowed for len to be 0. + * + * It returns a 'tevent_req' handle, where the caller can register a callback + * with tevent_req_set_callback(). The callback is triggered when the specific + * implementation (assumes it) has delivered the datagram to the "wire". + * + * The callback is then supposed to get the result by calling + * tdgram_sendto_recv() on the 'tevent_req'. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] ev The tevent_context to run on. + * + * @param[in] dgram The dgram context to work on. + * + * @param[in] buf The buffer to send. + * + * @param[in] len The length of the buffer to send. It has to be bigger + * than 0. + * + * @param[in] dst The destination to send the datagram to in form of a + * tsocket_address. + * + * @return Returns a 'tevent_req' handle, where the caller can + * register a callback with tevent_req_set_callback(). + * NULL on fatal error. + * + * @see tdgram_inet_udp_socket() + * @see tdgram_unix_socket() + * @see tdgram_sendto_recv() + */ +struct tevent_req *tdgram_sendto_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram, + const uint8_t *buf, size_t len, + const struct tsocket_address *dst); + +/** + * @brief Receive the result of the sent datagram. + * + * The caller can only have one outstanding tdgram_sendto_send() at a time + * otherwise the caller will get '*perrno = EBUSY'. + * + * @param[in] req The tevent request from tdgram_sendto_send(). + * + * @param[out] perrno The error number, set if an error occurred. + * + * @return The length of the datagram (0 is never returned!), -1 on + * error with perrno set to the actual errno. + * + * @see tdgram_sendto_send() + */ +ssize_t tdgram_sendto_recv(struct tevent_req *req, + int *perrno); + +/** + * @brief Shutdown/close an abstracted socket. + * + * It returns a 'tevent_req' handle, where the caller can register a callback + * with tevent_req_set_callback(). The callback is triggered when the specific + * implementation (assumes it) has delivered the datagram to the "wire". + * + * The callback is then supposed to get the result by calling + * tdgram_sendto_recv() on the 'tevent_req'. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] ev The tevent_context to run on. + * + * @param[in] dgram The dgram context to disconnect from. + * + * @return Returns a 'tevent_req' handle, where the caller can + * register a callback with tevent_req_set_callback(). + * NULL on fatal error. + * + * @see tdgram_disconnect_recv() + */ +struct tevent_req *tdgram_disconnect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram); + +/** + * @brief Receive the result from a tdgram_disconnect_send() request. + * + * The caller should make sure there're no outstanding tdgram_recvfrom_send() + * and tdgram_sendto_send() calls otherwise the caller will get + * '*perrno = EBUSY'. + * + * @param[in] req The tevent request from tdgram_disconnect_send(). + * + * @param[out] perrno The error number, set if an error occurred. + * + * @return The length of the datagram (0 is never returned!), -1 on + * error with perrno set to the actual errno. + * + * @see tdgram_disconnect_send() + */ +int tdgram_disconnect_recv(struct tevent_req *req, + int *perrno); + +/** + * @} + */ + +/** + * @defgroup tstream_context The tstream_context abstraction + * @ingroup tsocket + * + * The tstream_context is like an abstract class for stream based sockets. The + * interface provides async 'tevent_req' based functions on top functionality + * is similar to the readv(2)/writev(2)/close(2) syscalls. + * + * @note You can always use talloc_free(tstream) to cleanup the resources + * of the tstream_context on a fatal error. + * + * @{ + */ + +/** + * @brief Report the number of bytes received but not consumed yet. + * + * The tstream_pending_bytes() function reports how much bytes of the incoming + * stream have been received but not consumed yet. + * + * @param[in] stream The tstream_context to check for pending bytes. + * + * @return The number of bytes received, -1 on error with errno + * set. + */ +ssize_t tstream_pending_bytes(struct tstream_context *stream); + +/** + * @brief Read a specific amount of bytes from a stream socket. + * + * The function can be called to read for a specific amount of bytes from the + * stream into given buffers. The caller has to preallocate the buffers. + * + * The caller might need to use tstream_pending_bytes() if the protocol doesn't + * have a fixed pdu header containing the pdu size. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] ev The tevent_context to run on. + * + * @param[in] stream The tstream context to work on. + * + * @param[out] vector A preallocated iovec to store the data to read. + * + * @param[in] count The number of buffers in the vector allocated. + * + * @return A 'tevent_req' handle, where the caller can register + * a callback with tevent_req_set_callback(). NULL on + * fatal error. + * + * @see tstream_unix_connect_send() + * @see tstream_inet_tcp_connect_send() + */ +struct tevent_req *tstream_readv_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct iovec *vector, + size_t count); + +/** + * @brief Get the result of a tstream_readv_send(). + * + * The caller can only have one outstanding tstream_readv_send() + * at a time otherwise the caller will get *perrno = EBUSY. + * + * @param[in] req The tevent request from tstream_readv_send(). + * + * @param[out] perrno The error number, set if an error occurred. + * + * @return The length of the stream (0 is never returned!), -1 on + * error with perrno set to the actual errno. + */ +int tstream_readv_recv(struct tevent_req *req, + int *perrno); + +/** + * @brief Write buffers from a vector into a stream socket. + * + * The function can be called to write buffers from a given vector + * to a stream socket. + * + * You have to ensure that the vector is not empty. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] ev The tevent_context to run on. + * + * @param[in] stream The tstream context to work on. + * + * @param[in] vector The iovec vector with data to write on a stream socket. + * + * @param[in] count The number of buffers in the vector to write. + * + * @return A 'tevent_req' handle, where the caller can register + * a callback with tevent_req_set_callback(). NULL on + * fatal error. + */ +struct tevent_req *tstream_writev_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + const struct iovec *vector, + size_t count); + +/** + * @brief Get the result of a tstream_writev_send(). + * + * The caller can only have one outstanding tstream_writev_send() + * at a time otherwise the caller will get *perrno = EBUSY. + * + * @param[in] req The tevent request from tstream_writev_send(). + * + * @param[out] perrno The error number, set if an error occurred. + * + * @return The length of the stream (0 is never returned!), -1 on + * error with perrno set to the actual errno. + */ +int tstream_writev_recv(struct tevent_req *req, + int *perrno); + +/** + * @brief Shutdown/close an abstracted socket. + * + * It returns a 'tevent_req' handle, where the caller can register a callback + * with tevent_req_set_callback(). The callback is triggered when the specific + * implementation (assumes it) has delivered the stream to the "wire". + * + * The callback is then supposed to get the result by calling + * tdgram_sendto_recv() on the 'tevent_req'. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] ev The tevent_context to run on. + * + * @param[in] stream The tstream context to work on. + * + * @return A 'tevent_req' handle, where the caller can register + * a callback with tevent_req_set_callback(). NULL on + * fatal error. + */ +struct tevent_req *tstream_disconnect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream); + +/** + * @brief Get the result of a tstream_disconnect_send(). + * + * The caller can only have one outstanding tstream_writev_send() + * at a time otherwise the caller will get *perrno = EBUSY. + * + * @param[in] req The tevent request from tstream_disconnect_send(). + * + * @param[out] perrno The error number, set if an error occurred. + * + * @return The length of the stream (0 is never returned!), -1 on + * error with perrno set to the actual errno. + */ +int tstream_disconnect_recv(struct tevent_req *req, + int *perrno); + +/** + * @} + */ + + +/** + * @defgroup tsocket_bsd tsocket_bsd - inet, inet6 and unix + * @ingroup tsocket + * + * The main tsocket library comes with implementations for BSD style ipv4, ipv6 + * and unix sockets. + * + * @{ + */ + +/** + * @brief Find out if the tsocket_address represents an ipv4 or ipv6 endpoint. + * + * @param[in] addr The tsocket_address pointer + * + * @param[in] fam The family can be can be "ipv4", "ipv6" or "ip". With + * "ip" is autodetects "ipv4" or "ipv6" based on the + * addr. + * + * @return true if addr represents an address of the given family, + * otherwise false. + */ +bool tsocket_address_is_inet(const struct tsocket_address *addr, const char *fam); + +#ifdef DOXYGEN +/** + * @brief Create a tsocket_address for ipv4 and ipv6 endpoint addresses. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] fam The family can be can be "ipv4", "ipv6" or "ip". With + * "ip" is autodetects "ipv4" or "ipv6" based on the + * addr. + * + * @param[in] addr A valid ip address string based on the selected family + * (dns names are not allowed!). It's valid to pass NULL, + * which gets mapped to "0.0.0.0" or "::". + * + * @param[in] port A valid port number. + * + * @param[out] _addr A tsocket_address pointer to store the information. + * + * @return 0 on success, -1 on error with errno set. + */ +int tsocket_address_inet_from_strings(TALLOC_CTX *mem_ctx, + const char *fam, + const char *addr, + uint16_t port, + struct tsocket_address **_addr); +#else +int _tsocket_address_inet_from_strings(TALLOC_CTX *mem_ctx, + const char *fam, + const char *addr, + uint16_t port, + struct tsocket_address **_addr, + const char *location); + +#define tsocket_address_inet_from_strings(mem_ctx, fam, addr, port, _addr) \ + _tsocket_address_inet_from_strings(mem_ctx, fam, addr, port, _addr, \ + __location__) +#endif + +#ifdef DOXYGEN +/** + * @brief Create a tsocket_address for ipv4 and ipv6 endpoint addresses. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] fam The family can be can be "ipv4", "ipv6" or "ip". With + * "ip" it autodetects "ipv4" or "ipv6" based on the + * addr. + * + * @param[in] host_port_addr A valid ip address string based on the + * selected family (dns names are not allowed!). A port + * number may follow separated by a colon. IPv6 may be + * surrounded in square brackets, and these are required + * if appending a port number. It's valid to pass NULL, + * which gets mapped to "0.0.0.0" or "::". + * + * @param[in] default_port A valid port number for the default port if none + * given. + * + * @param[out] _addr A tsocket_address pointer to store the information. + * + * @return 0 on success, -1 on error with errno set. + */ +int tsocket_address_inet_from_hostport_strings(TALLOC_CTX *mem_ctx, + const char *fam, + const char *host_port_addr, + uint16_t default_port, + struct tsocket_address **_addr); +#else +int _tsocket_address_inet_from_hostport_strings(TALLOC_CTX *mem_ctx, + const char *fam, + const char *host_port_addr, + uint16_t default_port, + struct tsocket_address **_addr, + const char *location); + +#define tsocket_address_inet_from_hostport_strings( \ + mem_ctx, fam, host_port_addr, default_port, _addr) \ + _tsocket_address_inet_from_hostport_strings( \ + mem_ctx, fam, host_port_addr, default_port, _addr, __location__) +#endif + +/** + * @brief Get the address of an 'inet' tsocket_address as a string. + * + * @param[in] addr The address to convert to a string. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @return A newly allocated string of the address, NULL on error + * with errno set. + * + * @see tsocket_address_is_inet() + */ +char *tsocket_address_inet_addr_string(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx); + +/** + * @brief Get the port number as an integer from an 'inet' tsocket_address. + * + * @param[in] addr The tsocket address to use. + * + * @return The port number, 0 on error with errno set. + */ +uint16_t tsocket_address_inet_port(const struct tsocket_address *addr); + +/** + * @brief Set the port number of an existing 'inet' tsocket_address. + * + * @param[in] addr The existing tsocket_address to use. + * + * @param[in] port The valid port number to set. + * + * @return 0 on success, -1 on error with errno set. + */ +int tsocket_address_inet_set_port(struct tsocket_address *addr, + uint16_t port); + +/** + * @brief Find out if the tsocket_address represents an unix domain endpoint. + * + * @param[in] addr The tsocket_address pointer + * + * @return true if addr represents an unix domain endpoint, + * otherwise false. + */ +bool tsocket_address_is_unix(const struct tsocket_address *addr); + +#ifdef DOXYGEN +/** + * @brief Create a tsocket_address for a unix domain endpoint addresses. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] path The filesystem path, NULL will map "". + * + * @param[in] _addr The tsocket_address pointer to store the information. + * + * @return 0 on success, -1 on error with errno set. + * + * @see tsocket_address_is_unix() + */ +int tsocket_address_unix_from_path(TALLOC_CTX *mem_ctx, + const char *path, + struct tsocket_address **_addr); +#else +int _tsocket_address_unix_from_path(TALLOC_CTX *mem_ctx, + const char *path, + struct tsocket_address **_addr, + const char *location); + +#define tsocket_address_unix_from_path(mem_ctx, path, _addr) \ + _tsocket_address_unix_from_path(mem_ctx, path, _addr, \ + __location__) +#endif + +/** + * @brief Get the address of an 'unix' tsocket_address. + * + * @param[in] addr A valid 'unix' tsocket_address. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @return The path of the unix domain socket, NULL on error or if + * the tsocket_address doesn't represent an unix domain + * endpoint path. + */ +char *tsocket_address_unix_path(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx); + +#ifdef DOXYGEN +/** + * @brief Wrap an existing file descriptors into the tdgram abstraction. + * + * You can use this function to wrap an existing file descriptors into the + * tdgram abstraction. After that you're not able to use this file descriptor + * for anything else. The file descriptor will be closed when the stream gets + * freed. If you still want to use the fd you have to create a duplicate. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] fd The non blocking fd to use! + * + * @param[out] dgram A pointer to store an allocated tdgram_context. + * + * @return 0 on success, -1 on error. + * + * Example: + * @code + * fd2 = dup(fd); + * rc = tdgram_bsd_existing_socket(mem_ctx, fd2, &tdgram); + * if (rc < 0) { + * return; + * } + * @endcode + * + * @warning This is an internal function. You should read the code to fully + * understand it if you plan to use it. + */ +int tdgram_bsd_existing_socket(TALLOC_CTX *mem_ctx, + int fd, + struct tdgram_context **dgram); +#else +int _tdgram_bsd_existing_socket(TALLOC_CTX *mem_ctx, + int fd, + struct tdgram_context **_dgram, + const char *location); +#define tdgram_bsd_existing_socket(mem_ctx, fd, dgram) \ + _tdgram_bsd_existing_socket(mem_ctx, fd, dgram, \ + __location__) +#endif + +/** + * @brief Request a syscall optimization for tdgram_recvfrom_send() + * + * This function is only used to reduce the amount of syscalls and + * optimize performance. You should only use this if you know + * what you're doing. + * + * The optimization is off by default. + * + * @param[in] dgram The tdgram_context of a bsd socket, if this + * not a bsd socket the function does nothing. + * + * @param[in] on The boolean value to turn the optimization on and off. + * + * @return The old boolean value. + * + * @see tdgram_recvfrom_send() + */ +bool tdgram_bsd_optimize_recvfrom(struct tdgram_context *dgram, + bool on); + +#ifdef DOXYGEN +/** + * @brief Create a tdgram_context for a ipv4 or ipv6 UDP communication. + * + * @param[in] local An 'inet' tsocket_address for the local endpoint. + * + * @param[in] remote An 'inet' tsocket_address for the remote endpoint or + * NULL (??? to create a listener?). + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] dgram The tdgram_context pointer to setup the udp + * communication. The function will allocate the memory. + * + * @return 0 on success, -1 on error with errno set. + * + * @see tdgram_inet_udp_broadcast_socket() + */ +int tdgram_inet_udp_socket(const struct tsocket_address *local, + const struct tsocket_address *remote, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram); +#else +int _tdgram_inet_udp_socket(const struct tsocket_address *local, + const struct tsocket_address *remote, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram, + const char *location); +#define tdgram_inet_udp_socket(local, remote, mem_ctx, dgram) \ + _tdgram_inet_udp_socket(local, remote, mem_ctx, dgram, __location__) +#endif + +#ifdef DOXYGEN +/** + * @brief Create a tdgram_context for a ipv4 UDP broadcast (and unicast) communication. + * + * @param[in] local An 'inet' (ipv4 only) tsocket_address for the local endpoint. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] dgram The tdgram_context pointer to setup the udp + * communication. The function will allocate the memory. + * + * @return 0 on success, -1 on error with errno set. + * + * @see tdgram_inet_udp_socket() + */ +int tdgram_inet_udp_broadcast_socket(const struct tsocket_address *local, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram); +#else +int _tdgram_inet_udp_broadcast_socket(const struct tsocket_address *local, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram, + const char *location); +#define tdgram_inet_udp_broadcast_socket(local, mem_ctx, dgram) \ + _tdgram_inet_udp_broadcast_socket(local, mem_ctx, dgram, __location__) +#endif + +#ifdef DOXYGEN +/** + * @brief Create a tdgram_context for unix domain datagram communication. + * + * @param[in] local An 'unix' tsocket_address for the local endpoint. + * + * @param[in] remote An 'unix' tsocket_address for the remote endpoint or + * NULL (??? to create a listener?). + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] dgram The tdgram_context pointer to setup the udp + * communication. The function will allocate the memory. + * + * @return 0 on success, -1 on error with errno set. + */ +int tdgram_unix_socket(const struct tsocket_address *local, + const struct tsocket_address *remote, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram); +#else +int _tdgram_unix_socket(const struct tsocket_address *local, + const struct tsocket_address *remote, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram, + const char *location); + +#define tdgram_unix_socket(local, remote, mem_ctx, dgram) \ + _tdgram_unix_socket(local, remote, mem_ctx, dgram, __location__) +#endif + +/** + * @brief Request a syscall optimization for tstream_readv_send() + * + * This function is only used to reduce the amount of syscalls and + * optimize performance. You should only use this if you know + * what you're doing. + * + * The optimization is off by default. + * + * @param[in] stream The tstream_context of a bsd socket, if this + * not a bsd socket the function does nothing. + * + * @param[in] on The boolean value to turn the optimization on and off. + * + * @return The old boolean value. + * + * @see tstream_readv_send() + */ +bool tstream_bsd_optimize_readv(struct tstream_context *stream, + bool on); + +/** + * @brief Request that tstream_readv_send() fails within pending data + * + * By default we allow pending data to be drained from the + * recv queue, before we report EPIPE when reaching EOF. + * + * For server applications it's typically useful to + * fail early in order to avoid useless work, + * as the response can't be transferred to the client anyway. + * + * @param[in] stream The tstream_context of a bsd socket, if this + * not a bsd socket the function does nothing. + * + * @param[in] on The boolean value to turn the early fail on and off. + * + * @return The old boolean value. + * + * @see tstream_readv_send() + */ +bool tstream_bsd_fail_readv_first_error(struct tstream_context *stream, + bool on); + +/** + * @brief Connect async to a TCP endpoint and create a tstream_context for the + * stream based communication. + * + * Use this function to connect asynchronously to a remote ipv4 or ipv6 TCP + * endpoint and create a tstream_context for the stream based communication. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] ev The tevent_context to run on. + * + * @param[in] local An 'inet' tsocket_address for the local endpoint. + * + * @param[in] remote An 'inet' tsocket_address for the remote endpoint. + * + * @return A 'tevent_req' handle, where the caller can register a + * callback with tevent_req_set_callback(). NULL on a fatal + * error. + * + * @see tstream_inet_tcp_connect_recv() + */ +struct tevent_req *tstream_inet_tcp_connect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + const struct tsocket_address *local, + const struct tsocket_address *remote); + +#ifdef DOXYGEN +/** + * @brief Receive the result from a tstream_inet_tcp_connect_send(). + * + * @param[in] req The tevent request from tstream_inet_tcp_connect_send(). + * + * @param[out] perrno The error number, set if an error occurred. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[out] stream A tstream_context pointer to setup the tcp communication + * on. This function will allocate the memory. + * + * @param[out] local The real 'inet' tsocket_address of the local endpoint. + * This parameter is optional and can be NULL. + * + * @return 0 on success, -1 on error with perrno set. + */ +int tstream_inet_tcp_connect_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + struct tstream_context **stream, + struct tsocket_address **local) +#else +int _tstream_inet_tcp_connect_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + struct tstream_context **stream, + struct tsocket_address **local, + const char *location); +#define tstream_inet_tcp_connect_recv(req, perrno, mem_ctx, stream, local) \ + _tstream_inet_tcp_connect_recv(req, perrno, mem_ctx, stream, local, \ + __location__) +#endif + +/** + * @brief Connect async to a unix domain endpoint and create a tstream_context + * for the stream based communication. + * + * Use this function to connect asynchronously to a unix domainendpoint and + * create a tstream_context for the stream based communication. + * + * The callback is triggered when a socket is connected and ready for IO or an + * error happened. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] ev The tevent_context to run on. + * + * @param[in] local An 'unix' tsocket_address for the local endpoint. + * + * @param[in] remote An 'unix' tsocket_address for the remote endpoint. + * + * @return A 'tevent_req' handle, where the caller can register a + * callback with tevent_req_set_callback(). NULL on a falal + * error. + * + * @see tstream_unix_connect_recv() + */ +struct tevent_req * tstream_unix_connect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + const struct tsocket_address *local, + const struct tsocket_address *remote); + +#ifdef DOXYGEN +/** + * @brief Receive the result from a tstream_unix_connect_send(). + * + * @param[in] req The tevent request from tstream_inet_tcp_connect_send(). + * + * @param[out] perrno The error number, set if an error occurred. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] stream The tstream context to work on. + * + * @return 0 on success, -1 on error with perrno set. + */ +int tstream_unix_connect_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + struct tstream_context **stream); +#else +int _tstream_unix_connect_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + struct tstream_context **stream, + const char *location); +#define tstream_unix_connect_recv(req, perrno, mem_ctx, stream) \ + _tstream_unix_connect_recv(req, perrno, mem_ctx, stream, \ + __location__) +#endif + +#ifdef DOXYGEN +/** + * @brief Create two connected 'unix' tsocket_contexts for stream based + * communication. + * + * @param[in] mem_ctx1 The talloc memory context to use for stream1. + * + * @param[in] stream1 The first stream to connect. + * + * @param[in] mem_ctx2 The talloc memory context to use for stream2. + * + * @param[in] stream2 The second stream to connect. + * + * @return 0 on success, -1 on error with errno set. + */ +int tstream_unix_socketpair(TALLOC_CTX *mem_ctx1, + struct tstream_context **stream1, + TALLOC_CTX *mem_ctx2, + struct tstream_context **stream2); +#else +int _tstream_unix_socketpair(TALLOC_CTX *mem_ctx1, + struct tstream_context **_stream1, + TALLOC_CTX *mem_ctx2, + struct tstream_context **_stream2, + const char *location); + +#define tstream_unix_socketpair(mem_ctx1, stream1, mem_ctx2, stream2) \ + _tstream_unix_socketpair(mem_ctx1, stream1, mem_ctx2, stream2, \ + __location__) +#endif + +struct sockaddr; + +#ifdef DOXYGEN +/** + * @brief Convert a tsocket address to a bsd socket address. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] sa The sockaddr structure to convert. + * + * @param[in] sa_socklen The length of the sockaddr structure. + * + * @param[out] addr The tsocket pointer to allocate and fill. + * + * @return 0 on success, -1 on error with errno set. + */ +int tsocket_address_bsd_from_sockaddr(TALLOC_CTX *mem_ctx, + const struct sockaddr *sa, + size_t sa_socklen, + struct tsocket_address **addr); +#else +int _tsocket_address_bsd_from_sockaddr(TALLOC_CTX *mem_ctx, + const struct sockaddr *sa, + size_t sa_socklen, + struct tsocket_address **_addr, + const char *location); + +#define tsocket_address_bsd_from_sockaddr(mem_ctx, sa, sa_socklen, _addr) \ + _tsocket_address_bsd_from_sockaddr(mem_ctx, sa, sa_socklen, _addr, \ + __location__) +#endif + +#ifdef DOXYGEN +/** + * @brief Convert a samba address to a tsocket address. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] s_addr The samba address structure to convert. + * + * @param[out] t_addr The tsocket pointer to allocate and fill. + * + * @return 0 on success, -1 on error with errno set. + */ +int tsocket_address_bsd_from_samba_sockaddr(TALLOC_CTX *mem_ctx, + const struct samba_sockaddr *xs_addr, + struct tsocket_address **t_addr); +#else +int _tsocket_address_bsd_from_samba_sockaddr(TALLOC_CTX *mem_ctx, + const struct samba_sockaddr *xs_addr, + struct tsocket_address **t_addr, + const char *location); + +#define tsocket_address_bsd_from_samba_sockaddr(mem_ctx, xs_addr, t_addr) \ + _tsocket_address_bsd_from_samba_sockaddr(mem_ctx, xs_addr, t_addr, \ + __location__) +#endif + +/** + * @brief Fill a bsd sockaddr structure. + * + * @param[in] addr The tsocket address structure to use. + * + * @param[in] sa The bsd sockaddr structure to fill out. + * + * @param[in] sa_socklen The length of the bsd sockaddr structure to fill out. + * + * @return The actual size of the sockaddr structure, -1 on error + * with errno set. The size could differ from sa_socklen. + * + * @code + * ssize_t socklen; + * struct sockaddr_storage ss; + * + * socklen = tsocket_address_bsd_sockaddr(taddr, + * (struct sockaddr *) &ss, + * sizeof(struct sockaddr_storage)); + * if (socklen < 0) { + * return -1; + * } + * @endcode + */ +ssize_t tsocket_address_bsd_sockaddr(const struct tsocket_address *addr, + struct sockaddr *sa, + size_t sa_socklen); + +#ifdef DOXYGEN +/** + * @brief Wrap an existing file descriptors into the tstream abstraction. + * + * You can use this function to wrap an existing file descriptors into the + * tstream abstraction. After that you're not able to use this file descriptor + * for anything else. The file descriptor will be closed when the stream gets + * freed. If you still want to use the fd you have to create a duplicate. + * + * @param[in] mem_ctx The talloc memory context to use. + * + * @param[in] fd The non blocking fd to use! + * + * @param[out] stream A pointer to store an allocated tstream_context. + * + * @return 0 on success, -1 on error. + * + * Example: + * @code + * fd2 = dup(fd); + * rc = tstream_bsd_existing_socket(mem_ctx, fd2, &tstream); + * if (rc < 0) { + * stream_terminate_connection(conn, "named_pipe_accept: out of memory"); + * return; + * } + * @endcode + * + * @warning This is an internal function. You should read the code to fully + * understand it if you plan to use it. + */ +int tstream_bsd_existing_socket(TALLOC_CTX *mem_ctx, + int fd, + struct tstream_context **stream); +#else +int _tstream_bsd_existing_socket(TALLOC_CTX *mem_ctx, + int fd, + struct tstream_context **_stream, + const char *location); +#define tstream_bsd_existing_socket(mem_ctx, fd, stream) \ + _tstream_bsd_existing_socket(mem_ctx, fd, stream, \ + __location__) +#endif + +/** + * @} + */ + +/** + * @defgroup tsocket_helper Queue and PDU helpers + * @ingroup tsocket + * + * In order to make the live easier for callers which want to implement a + * function to receive a full PDU with a single async function pair, there're + * some helper functions. + * + * There're some cases where the caller wants doesn't care about the order of + * doing IO on the abstracted sockets. + * + * @{ + */ + +/** + * @brief Queue a dgram blob for sending through the socket. + * + * This function queues a blob for sending to destination through an existing + * dgram socket. The async callback is triggered when the whole blob is + * delivered to the underlying system socket. + * + * The caller needs to make sure that all non-scalar input parameters hang + * around for the whole lifetime of the request. + * + * @param[in] mem_ctx The memory context for the result. + * + * @param[in] ev The event context the operation should work on. + * + * @param[in] dgram The tdgram_context to send the message buffer. + * + * @param[in] queue The existing dgram queue. + * + * @param[in] buf The message buffer to send. + * + * @param[in] len The message length. + * + * @param[in] dst The destination socket address. + * + * @return The async request handle. NULL on fatal error. + * + * @see tdgram_sendto_queue_recv() + */ +struct tevent_req *tdgram_sendto_queue_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram, + struct tevent_queue *queue, + const uint8_t *buf, + size_t len, + struct tsocket_address *dst); + +/** + * @brief Receive the result of the sent dgram blob. + * + * @param[in] req The tevent request from tdgram_sendto_queue_send(). + * + * @param[out] perrno The error set to the actual errno. + * + * @return The length of the datagram (0 is never returned!), -1 on + * error with perrno set to the actual errno. + */ +ssize_t tdgram_sendto_queue_recv(struct tevent_req *req, int *perrno); + +typedef int (*tstream_readv_pdu_next_vector_t)(struct tstream_context *stream, + void *private_data, + TALLOC_CTX *mem_ctx, + struct iovec **vector, + size_t *count); + +struct tevent_req *tstream_readv_pdu_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + tstream_readv_pdu_next_vector_t next_vector_fn, + void *next_vector_private); +int tstream_readv_pdu_recv(struct tevent_req *req, int *perrno); + +/** + * @brief Queue a read request for a PDU on the socket. + * + * This function queues a read request for a PDU on a stream socket. The async + * callback is triggered when a full PDU has been read from the socket. + * + * The caller needs to make sure that all non-scalar input parameters hang + * around for the whole lifetime of the request. + * + * @param[in] mem_ctx The memory context for the result + * + * @param[in] ev The tevent_context to run on + * + * @param[in] stream The stream to send data through + * + * @param[in] queue The existing send queue + * + * @param[in] next_vector_fn The next vector function + * + * @param[in] next_vector_private The private_data of the next vector function + * + * @return The async request handle. NULL on fatal error. + * + * @see tstream_readv_pdu_queue_recv() + */ +struct tevent_req *tstream_readv_pdu_queue_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct tevent_queue *queue, + tstream_readv_pdu_next_vector_t next_vector_fn, + void *next_vector_private); + +/** + * @brief Receive the PDU blob read from the stream. + * + * @param[in] req The tevent request from tstream_readv_pdu_queue_send(). + * + * @param[out] perrno The error set to the actual errno. + * + * @return The number of bytes read on success, -1 on error with + * perrno set to the actual errno. + */ +int tstream_readv_pdu_queue_recv(struct tevent_req *req, int *perrno); + +/** + * @brief Queue an iovector for sending through the socket + * + * This function queues an iovector for sending to destination through an + * existing stream socket. The async callback is triggered when the whole + * vector has been delivered to the underlying system socket. + * + * The caller needs to make sure that all non-scalar input parameters hang + * around for the whole lifetime of the request. + * + * @param[in] mem_ctx The memory context for the result. + * + * @param[in] ev The tevent_context to run on. + * + * @param[in] stream The stream to send data through. + * + * @param[in] queue The existing send queue. + * + * @param[in] vector The iovec vector so write. + * + * @param[in] count The size of the vector. + * + * @return The async request handle. NULL on fatal error. + */ +struct tevent_req *tstream_writev_queue_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct tevent_queue *queue, + const struct iovec *vector, + size_t count); + +/** + * @brief Receive the result of the sent iovector. + * + * @param[in] req The tevent request from tstream_writev_queue_send(). + * + * @param[out] perrno The error set to the actual errno. + * + * @return The length of the iovector (0 is never returned!), -1 on + * error with perrno set to the actual errno. + */ +int tstream_writev_queue_recv(struct tevent_req *req, int *perrno); + +/** + * @} + */ + +#endif /* _TSOCKET_H */ + diff --git a/lib/tsocket/tsocket_bsd.c b/lib/tsocket/tsocket_bsd.c new file mode 100644 index 0000000..4483b03 --- /dev/null +++ b/lib/tsocket/tsocket_bsd.c @@ -0,0 +1,2845 @@ +/* + Unix SMB/CIFS implementation. + + Copyright (C) Stefan Metzmacher 2009 + + ** NOTE! The following LGPL license applies to the tsocket + ** library. This does NOT imply that all of Samba is released + ** under the LGPL + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see <http://www.gnu.org/licenses/>. +*/ + +#include "replace.h" +#include "system/filesys.h" +#include "system/network.h" +#include "tsocket.h" +#include "tsocket_internal.h" +#include "lib/util/iov_buf.h" +#include "lib/util/blocking.h" +#include "lib/util/util_net.h" +#include "lib/util/samba_util.h" + +static int tsocket_bsd_error_from_errno(int ret, + int sys_errno, + bool *retry) +{ + *retry = false; + + if (ret >= 0) { + return 0; + } + + if (ret != -1) { + return EIO; + } + + if (sys_errno == 0) { + return EIO; + } + + if (sys_errno == EINTR) { + *retry = true; + return sys_errno; + } + + if (sys_errno == EINPROGRESS) { + *retry = true; + return sys_errno; + } + + if (sys_errno == EAGAIN) { + *retry = true; + return sys_errno; + } + + /* ENOMEM is retryable on Solaris/illumos, and possibly other systems. */ + if (sys_errno == ENOMEM) { + *retry = true; + return sys_errno; + } + +#ifdef EWOULDBLOCK + if (sys_errno == EWOULDBLOCK) { + *retry = true; + return sys_errno; + } +#endif + + return sys_errno; +} + +static int tsocket_bsd_common_prepare_fd(int fd, bool high_fd) +{ + int i; + int sys_errno = 0; + int fds[3]; + int num_fds = 0; + + int result; + bool ok; + + if (fd == -1) { + return -1; + } + + /* first make a fd >= 3 */ + if (high_fd) { + while (fd < 3) { + fds[num_fds++] = fd; + fd = dup(fd); + if (fd == -1) { + sys_errno = errno; + break; + } + } + for (i=0; i<num_fds; i++) { + close(fds[i]); + } + if (fd == -1) { + errno = sys_errno; + return fd; + } + } + + result = set_blocking(fd, false); + if (result == -1) { + goto fail; + } + + ok = smb_set_close_on_exec(fd); + if (!ok) { + goto fail; + } + + return fd; + + fail: + if (fd != -1) { + sys_errno = errno; + close(fd); + errno = sys_errno; + } + return -1; +} + +#ifdef HAVE_LINUX_RTNETLINK_H +/** + * Get the amount of pending bytes from a netlink socket + * + * For some reason netlink sockets don't support querying the amount of pending + * data via ioctl with FIONREAD, which is what we use in tsocket_bsd_pending() + * below. + * + * We know we are on Linux as we're using netlink, which means we have a working + * MSG_TRUNC flag to recvmsg() as well, so we use that together with MSG_PEEK. + **/ +static ssize_t tsocket_bsd_netlink_pending(int fd) +{ + struct iovec iov; + struct msghdr msg; + char buf[1]; + + iov = (struct iovec) { + .iov_base = buf, + .iov_len = sizeof(buf) + }; + + msg = (struct msghdr) { + .msg_iov = &iov, + .msg_iovlen = 1 + }; + + return recvmsg(fd, &msg, MSG_PEEK | MSG_TRUNC); +} +#else +static ssize_t tsocket_bsd_netlink_pending(int fd) +{ + errno = ENOSYS; + return -1; +} +#endif + +static ssize_t tsocket_bsd_pending(int fd) +{ + int ret; + int value = 0; + + ret = ioctl(fd, FIONREAD, &value); + if (ret == -1) { + return ret; + } + + if (ret != 0) { + /* this should not be reached */ + errno = EIO; + return -1; + } + + if (value != 0) { + return value; + } + + return samba_socket_poll_or_sock_error(fd); +} + +static const struct tsocket_address_ops tsocket_address_bsd_ops; + +int _tsocket_address_bsd_from_sockaddr(TALLOC_CTX *mem_ctx, + const struct sockaddr *sa, + size_t sa_socklen, + struct tsocket_address **_addr, + const char *location) +{ + struct tsocket_address *addr; + struct samba_sockaddr *bsda = NULL; + + if (sa_socklen < sizeof(sa->sa_family)) { + errno = EINVAL; + return -1; + } + + switch (sa->sa_family) { + case AF_UNIX: + if (sa_socklen > sizeof(struct sockaddr_un)) { + sa_socklen = sizeof(struct sockaddr_un); + } + break; + case AF_INET: + if (sa_socklen < sizeof(struct sockaddr_in)) { + errno = EINVAL; + return -1; + } + sa_socklen = sizeof(struct sockaddr_in); + break; +#ifdef HAVE_IPV6 + case AF_INET6: + if (sa_socklen < sizeof(struct sockaddr_in6)) { + errno = EINVAL; + return -1; + } + sa_socklen = sizeof(struct sockaddr_in6); + break; +#endif + default: + errno = EAFNOSUPPORT; + return -1; + } + + if (sa_socklen > sizeof(struct sockaddr_storage)) { + errno = EINVAL; + return -1; + } + + addr = tsocket_address_create(mem_ctx, + &tsocket_address_bsd_ops, + &bsda, + struct samba_sockaddr, + location); + if (!addr) { + errno = ENOMEM; + return -1; + } + + ZERO_STRUCTP(bsda); + + memcpy(&bsda->u.ss, sa, sa_socklen); + + bsda->sa_socklen = sa_socklen; +#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN + bsda->u.sa.sa_len = bsda->sa_socklen; +#endif + + *_addr = addr; + return 0; +} + +int _tsocket_address_bsd_from_samba_sockaddr(TALLOC_CTX *mem_ctx, + const struct samba_sockaddr *xs_addr, + struct tsocket_address **t_addr, + const char *location) +{ + return _tsocket_address_bsd_from_sockaddr(mem_ctx, + &xs_addr->u.sa, + xs_addr->sa_socklen, + t_addr, + location); +} + +ssize_t tsocket_address_bsd_sockaddr(const struct tsocket_address *addr, + struct sockaddr *sa, + size_t sa_socklen) +{ + struct samba_sockaddr *bsda = talloc_get_type(addr->private_data, + struct samba_sockaddr); + + if (!bsda) { + errno = EINVAL; + return -1; + } + + if (sa_socklen < bsda->sa_socklen) { + errno = EINVAL; + return -1; + } + + if (sa_socklen > bsda->sa_socklen) { + memset(sa, 0, sa_socklen); + sa_socklen = bsda->sa_socklen; + } + + memcpy(sa, &bsda->u.ss, sa_socklen); +#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN + sa->sa_len = sa_socklen; +#endif + return sa_socklen; +} + +bool tsocket_address_is_inet(const struct tsocket_address *addr, const char *fam) +{ + struct samba_sockaddr *bsda = talloc_get_type(addr->private_data, + struct samba_sockaddr); + + if (!bsda) { + return false; + } + + switch (bsda->u.sa.sa_family) { + case AF_INET: + if (strcasecmp(fam, "ip") == 0) { + return true; + } + + if (strcasecmp(fam, "ipv4") == 0) { + return true; + } + + return false; +#ifdef HAVE_IPV6 + case AF_INET6: + if (strcasecmp(fam, "ip") == 0) { + return true; + } + + if (strcasecmp(fam, "ipv6") == 0) { + return true; + } + + return false; +#endif + } + + return false; +} + +int _tsocket_address_inet_from_strings(TALLOC_CTX *mem_ctx, + const char *fam, + const char *addr, + uint16_t port, + struct tsocket_address **_addr, + const char *location) +{ + struct addrinfo hints; + struct addrinfo *result = NULL; + char port_str[6]; + int ret; + + ZERO_STRUCT(hints); + /* + * we use SOCKET_STREAM here to get just one result + * back from getaddrinfo(). + */ + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV; + + if (strcasecmp(fam, "ip") == 0) { + hints.ai_family = AF_UNSPEC; + if (!addr) { +#ifdef HAVE_IPV6 + addr = "::"; +#else + addr = "0.0.0.0"; +#endif + } + } else if (strcasecmp(fam, "ipv4") == 0) { + hints.ai_family = AF_INET; + if (!addr) { + addr = "0.0.0.0"; + } +#ifdef HAVE_IPV6 + } else if (strcasecmp(fam, "ipv6") == 0) { + hints.ai_family = AF_INET6; + if (!addr) { + addr = "::"; + } +#endif + } else { + errno = EAFNOSUPPORT; + return -1; + } + + snprintf(port_str, sizeof(port_str), "%u", port); + + ret = getaddrinfo(addr, port_str, &hints, &result); + if (ret != 0) { + switch (ret) { + case EAI_FAIL: + case EAI_NONAME: +#ifdef EAI_ADDRFAMILY + case EAI_ADDRFAMILY: +#endif + errno = EINVAL; + break; + } + ret = -1; + goto done; + } + + if (result->ai_socktype != SOCK_STREAM) { + errno = EINVAL; + ret = -1; + goto done; + } + + ret = _tsocket_address_bsd_from_sockaddr(mem_ctx, + result->ai_addr, + result->ai_addrlen, + _addr, + location); + +done: + if (result) { + freeaddrinfo(result); + } + return ret; +} + +int _tsocket_address_inet_from_hostport_strings(TALLOC_CTX *mem_ctx, + const char *fam, + const char *host_port_addr, + uint16_t default_port, + struct tsocket_address **_addr, + const char *location) +{ + char *pl_sq = NULL; + char *pr_sq = NULL; + char *pl_period = NULL; + char *port_sep = NULL; + char *cport = NULL; + char *buf = NULL; + uint64_t port = 0; + int ret; + char *s_addr = NULL; + uint16_t s_port = default_port; + bool conv_ret; + bool is_ipv6_by_squares = false; + + if (host_port_addr == NULL) { + /* got straight to next function if host_port_addr is NULL */ + goto get_addr; + } + buf = talloc_strdup(mem_ctx, host_port_addr); + if (buf == NULL) { + errno = ENOMEM; + return -1; + } + pl_period = strchr_m(buf, '.'); + port_sep = strrchr_m(buf, ':'); + pl_sq = strchr_m(buf, '['); + pr_sq = strrchr_m(buf, ']'); + /* See if its IPv4 or IPv6 */ + /* Only parse IPv6 with squares with/without port, and IPv4 with port */ + /* Everything else, let tsocket_address_inet_from string() */ + /* find parsing errors */ +#ifdef HAVE_IPV6 + is_ipv6_by_squares = (pl_sq != NULL && pr_sq != NULL && pr_sq > pl_sq); +#endif + if (is_ipv6_by_squares) { + /* IPv6 possibly with port - squares detected */ + port_sep = pr_sq + 1; + if (*port_sep == '\0') { + s_addr = pl_sq + 1; + *pr_sq = 0; + s_port = default_port; + goto get_addr; + } + if (*port_sep != ':') { + errno = EINVAL; + return -1; + } + cport = port_sep + 1; + conv_ret = conv_str_u64(cport, &port); + if (!conv_ret) { + errno = EINVAL; + return -1; + } + if (port > 65535) { + errno = EINVAL; + return -1; + } + s_port = (uint16_t)port; + *port_sep = 0; + *pr_sq = 0; + s_addr = pl_sq + 1; + *pl_sq = 0; + goto get_addr; + } else if (pl_period != NULL && port_sep != NULL) { + /* IPv4 with port - more than one period in string */ + cport = port_sep + 1; + conv_ret = conv_str_u64(cport, &port); + if (!conv_ret) { + errno = EINVAL; + return -1; + } + if (port > 65535) { + errno = EINVAL; + return -1; + } + s_port = (uint16_t)port; + *port_sep = 0; + s_addr = buf; + goto get_addr; + } else { + /* Everything else, let tsocket_address_inet_from string() */ + /* find parsing errors */ + s_addr = buf; + s_port = default_port; + goto get_addr; + } +get_addr: + ret = _tsocket_address_inet_from_strings( + mem_ctx, fam, s_addr, s_port, _addr, location); + + return ret; +} + +char *tsocket_address_inet_addr_string(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx) +{ + struct samba_sockaddr *bsda = talloc_get_type(addr->private_data, + struct samba_sockaddr); + char addr_str[INET6_ADDRSTRLEN+1]; + const char *str; + + if (!bsda) { + errno = EINVAL; + return NULL; + } + + switch (bsda->u.sa.sa_family) { + case AF_INET: + str = inet_ntop(bsda->u.in.sin_family, + &bsda->u.in.sin_addr, + addr_str, sizeof(addr_str)); + break; +#ifdef HAVE_IPV6 + case AF_INET6: + str = inet_ntop(bsda->u.in6.sin6_family, + &bsda->u.in6.sin6_addr, + addr_str, sizeof(addr_str)); + break; +#endif + default: + errno = EINVAL; + return NULL; + } + + if (!str) { + return NULL; + } + + return talloc_strdup(mem_ctx, str); +} + +uint16_t tsocket_address_inet_port(const struct tsocket_address *addr) +{ + struct samba_sockaddr *bsda = talloc_get_type(addr->private_data, + struct samba_sockaddr); + uint16_t port = 0; + + if (!bsda) { + errno = EINVAL; + return 0; + } + + switch (bsda->u.sa.sa_family) { + case AF_INET: + port = ntohs(bsda->u.in.sin_port); + break; +#ifdef HAVE_IPV6 + case AF_INET6: + port = ntohs(bsda->u.in6.sin6_port); + break; +#endif + default: + errno = EINVAL; + return 0; + } + + return port; +} + +int tsocket_address_inet_set_port(struct tsocket_address *addr, + uint16_t port) +{ + struct samba_sockaddr *bsda = talloc_get_type(addr->private_data, + struct samba_sockaddr); + + if (!bsda) { + errno = EINVAL; + return -1; + } + + switch (bsda->u.sa.sa_family) { + case AF_INET: + bsda->u.in.sin_port = htons(port); + break; +#ifdef HAVE_IPV6 + case AF_INET6: + bsda->u.in6.sin6_port = htons(port); + break; +#endif + default: + errno = EINVAL; + return -1; + } + + return 0; +} + +bool tsocket_address_is_unix(const struct tsocket_address *addr) +{ + struct samba_sockaddr *bsda = talloc_get_type(addr->private_data, + struct samba_sockaddr); + + if (!bsda) { + return false; + } + + switch (bsda->u.sa.sa_family) { + case AF_UNIX: + return true; + } + + return false; +} + +int _tsocket_address_unix_from_path(TALLOC_CTX *mem_ctx, + const char *path, + struct tsocket_address **_addr, + const char *location) +{ + struct sockaddr_un un; + void *p = &un; + int ret; + + if (!path) { + path = ""; + } + + if (strlen(path) > sizeof(un.sun_path)-1) { + errno = ENAMETOOLONG; + return -1; + } + + ZERO_STRUCT(un); + un.sun_family = AF_UNIX; + strncpy(un.sun_path, path, sizeof(un.sun_path)-1); + + ret = _tsocket_address_bsd_from_sockaddr(mem_ctx, + (struct sockaddr *)p, + sizeof(un), + _addr, + location); + + return ret; +} + +char *tsocket_address_unix_path(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx) +{ + struct samba_sockaddr *bsda = talloc_get_type(addr->private_data, + struct samba_sockaddr); + const char *str; + + if (!bsda) { + errno = EINVAL; + return NULL; + } + + switch (bsda->u.sa.sa_family) { + case AF_UNIX: + str = bsda->u.un.sun_path; + break; + default: + errno = EINVAL; + return NULL; + } + + return talloc_strdup(mem_ctx, str); +} + +static char *tsocket_address_bsd_string(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx) +{ + struct samba_sockaddr *bsda = talloc_get_type(addr->private_data, + struct samba_sockaddr); + char *str; + char *addr_str; + const char *prefix = NULL; + uint16_t port; + + switch (bsda->u.sa.sa_family) { + case AF_UNIX: + return talloc_asprintf(mem_ctx, "unix:%s", + bsda->u.un.sun_path); + case AF_INET: + prefix = "ipv4"; + break; +#ifdef HAVE_IPV6 + case AF_INET6: + prefix = "ipv6"; + break; +#endif + default: + errno = EINVAL; + return NULL; + } + + addr_str = tsocket_address_inet_addr_string(addr, mem_ctx); + if (!addr_str) { + return NULL; + } + + port = tsocket_address_inet_port(addr); + + str = talloc_asprintf(mem_ctx, "%s:%s:%u", + prefix, addr_str, port); + talloc_free(addr_str); + + return str; +} + +static struct tsocket_address *tsocket_address_bsd_copy(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx, + const char *location) +{ + struct samba_sockaddr *bsda = talloc_get_type(addr->private_data, + struct samba_sockaddr); + struct tsocket_address *copy; + int ret; + + ret = _tsocket_address_bsd_from_sockaddr(mem_ctx, + &bsda->u.sa, + bsda->sa_socklen, + ©, + location); + if (ret != 0) { + return NULL; + } + + return copy; +} + +static const struct tsocket_address_ops tsocket_address_bsd_ops = { + .name = "bsd", + .string = tsocket_address_bsd_string, + .copy = tsocket_address_bsd_copy, +}; + +struct tdgram_bsd { + int fd; + + void *event_ptr; + struct tevent_fd *fde; + bool optimize_recvfrom; + bool netlink; + + void *readable_private; + void (*readable_handler)(void *private_data); + void *writeable_private; + void (*writeable_handler)(void *private_data); +}; + +bool tdgram_bsd_optimize_recvfrom(struct tdgram_context *dgram, + bool on) +{ + struct tdgram_bsd *bsds = + talloc_get_type(_tdgram_context_data(dgram), + struct tdgram_bsd); + bool old; + + if (bsds == NULL) { + /* not a bsd socket */ + return false; + } + + old = bsds->optimize_recvfrom; + bsds->optimize_recvfrom = on; + + return old; +} + +static void tdgram_bsd_fde_handler(struct tevent_context *ev, + struct tevent_fd *fde, + uint16_t flags, + void *private_data) +{ + struct tdgram_bsd *bsds = talloc_get_type_abort(private_data, + struct tdgram_bsd); + + if (flags & TEVENT_FD_WRITE) { + bsds->writeable_handler(bsds->writeable_private); + return; + } + if (flags & TEVENT_FD_READ) { + if (!bsds->readable_handler) { + TEVENT_FD_NOT_READABLE(bsds->fde); + return; + } + bsds->readable_handler(bsds->readable_private); + return; + } +} + +static int tdgram_bsd_set_readable_handler(struct tdgram_bsd *bsds, + struct tevent_context *ev, + void (*handler)(void *private_data), + void *private_data) +{ + if (ev == NULL) { + if (handler) { + errno = EINVAL; + return -1; + } + if (!bsds->readable_handler) { + return 0; + } + bsds->readable_handler = NULL; + bsds->readable_private = NULL; + + return 0; + } + + /* read and write must use the same tevent_context */ + if (bsds->event_ptr != ev) { + if (bsds->readable_handler || bsds->writeable_handler) { + errno = EINVAL; + return -1; + } + bsds->event_ptr = NULL; + TALLOC_FREE(bsds->fde); + } + + if (tevent_fd_get_flags(bsds->fde) == 0) { + TALLOC_FREE(bsds->fde); + + bsds->fde = tevent_add_fd(ev, bsds, + bsds->fd, TEVENT_FD_READ, + tdgram_bsd_fde_handler, + bsds); + if (!bsds->fde) { + errno = ENOMEM; + return -1; + } + + /* cache the event context we're running on */ + bsds->event_ptr = ev; + } else if (!bsds->readable_handler) { + TEVENT_FD_READABLE(bsds->fde); + } + + bsds->readable_handler = handler; + bsds->readable_private = private_data; + + return 0; +} + +static int tdgram_bsd_set_writeable_handler(struct tdgram_bsd *bsds, + struct tevent_context *ev, + void (*handler)(void *private_data), + void *private_data) +{ + if (ev == NULL) { + if (handler) { + errno = EINVAL; + return -1; + } + if (!bsds->writeable_handler) { + return 0; + } + bsds->writeable_handler = NULL; + bsds->writeable_private = NULL; + TEVENT_FD_NOT_WRITEABLE(bsds->fde); + + return 0; + } + + /* read and write must use the same tevent_context */ + if (bsds->event_ptr != ev) { + if (bsds->readable_handler || bsds->writeable_handler) { + errno = EINVAL; + return -1; + } + bsds->event_ptr = NULL; + TALLOC_FREE(bsds->fde); + } + + if (tevent_fd_get_flags(bsds->fde) == 0) { + TALLOC_FREE(bsds->fde); + + bsds->fde = tevent_add_fd(ev, bsds, + bsds->fd, TEVENT_FD_WRITE, + tdgram_bsd_fde_handler, + bsds); + if (!bsds->fde) { + errno = ENOMEM; + return -1; + } + + /* cache the event context we're running on */ + bsds->event_ptr = ev; + } else if (!bsds->writeable_handler) { + TEVENT_FD_WRITEABLE(bsds->fde); + } + + bsds->writeable_handler = handler; + bsds->writeable_private = private_data; + + return 0; +} + +struct tdgram_bsd_recvfrom_state { + struct tdgram_context *dgram; + bool first_try; + uint8_t *buf; + size_t len; + struct tsocket_address *src; +}; + +static int tdgram_bsd_recvfrom_destructor(struct tdgram_bsd_recvfrom_state *state) +{ + struct tdgram_bsd *bsds = tdgram_context_data(state->dgram, + struct tdgram_bsd); + + tdgram_bsd_set_readable_handler(bsds, NULL, NULL, NULL); + + return 0; +} + +static void tdgram_bsd_recvfrom_handler(void *private_data); + +static struct tevent_req *tdgram_bsd_recvfrom_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram) +{ + struct tevent_req *req; + struct tdgram_bsd_recvfrom_state *state; + struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd); + int ret; + + req = tevent_req_create(mem_ctx, &state, + struct tdgram_bsd_recvfrom_state); + if (!req) { + return NULL; + } + + state->dgram = dgram; + state->first_try= true; + state->buf = NULL; + state->len = 0; + state->src = NULL; + + talloc_set_destructor(state, tdgram_bsd_recvfrom_destructor); + + if (bsds->fd == -1) { + tevent_req_error(req, ENOTCONN); + goto post; + } + + + /* + * this is a fast path, not waiting for the + * socket to become explicit readable gains + * about 10%-20% performance in benchmark tests. + */ + if (bsds->optimize_recvfrom) { + /* + * We only do the optimization on + * recvfrom if the caller asked for it. + * + * This is needed because in most cases + * we prefer to flush send buffers before + * receiving incoming requests. + */ + tdgram_bsd_recvfrom_handler(req); + if (!tevent_req_is_in_progress(req)) { + goto post; + } + } + + ret = tdgram_bsd_set_readable_handler(bsds, ev, + tdgram_bsd_recvfrom_handler, + req); + if (ret == -1) { + tevent_req_error(req, errno); + goto post; + } + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tdgram_bsd_recvfrom_handler(void *private_data) +{ + struct tevent_req *req = talloc_get_type_abort(private_data, + struct tevent_req); + struct tdgram_bsd_recvfrom_state *state = tevent_req_data(req, + struct tdgram_bsd_recvfrom_state); + struct tdgram_context *dgram = state->dgram; + struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd); + struct samba_sockaddr *bsda = NULL; + ssize_t ret; + int err; + bool retry; + + if (bsds->netlink) { + ret = tsocket_bsd_netlink_pending(bsds->fd); + } else { + ret = tsocket_bsd_pending(bsds->fd); + } + + if (state->first_try && ret == 0) { + state->first_try = false; + /* retry later */ + return; + } + state->first_try = false; + + err = tsocket_bsd_error_from_errno(ret, errno, &retry); + if (retry) { + /* retry later */ + return; + } + if (tevent_req_error(req, err)) { + return; + } + + /* note that 'ret' can be 0 here */ + state->buf = talloc_array(state, uint8_t, ret); + if (tevent_req_nomem(state->buf, req)) { + return; + } + state->len = ret; + + state->src = tsocket_address_create(state, + &tsocket_address_bsd_ops, + &bsda, + struct samba_sockaddr, + __location__ "bsd_recvfrom"); + if (tevent_req_nomem(state->src, req)) { + return; + } + + ZERO_STRUCTP(bsda); + bsda->sa_socklen = sizeof(bsda->u.ss); +#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN + bsda->u.sa.sa_len = bsda->sa_socklen; +#endif + + ret = recvfrom(bsds->fd, state->buf, state->len, 0, + &bsda->u.sa, &bsda->sa_socklen); + err = tsocket_bsd_error_from_errno(ret, errno, &retry); + if (retry) { + /* retry later */ + return; + } + if (tevent_req_error(req, err)) { + return; + } + + /* + * Some systems (FreeBSD, see bug #7115) return too much + * bytes in tsocket_bsd_pending()/ioctl(fd, FIONREAD, ...), + * the return value includes some IP/UDP header bytes, + * while recvfrom() just returns the payload. + */ + state->buf = talloc_realloc(state, state->buf, uint8_t, ret); + if (tevent_req_nomem(state->buf, req)) { + return; + } + state->len = ret; + + tevent_req_done(req); +} + +static ssize_t tdgram_bsd_recvfrom_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + uint8_t **buf, + struct tsocket_address **src) +{ + struct tdgram_bsd_recvfrom_state *state = tevent_req_data(req, + struct tdgram_bsd_recvfrom_state); + ssize_t ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + *buf = talloc_move(mem_ctx, &state->buf); + ret = state->len; + if (src) { + *src = talloc_move(mem_ctx, &state->src); + } + } + + tevent_req_received(req); + return ret; +} + +struct tdgram_bsd_sendto_state { + struct tdgram_context *dgram; + + const uint8_t *buf; + size_t len; + const struct tsocket_address *dst; + + ssize_t ret; +}; + +static int tdgram_bsd_sendto_destructor(struct tdgram_bsd_sendto_state *state) +{ + struct tdgram_bsd *bsds = tdgram_context_data(state->dgram, + struct tdgram_bsd); + + tdgram_bsd_set_writeable_handler(bsds, NULL, NULL, NULL); + + return 0; +} + +static void tdgram_bsd_sendto_handler(void *private_data); + +static struct tevent_req *tdgram_bsd_sendto_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram, + const uint8_t *buf, + size_t len, + const struct tsocket_address *dst) +{ + struct tevent_req *req; + struct tdgram_bsd_sendto_state *state; + struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd); + int ret; + + req = tevent_req_create(mem_ctx, &state, + struct tdgram_bsd_sendto_state); + if (!req) { + return NULL; + } + + state->dgram = dgram; + state->buf = buf; + state->len = len; + state->dst = dst; + state->ret = -1; + + talloc_set_destructor(state, tdgram_bsd_sendto_destructor); + + if (bsds->fd == -1) { + tevent_req_error(req, ENOTCONN); + goto post; + } + + /* + * this is a fast path, not waiting for the + * socket to become explicit writeable gains + * about 10%-20% performance in benchmark tests. + */ + tdgram_bsd_sendto_handler(req); + if (!tevent_req_is_in_progress(req)) { + goto post; + } + + ret = tdgram_bsd_set_writeable_handler(bsds, ev, + tdgram_bsd_sendto_handler, + req); + if (ret == -1) { + tevent_req_error(req, errno); + goto post; + } + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tdgram_bsd_sendto_handler(void *private_data) +{ + struct tevent_req *req = talloc_get_type_abort(private_data, + struct tevent_req); + struct tdgram_bsd_sendto_state *state = tevent_req_data(req, + struct tdgram_bsd_sendto_state); + struct tdgram_context *dgram = state->dgram; + struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd); + struct sockaddr *sa = NULL; + socklen_t sa_socklen = 0; + ssize_t ret; + int err; + bool retry; + + if (state->dst) { + struct samba_sockaddr *bsda = + talloc_get_type(state->dst->private_data, + struct samba_sockaddr); + + sa = &bsda->u.sa; + sa_socklen = bsda->sa_socklen; + } + + ret = sendto(bsds->fd, state->buf, state->len, 0, sa, sa_socklen); + err = tsocket_bsd_error_from_errno(ret, errno, &retry); + if (retry) { + /* retry later */ + return; + } + + if (err == EMSGSIZE) { + /* round up in 1K increments */ + int bufsize = ((state->len + 1023) & (~1023)); + + ret = setsockopt(bsds->fd, SOL_SOCKET, SO_SNDBUF, &bufsize, + sizeof(bufsize)); + if (ret == 0) { + /* + * We do the retry here, rather then via the + * handler, as we only want to retry once for + * this condition, so if there is a mismatch + * between what setsockopt() accepts and what can + * actually be sent, we do not end up in a + * loop. + */ + + ret = sendto(bsds->fd, state->buf, state->len, + 0, sa, sa_socklen); + err = tsocket_bsd_error_from_errno(ret, errno, &retry); + if (retry) { /* retry later */ + return; + } + } + } + + if (tevent_req_error(req, err)) { + return; + } + + state->ret = ret; + + tevent_req_done(req); +} + +static ssize_t tdgram_bsd_sendto_recv(struct tevent_req *req, int *perrno) +{ + struct tdgram_bsd_sendto_state *state = tevent_req_data(req, + struct tdgram_bsd_sendto_state); + ssize_t ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = state->ret; + } + + tevent_req_received(req); + return ret; +} + +struct tdgram_bsd_disconnect_state { + uint8_t __dummy; +}; + +static struct tevent_req *tdgram_bsd_disconnect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram) +{ + struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd); + struct tevent_req *req; + struct tdgram_bsd_disconnect_state *state; + int ret; + int err; + bool dummy; + + req = tevent_req_create(mem_ctx, &state, + struct tdgram_bsd_disconnect_state); + if (req == NULL) { + return NULL; + } + + if (bsds->fd == -1) { + tevent_req_error(req, ENOTCONN); + goto post; + } + + TALLOC_FREE(bsds->fde); + ret = close(bsds->fd); + bsds->fd = -1; + err = tsocket_bsd_error_from_errno(ret, errno, &dummy); + if (tevent_req_error(req, err)) { + goto post; + } + + tevent_req_done(req); +post: + tevent_req_post(req, ev); + return req; +} + +static int tdgram_bsd_disconnect_recv(struct tevent_req *req, + int *perrno) +{ + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + + tevent_req_received(req); + return ret; +} + +static const struct tdgram_context_ops tdgram_bsd_ops = { + .name = "bsd", + + .recvfrom_send = tdgram_bsd_recvfrom_send, + .recvfrom_recv = tdgram_bsd_recvfrom_recv, + + .sendto_send = tdgram_bsd_sendto_send, + .sendto_recv = tdgram_bsd_sendto_recv, + + .disconnect_send = tdgram_bsd_disconnect_send, + .disconnect_recv = tdgram_bsd_disconnect_recv, +}; + +static int tdgram_bsd_destructor(struct tdgram_bsd *bsds) +{ + TALLOC_FREE(bsds->fde); + if (bsds->fd != -1) { + close(bsds->fd); + bsds->fd = -1; + } + return 0; +} + +static int tdgram_bsd_dgram_socket(const struct tsocket_address *local, + const struct tsocket_address *remote, + bool broadcast, + TALLOC_CTX *mem_ctx, + struct tdgram_context **_dgram, + const char *location) +{ + struct samba_sockaddr *lbsda = + talloc_get_type_abort(local->private_data, + struct samba_sockaddr); + struct samba_sockaddr *rbsda = NULL; + struct tdgram_context *dgram; + struct tdgram_bsd *bsds; + int fd; + int ret; + bool do_bind = false; + bool do_reuseaddr = false; + bool do_ipv6only = false; + bool is_inet = false; + int sa_fam = lbsda->u.sa.sa_family; + + if (remote) { + rbsda = talloc_get_type_abort(remote->private_data, + struct samba_sockaddr); + } + + switch (lbsda->u.sa.sa_family) { + case AF_UNIX: + if (broadcast) { + errno = EINVAL; + return -1; + } + if (lbsda->u.un.sun_path[0] != 0) { + do_reuseaddr = true; + do_bind = true; + } + break; + case AF_INET: + if (lbsda->u.in.sin_port != 0) { + do_reuseaddr = true; + do_bind = true; + } + if (lbsda->u.in.sin_addr.s_addr != INADDR_ANY) { + do_bind = true; + } + is_inet = true; + break; +#ifdef HAVE_IPV6 + case AF_INET6: + if (lbsda->u.in6.sin6_port != 0) { + do_reuseaddr = true; + do_bind = true; + } + if (memcmp(&in6addr_any, + &lbsda->u.in6.sin6_addr, + sizeof(in6addr_any)) != 0) { + do_bind = true; + } + is_inet = true; + do_ipv6only = true; + break; +#endif + default: + errno = EINVAL; + return -1; + } + + if (!do_bind && is_inet && rbsda) { + sa_fam = rbsda->u.sa.sa_family; + switch (sa_fam) { + case AF_INET: + do_ipv6only = false; + break; +#ifdef HAVE_IPV6 + case AF_INET6: + do_ipv6only = true; + break; +#endif + } + } + + fd = socket(sa_fam, SOCK_DGRAM, 0); + if (fd < 0) { + return -1; + } + + fd = tsocket_bsd_common_prepare_fd(fd, true); + if (fd < 0) { + return -1; + } + + dgram = tdgram_context_create(mem_ctx, + &tdgram_bsd_ops, + &bsds, + struct tdgram_bsd, + location); + if (!dgram) { + int saved_errno = errno; + close(fd); + errno = saved_errno; + return -1; + } + ZERO_STRUCTP(bsds); + bsds->fd = fd; + talloc_set_destructor(bsds, tdgram_bsd_destructor); + +#ifdef HAVE_IPV6 + if (do_ipv6only) { + int val = 1; + + ret = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, + (const void *)&val, sizeof(val)); + if (ret == -1) { + int saved_errno = errno; + talloc_free(dgram); + errno = saved_errno; + return -1; + } + } +#endif + + if (broadcast) { + int val = 1; + + ret = setsockopt(fd, SOL_SOCKET, SO_BROADCAST, + (const void *)&val, sizeof(val)); + if (ret == -1) { + int saved_errno = errno; + talloc_free(dgram); + errno = saved_errno; + return -1; + } + } + + if (do_reuseaddr) { + int val = 1; + + ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, + (const void *)&val, sizeof(val)); + if (ret == -1) { + int saved_errno = errno; + talloc_free(dgram); + errno = saved_errno; + return -1; + } + } + + if (do_bind) { + ret = bind(fd, &lbsda->u.sa, lbsda->sa_socklen); + if (ret == -1) { + int saved_errno = errno; + talloc_free(dgram); + errno = saved_errno; + return -1; + } + } + + if (rbsda) { + if (rbsda->u.sa.sa_family != sa_fam) { + talloc_free(dgram); + errno = EINVAL; + return -1; + } + + ret = connect(fd, &rbsda->u.sa, rbsda->sa_socklen); + if (ret == -1) { + int saved_errno = errno; + talloc_free(dgram); + errno = saved_errno; + return -1; + } + } + + *_dgram = dgram; + return 0; +} + +int _tdgram_bsd_existing_socket(TALLOC_CTX *mem_ctx, + int fd, + struct tdgram_context **_dgram, + const char *location) +{ + struct tdgram_context *dgram; + struct tdgram_bsd *bsds; +#ifdef HAVE_LINUX_RTNETLINK_H + int result; + struct sockaddr sa; + socklen_t sa_len = sizeof(struct sockaddr); +#endif + + dgram = tdgram_context_create(mem_ctx, + &tdgram_bsd_ops, + &bsds, + struct tdgram_bsd, + location); + if (!dgram) { + return -1; + } + ZERO_STRUCTP(bsds); + bsds->fd = fd; + talloc_set_destructor(bsds, tdgram_bsd_destructor); + + *_dgram = dgram; + +#ifdef HAVE_LINUX_RTNETLINK_H + /* + * Try to determine the protocol family and remember if it's + * AF_NETLINK. We don't care if this fails. + */ + result = getsockname(fd, &sa, &sa_len); + if (result == 0 && sa.sa_family == AF_NETLINK) { + bsds->netlink = true; + } +#endif + + return 0; +} + +int _tdgram_inet_udp_socket(const struct tsocket_address *local, + const struct tsocket_address *remote, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram, + const char *location) +{ + struct samba_sockaddr *lbsda = + talloc_get_type_abort(local->private_data, + struct samba_sockaddr); + int ret; + + switch (lbsda->u.sa.sa_family) { + case AF_INET: + break; +#ifdef HAVE_IPV6 + case AF_INET6: + break; +#endif + default: + errno = EINVAL; + return -1; + } + + ret = tdgram_bsd_dgram_socket(local, remote, false, + mem_ctx, dgram, location); + + return ret; +} + +int _tdgram_inet_udp_broadcast_socket(const struct tsocket_address *local, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram, + const char *location) +{ + struct samba_sockaddr *lbsda = + talloc_get_type_abort(local->private_data, + struct samba_sockaddr); + int ret; + + switch (lbsda->u.sa.sa_family) { + case AF_INET: + break; +#ifdef HAVE_IPV6 + case AF_INET6: + /* only ipv4 */ + errno = EINVAL; + return -1; +#endif + default: + errno = EINVAL; + return -1; + } + + ret = tdgram_bsd_dgram_socket(local, NULL, true, + mem_ctx, dgram, location); + + return ret; +} + +int _tdgram_unix_socket(const struct tsocket_address *local, + const struct tsocket_address *remote, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram, + const char *location) +{ + struct samba_sockaddr *lbsda = + talloc_get_type_abort(local->private_data, + struct samba_sockaddr); + int ret; + + switch (lbsda->u.sa.sa_family) { + case AF_UNIX: + break; + default: + errno = EINVAL; + return -1; + } + + ret = tdgram_bsd_dgram_socket(local, remote, false, + mem_ctx, dgram, location); + + return ret; +} + +struct tstream_bsd { + int fd; + int error; + + void *event_ptr; + struct tevent_fd *fde; + bool optimize_readv; + bool fail_readv_first_error; + + void *readable_private; + void (*readable_handler)(void *private_data); + void *writeable_private; + void (*writeable_handler)(void *private_data); +}; + +bool tstream_bsd_optimize_readv(struct tstream_context *stream, + bool on) +{ + struct tstream_bsd *bsds = + talloc_get_type(_tstream_context_data(stream), + struct tstream_bsd); + bool old; + + if (bsds == NULL) { + /* not a bsd socket */ + return false; + } + + old = bsds->optimize_readv; + bsds->optimize_readv = on; + + return old; +} + +bool tstream_bsd_fail_readv_first_error(struct tstream_context *stream, + bool on) +{ + struct tstream_bsd *bsds = + talloc_get_type(_tstream_context_data(stream), + struct tstream_bsd); + bool old; + + if (bsds == NULL) { + /* not a bsd socket */ + return false; + } + + old = bsds->fail_readv_first_error; + bsds->fail_readv_first_error = on; + + return old; +} + +static void tstream_bsd_fde_handler(struct tevent_context *ev, + struct tevent_fd *fde, + uint16_t flags, + void *private_data) +{ + struct tstream_bsd *bsds = talloc_get_type_abort(private_data, + struct tstream_bsd); + + if (flags & TEVENT_FD_ERROR) { + /* + * We lazily keep TEVENT_FD_READ alive + * in tstream_bsd_set_readable_handler() + * + * So we have to check TEVENT_FD_READ + * as well as bsds->readable_handler + * + * We only drain remaining data from the + * the recv queue if available and desired. + */ + if ((flags & TEVENT_FD_READ) && + !bsds->fail_readv_first_error && + (bsds->readable_handler != NULL)) + { + /* + * If there's still data to read + * we allow it to be read until + * we reach EOF (=> EPIPE). + */ + bsds->readable_handler(bsds->readable_private); + return; + } + + /* + * If there's no data left to read, + * we get the error. + * + * It means we no longer call any readv or + * writev, as bsds->error is checked first. + */ + if (bsds->error == 0) { + int ret = samba_socket_poll_or_sock_error(bsds->fd); + + if (ret == -1) { + bsds->error = errno; + } + /* fallback to EPIPE */ + if (bsds->error == 0) { + bsds->error = EPIPE; + } + } + + /* + * Let write to fail early. + * + * Note we only need to check TEVENT_FD_WRITE + * as tstream_bsd_set_writeable_handler() + * clear it together with the handler. + */ + if (flags & TEVENT_FD_WRITE) { + bsds->writeable_handler(bsds->writeable_private); + return; + } + + /* We prefer the readable handler to fire first. */ + if (bsds->readable_handler != NULL) { + bsds->readable_handler(bsds->readable_private); + return; + } + + /* As last resort we notify the writeable handler */ + if (bsds->writeable_handler != NULL) { + bsds->writeable_handler(bsds->writeable_private); + return; + } + + /* + * We may hit this because we don't clear TEVENT_FD_ERROR + * in tstream_bsd_set_readable_handler() nor + * tstream_bsd_set_writeable_handler(). + * + * As we already captured the error, we can remove + * the fde completely. + */ + TALLOC_FREE(bsds->fde); + return; + } + if (flags & TEVENT_FD_WRITE) { + bsds->writeable_handler(bsds->writeable_private); + return; + } + if (flags & TEVENT_FD_READ) { + if (!bsds->readable_handler) { + /* + * tstream_bsd_set_readable_handler + * doesn't clear TEVENT_FD_READ. + * + * In order to avoid cpu-spinning + * we need to clear it here. + */ + TEVENT_FD_NOT_READABLE(bsds->fde); + + /* + * Here we're lazy and keep TEVENT_FD_ERROR + * alive. If it's triggered the next time + * we'll handle it gracefully above + * and end up with TALLOC_FREE(bsds->fde); + * in order to spin on TEVENT_FD_ERROR. + */ + return; + } + bsds->readable_handler(bsds->readable_private); + return; + } +} + +static int tstream_bsd_set_readable_handler(struct tstream_bsd *bsds, + struct tevent_context *ev, + void (*handler)(void *private_data), + void *private_data) +{ + if (ev == NULL) { + if (handler) { + errno = EINVAL; + return -1; + } + if (!bsds->readable_handler) { + return 0; + } + bsds->readable_handler = NULL; + bsds->readable_private = NULL; + + /* + * Here we are lazy as it's very likely that the next + * tevent_readv_send() will come in shortly, + * so we keep TEVENT_FD_READ alive. + */ + return 0; + } + + /* read and write must use the same tevent_context */ + if (bsds->event_ptr != ev) { + if (bsds->readable_handler || bsds->writeable_handler) { + errno = EINVAL; + return -1; + } + bsds->event_ptr = NULL; + TALLOC_FREE(bsds->fde); + } + + if (tevent_fd_get_flags(bsds->fde) == 0) { + TALLOC_FREE(bsds->fde); + + bsds->fde = tevent_add_fd(ev, bsds, + bsds->fd, + TEVENT_FD_ERROR | TEVENT_FD_READ, + tstream_bsd_fde_handler, + bsds); + if (!bsds->fde) { + errno = ENOMEM; + return -1; + } + + /* cache the event context we're running on */ + bsds->event_ptr = ev; + } else if (!bsds->readable_handler) { + TEVENT_FD_READABLE(bsds->fde); + /* + * TEVENT_FD_ERROR is likely already set, so + * TEVENT_FD_WANTERROR() is most likely a no-op. + */ + TEVENT_FD_WANTERROR(bsds->fde); + } + + bsds->readable_handler = handler; + bsds->readable_private = private_data; + + return 0; +} + +static int tstream_bsd_set_writeable_handler(struct tstream_bsd *bsds, + struct tevent_context *ev, + void (*handler)(void *private_data), + void *private_data) +{ + if (ev == NULL) { + if (handler) { + errno = EINVAL; + return -1; + } + if (!bsds->writeable_handler) { + return 0; + } + bsds->writeable_handler = NULL; + bsds->writeable_private = NULL; + + /* + * The writeable handler is only + * set if we got EAGAIN or a short + * writev on the first try, so + * this isn't the hot path. + * + * Here we are lazy and leave TEVENT_FD_ERROR + * alive as it's shared with the readable + * handler. So we only clear TEVENT_FD_WRITE. + */ + TEVENT_FD_NOT_WRITEABLE(bsds->fde); + return 0; + } + + /* read and write must use the same tevent_context */ + if (bsds->event_ptr != ev) { + if (bsds->readable_handler || bsds->writeable_handler) { + errno = EINVAL; + return -1; + } + bsds->event_ptr = NULL; + TALLOC_FREE(bsds->fde); + } + + if (tevent_fd_get_flags(bsds->fde) == 0) { + TALLOC_FREE(bsds->fde); + + bsds->fde = tevent_add_fd(ev, bsds, + bsds->fd, + TEVENT_FD_ERROR | TEVENT_FD_WRITE, + tstream_bsd_fde_handler, + bsds); + if (!bsds->fde) { + errno = ENOMEM; + return -1; + } + + /* cache the event context we're running on */ + bsds->event_ptr = ev; + } else if (!bsds->writeable_handler) { + TEVENT_FD_WRITEABLE(bsds->fde); + /* + * TEVENT_FD_ERROR is likely already set, so + * TEVENT_FD_WANTERROR() is most likely a no-op. + */ + TEVENT_FD_WANTERROR(bsds->fde); + } + + bsds->writeable_handler = handler; + bsds->writeable_private = private_data; + + return 0; +} + +static ssize_t tstream_bsd_pending_bytes(struct tstream_context *stream) +{ + struct tstream_bsd *bsds = tstream_context_data(stream, + struct tstream_bsd); + ssize_t ret; + + if (bsds->fd == -1) { + errno = ENOTCONN; + return -1; + } + + if (bsds->error != 0) { + errno = bsds->error; + return -1; + } + + ret = tsocket_bsd_pending(bsds->fd); + if (ret == -1) { + /* + * remember the error and don't + * allow further requests + */ + bsds->error = errno; + } + + return ret; +} + +struct tstream_bsd_readv_state { + struct tstream_context *stream; + + struct iovec *vector; + size_t count; + + int ret; +}; + +static int tstream_bsd_readv_destructor(struct tstream_bsd_readv_state *state) +{ + struct tstream_bsd *bsds = tstream_context_data(state->stream, + struct tstream_bsd); + + tstream_bsd_set_readable_handler(bsds, NULL, NULL, NULL); + + return 0; +} + +static void tstream_bsd_readv_handler(void *private_data); + +static struct tevent_req *tstream_bsd_readv_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct iovec *vector, + size_t count) +{ + struct tevent_req *req; + struct tstream_bsd_readv_state *state; + struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd); + int ret; + + req = tevent_req_create(mem_ctx, &state, + struct tstream_bsd_readv_state); + if (!req) { + return NULL; + } + + state->stream = stream; + /* we make a copy of the vector so that we can modify it */ + state->vector = talloc_array(state, struct iovec, count); + if (tevent_req_nomem(state->vector, req)) { + goto post; + } + memcpy(state->vector, vector, sizeof(struct iovec)*count); + state->count = count; + state->ret = 0; + + talloc_set_destructor(state, tstream_bsd_readv_destructor); + + if (bsds->fd == -1) { + tevent_req_error(req, ENOTCONN); + goto post; + } + + /* + * this is a fast path, not waiting for the + * socket to become explicit readable gains + * about 10%-20% performance in benchmark tests. + */ + if (bsds->optimize_readv) { + /* + * We only do the optimization on + * readv if the caller asked for it. + * + * This is needed because in most cases + * we prefer to flush send buffers before + * receiving incoming requests. + */ + tstream_bsd_readv_handler(req); + if (!tevent_req_is_in_progress(req)) { + goto post; + } + } + + ret = tstream_bsd_set_readable_handler(bsds, ev, + tstream_bsd_readv_handler, + req); + if (ret == -1) { + tevent_req_error(req, errno); + goto post; + } + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tstream_bsd_readv_handler(void *private_data) +{ + struct tevent_req *req = talloc_get_type_abort(private_data, + struct tevent_req); + struct tstream_bsd_readv_state *state = tevent_req_data(req, + struct tstream_bsd_readv_state); + struct tstream_context *stream = state->stream; + struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd); + int ret; + int err; + int _count; + bool ok, retry; + + if (bsds->error != 0) { + tevent_req_error(req, bsds->error); + return; + } + + ret = readv(bsds->fd, state->vector, state->count); + if (ret == 0) { + /* propagate end of file */ + bsds->error = EPIPE; + tevent_req_error(req, EPIPE); + return; + } + err = tsocket_bsd_error_from_errno(ret, errno, &retry); + if (retry) { + /* retry later */ + return; + } + if (err != 0) { + /* + * remember the error and don't + * allow further requests + */ + bsds->error = err; + } + if (tevent_req_error(req, err)) { + return; + } + + state->ret += ret; + + _count = state->count; /* tstream has size_t count, readv has int */ + ok = iov_advance(&state->vector, &_count, ret); + state->count = _count; + + if (!ok) { + tevent_req_error(req, EINVAL); + return; + } + + if (state->count > 0) { + /* we have more to read */ + return; + } + + tevent_req_done(req); +} + +static int tstream_bsd_readv_recv(struct tevent_req *req, + int *perrno) +{ + struct tstream_bsd_readv_state *state = tevent_req_data(req, + struct tstream_bsd_readv_state); + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = state->ret; + } + + tevent_req_received(req); + return ret; +} + +struct tstream_bsd_writev_state { + struct tstream_context *stream; + + struct iovec *vector; + size_t count; + + int ret; +}; + +static int tstream_bsd_writev_destructor(struct tstream_bsd_writev_state *state) +{ + struct tstream_bsd *bsds = tstream_context_data(state->stream, + struct tstream_bsd); + + tstream_bsd_set_writeable_handler(bsds, NULL, NULL, NULL); + + return 0; +} + +static void tstream_bsd_writev_handler(void *private_data); + +static struct tevent_req *tstream_bsd_writev_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + const struct iovec *vector, + size_t count) +{ + struct tevent_req *req; + struct tstream_bsd_writev_state *state; + struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd); + int ret; + + req = tevent_req_create(mem_ctx, &state, + struct tstream_bsd_writev_state); + if (!req) { + return NULL; + } + + state->stream = stream; + /* we make a copy of the vector so that we can modify it */ + state->vector = talloc_array(state, struct iovec, count); + if (tevent_req_nomem(state->vector, req)) { + goto post; + } + memcpy(state->vector, vector, sizeof(struct iovec)*count); + state->count = count; + state->ret = 0; + + talloc_set_destructor(state, tstream_bsd_writev_destructor); + + if (bsds->fd == -1) { + tevent_req_error(req, ENOTCONN); + goto post; + } + + /* + * this is a fast path, not waiting for the + * socket to become explicit writeable gains + * about 10%-20% performance in benchmark tests. + */ + tstream_bsd_writev_handler(req); + if (!tevent_req_is_in_progress(req)) { + goto post; + } + + ret = tstream_bsd_set_writeable_handler(bsds, ev, + tstream_bsd_writev_handler, + req); + if (ret == -1) { + tevent_req_error(req, errno); + goto post; + } + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tstream_bsd_writev_handler(void *private_data) +{ + struct tevent_req *req = talloc_get_type_abort(private_data, + struct tevent_req); + struct tstream_bsd_writev_state *state = tevent_req_data(req, + struct tstream_bsd_writev_state); + struct tstream_context *stream = state->stream; + struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd); + ssize_t ret; + int err; + int _count; + bool ok, retry; + + if (bsds->error != 0) { + tevent_req_error(req, bsds->error); + return; + } + + ret = writev(bsds->fd, state->vector, state->count); + if (ret == 0) { + /* propagate end of file */ + bsds->error = EPIPE; + tevent_req_error(req, EPIPE); + return; + } + err = tsocket_bsd_error_from_errno(ret, errno, &retry); + if (retry) { + /* + * retry later... + */ + return; + } + if (err != 0) { + /* + * remember the error and don't + * allow further requests + */ + bsds->error = err; + } + if (tevent_req_error(req, err)) { + return; + } + + state->ret += ret; + + _count = state->count; /* tstream has size_t count, writev has int */ + ok = iov_advance(&state->vector, &_count, ret); + state->count = _count; + + if (!ok) { + tevent_req_error(req, EINVAL); + return; + } + + if (state->count > 0) { + /* + * we have more to write + */ + return; + } + + tevent_req_done(req); +} + +static int tstream_bsd_writev_recv(struct tevent_req *req, int *perrno) +{ + struct tstream_bsd_writev_state *state = tevent_req_data(req, + struct tstream_bsd_writev_state); + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = state->ret; + } + + tevent_req_received(req); + return ret; +} + +struct tstream_bsd_disconnect_state { + void *__dummy; +}; + +static struct tevent_req *tstream_bsd_disconnect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream) +{ + struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd); + struct tevent_req *req; + struct tstream_bsd_disconnect_state *state; + int ret; + int err; + bool dummy; + + req = tevent_req_create(mem_ctx, &state, + struct tstream_bsd_disconnect_state); + if (req == NULL) { + return NULL; + } + + if (bsds->fd == -1) { + tevent_req_error(req, ENOTCONN); + goto post; + } + + TALLOC_FREE(bsds->fde); + ret = close(bsds->fd); + bsds->fd = -1; + err = tsocket_bsd_error_from_errno(ret, errno, &dummy); + if (tevent_req_error(req, err)) { + goto post; + } + + tevent_req_done(req); +post: + tevent_req_post(req, ev); + return req; +} + +static int tstream_bsd_disconnect_recv(struct tevent_req *req, + int *perrno) +{ + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + + tevent_req_received(req); + return ret; +} + +static const struct tstream_context_ops tstream_bsd_ops = { + .name = "bsd", + + .pending_bytes = tstream_bsd_pending_bytes, + + .readv_send = tstream_bsd_readv_send, + .readv_recv = tstream_bsd_readv_recv, + + .writev_send = tstream_bsd_writev_send, + .writev_recv = tstream_bsd_writev_recv, + + .disconnect_send = tstream_bsd_disconnect_send, + .disconnect_recv = tstream_bsd_disconnect_recv, +}; + +static int tstream_bsd_destructor(struct tstream_bsd *bsds) +{ + TALLOC_FREE(bsds->fde); + if (bsds->fd != -1) { + close(bsds->fd); + bsds->fd = -1; + } + return 0; +} + +int _tstream_bsd_existing_socket(TALLOC_CTX *mem_ctx, + int fd, + struct tstream_context **_stream, + const char *location) +{ + struct tstream_context *stream; + struct tstream_bsd *bsds; + + stream = tstream_context_create(mem_ctx, + &tstream_bsd_ops, + &bsds, + struct tstream_bsd, + location); + if (!stream) { + return -1; + } + ZERO_STRUCTP(bsds); + bsds->fd = fd; + talloc_set_destructor(bsds, tstream_bsd_destructor); + + *_stream = stream; + return 0; +} + +struct tstream_bsd_connect_state { + int fd; + struct tevent_fd *fde; + struct tstream_conext *stream; + struct tsocket_address *local; +}; + +static int tstream_bsd_connect_destructor(struct tstream_bsd_connect_state *state) +{ + TALLOC_FREE(state->fde); + if (state->fd != -1) { + close(state->fd); + state->fd = -1; + } + + return 0; +} + +static void tstream_bsd_connect_fde_handler(struct tevent_context *ev, + struct tevent_fd *fde, + uint16_t flags, + void *private_data); + +static struct tevent_req *tstream_bsd_connect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + int sys_errno, + const struct tsocket_address *local, + const struct tsocket_address *remote) +{ + struct tevent_req *req; + struct tstream_bsd_connect_state *state; + struct samba_sockaddr *lbsda = + talloc_get_type_abort(local->private_data, + struct samba_sockaddr); + struct samba_sockaddr *lrbsda = NULL; + struct samba_sockaddr *rbsda = + talloc_get_type_abort(remote->private_data, + struct samba_sockaddr); + int ret; + bool do_bind = false; + bool do_reuseaddr = false; + bool do_ipv6only = false; + bool is_inet = false; + int sa_fam = lbsda->u.sa.sa_family; + + req = tevent_req_create(mem_ctx, &state, + struct tstream_bsd_connect_state); + if (!req) { + return NULL; + } + state->fd = -1; + state->fde = NULL; + + talloc_set_destructor(state, tstream_bsd_connect_destructor); + + /* give the wrappers a chance to report an error */ + if (sys_errno != 0) { + tevent_req_error(req, sys_errno); + goto post; + } + + switch (lbsda->u.sa.sa_family) { + case AF_UNIX: + if (lbsda->u.un.sun_path[0] != 0) { + do_reuseaddr = true; + do_bind = true; + } + break; + case AF_INET: + if (lbsda->u.in.sin_port != 0) { + do_reuseaddr = true; + do_bind = true; + } + if (lbsda->u.in.sin_addr.s_addr != INADDR_ANY) { + do_bind = true; + } + is_inet = true; + break; +#ifdef HAVE_IPV6 + case AF_INET6: + if (lbsda->u.in6.sin6_port != 0) { + do_reuseaddr = true; + do_bind = true; + } + if (memcmp(&in6addr_any, + &lbsda->u.in6.sin6_addr, + sizeof(in6addr_any)) != 0) { + do_bind = true; + } + is_inet = true; + do_ipv6only = true; + break; +#endif + default: + tevent_req_error(req, EINVAL); + goto post; + } + + if (!do_bind && is_inet) { + sa_fam = rbsda->u.sa.sa_family; + switch (sa_fam) { + case AF_INET: + do_ipv6only = false; + break; +#ifdef HAVE_IPV6 + case AF_INET6: + do_ipv6only = true; + break; +#endif + } + } + + if (is_inet) { + state->local = tsocket_address_create(state, + &tsocket_address_bsd_ops, + &lrbsda, + struct samba_sockaddr, + __location__ "bsd_connect"); + if (tevent_req_nomem(state->local, req)) { + goto post; + } + + ZERO_STRUCTP(lrbsda); + lrbsda->sa_socklen = sizeof(lrbsda->u.ss); +#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN + lrbsda->u.sa.sa_len = lrbsda->sa_socklen; +#endif + } + + state->fd = socket(sa_fam, SOCK_STREAM, 0); + if (state->fd == -1) { + tevent_req_error(req, errno); + goto post; + } + + state->fd = tsocket_bsd_common_prepare_fd(state->fd, true); + if (state->fd == -1) { + tevent_req_error(req, errno); + goto post; + } + +#ifdef HAVE_IPV6 + if (do_ipv6only) { + int val = 1; + + ret = setsockopt(state->fd, IPPROTO_IPV6, IPV6_V6ONLY, + (const void *)&val, sizeof(val)); + if (ret == -1) { + tevent_req_error(req, errno); + goto post; + } + } +#endif + + if (do_reuseaddr) { + int val = 1; + + ret = setsockopt(state->fd, SOL_SOCKET, SO_REUSEADDR, + (const void *)&val, sizeof(val)); + if (ret == -1) { + tevent_req_error(req, errno); + goto post; + } + } + + if (do_bind) { + ret = bind(state->fd, &lbsda->u.sa, lbsda->sa_socklen); + if (ret == -1) { + tevent_req_error(req, errno); + goto post; + } + } + + if (rbsda->u.sa.sa_family != sa_fam) { + tevent_req_error(req, EINVAL); + goto post; + } + + ret = connect(state->fd, &rbsda->u.sa, rbsda->sa_socklen); + if (ret == -1) { + if (errno == EINPROGRESS) { + goto async; + } + tevent_req_error(req, errno); + goto post; + } + + if (!state->local) { + tevent_req_done(req); + goto post; + } + + if (lrbsda != NULL) { + ret = getsockname(state->fd, + &lrbsda->u.sa, + &lrbsda->sa_socklen); + if (ret == -1) { + tevent_req_error(req, errno); + goto post; + } + } + + tevent_req_done(req); + goto post; + + async: + + /* + * Note for historic reasons TEVENT_FD_WRITE is not enough + * to get notified for POLLERR or EPOLLHUP even if they + * come together with POLLOUT. That means we need to + * use TEVENT_FD_READ in addition until we have + * TEVENT_FD_ERROR. + */ + state->fde = tevent_add_fd(ev, state, + state->fd, + TEVENT_FD_ERROR | TEVENT_FD_WRITE, + tstream_bsd_connect_fde_handler, + req); + if (tevent_req_nomem(state->fde, req)) { + goto post; + } + + return req; + + post: + tevent_req_post(req, ev); + return req; +} + +static void tstream_bsd_connect_fde_handler(struct tevent_context *ev, + struct tevent_fd *fde, + uint16_t flags, + void *private_data) +{ + struct tevent_req *req = talloc_get_type_abort(private_data, + struct tevent_req); + struct tstream_bsd_connect_state *state = tevent_req_data(req, + struct tstream_bsd_connect_state); + struct samba_sockaddr *lrbsda = NULL; + int ret; + int err; + bool retry; + + ret = samba_socket_sock_error(state->fd); + err = tsocket_bsd_error_from_errno(ret, errno, &retry); + if (retry) { + /* retry later */ + return; + } + if (tevent_req_error(req, err)) { + return; + } + + if (!state->local) { + tevent_req_done(req); + return; + } + + lrbsda = talloc_get_type_abort(state->local->private_data, + struct samba_sockaddr); + + ret = getsockname(state->fd, &lrbsda->u.sa, &lrbsda->sa_socklen); + if (ret == -1) { + tevent_req_error(req, errno); + return; + } + + tevent_req_done(req); +} + +static int tstream_bsd_connect_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + struct tstream_context **stream, + struct tsocket_address **local, + const char *location) +{ + struct tstream_bsd_connect_state *state = tevent_req_data(req, + struct tstream_bsd_connect_state); + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = _tstream_bsd_existing_socket(mem_ctx, + state->fd, + stream, + location); + if (ret == -1) { + *perrno = errno; + goto done; + } + TALLOC_FREE(state->fde); + state->fd = -1; + + if (local) { + *local = talloc_move(mem_ctx, &state->local); + } + } + +done: + tevent_req_received(req); + return ret; +} + +struct tevent_req * tstream_inet_tcp_connect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + const struct tsocket_address *local, + const struct tsocket_address *remote) +{ + struct samba_sockaddr *lbsda = + talloc_get_type_abort(local->private_data, + struct samba_sockaddr); + struct tevent_req *req; + int sys_errno = 0; + + switch (lbsda->u.sa.sa_family) { + case AF_INET: + break; +#ifdef HAVE_IPV6 + case AF_INET6: + break; +#endif + default: + sys_errno = EINVAL; + break; + } + + req = tstream_bsd_connect_send(mem_ctx, ev, sys_errno, local, remote); + + return req; +} + +int _tstream_inet_tcp_connect_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + struct tstream_context **stream, + struct tsocket_address **local, + const char *location) +{ + return tstream_bsd_connect_recv(req, perrno, + mem_ctx, stream, local, + location); +} + +struct tevent_req * tstream_unix_connect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + const struct tsocket_address *local, + const struct tsocket_address *remote) +{ + struct samba_sockaddr *lbsda = + talloc_get_type_abort(local->private_data, + struct samba_sockaddr); + struct tevent_req *req; + int sys_errno = 0; + + switch (lbsda->u.sa.sa_family) { + case AF_UNIX: + break; + default: + sys_errno = EINVAL; + break; + } + + req = tstream_bsd_connect_send(mem_ctx, ev, sys_errno, local, remote); + + return req; +} + +int _tstream_unix_connect_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + struct tstream_context **stream, + const char *location) +{ + return tstream_bsd_connect_recv(req, perrno, + mem_ctx, stream, NULL, + location); +} + +int _tstream_unix_socketpair(TALLOC_CTX *mem_ctx1, + struct tstream_context **_stream1, + TALLOC_CTX *mem_ctx2, + struct tstream_context **_stream2, + const char *location) +{ + int ret; + int fds[2]; + int fd1; + int fd2; + struct tstream_context *stream1 = NULL; + struct tstream_context *stream2 = NULL; + + ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fds); + if (ret == -1) { + return -1; + } + fd1 = fds[0]; + fd2 = fds[1]; + + fd1 = tsocket_bsd_common_prepare_fd(fd1, true); + if (fd1 == -1) { + int sys_errno = errno; + close(fd2); + errno = sys_errno; + return -1; + } + + fd2 = tsocket_bsd_common_prepare_fd(fd2, true); + if (fd2 == -1) { + int sys_errno = errno; + close(fd1); + errno = sys_errno; + return -1; + } + + ret = _tstream_bsd_existing_socket(mem_ctx1, + fd1, + &stream1, + location); + if (ret == -1) { + int sys_errno = errno; + close(fd1); + close(fd2); + errno = sys_errno; + return -1; + } + + ret = _tstream_bsd_existing_socket(mem_ctx2, + fd2, + &stream2, + location); + if (ret == -1) { + int sys_errno = errno; + talloc_free(stream1); + close(fd2); + errno = sys_errno; + return -1; + } + + *_stream1 = stream1; + *_stream2 = stream2; + return 0; +} + diff --git a/lib/tsocket/tsocket_guide.txt b/lib/tsocket/tsocket_guide.txt new file mode 100644 index 0000000..1b56056 --- /dev/null +++ b/lib/tsocket/tsocket_guide.txt @@ -0,0 +1,481 @@ + +Basic design of the tsocket abstraction +======================================= + +The tsocket abstraction is split into two +different kinds of communication interfaces. + +There is the "tstream_context" interface which abstracts +the communication through a bidirectional +byte stream between two endpoints. + +And there is the "tdgram_context" interface +which abstracts datagram based communication between any +number of endpoints. + +Both interfaces share the "tsocket_address" abstraction +for endpoint addresses. + +The whole library is based on the talloc(3) and 'tevent' libraries +and provides "tevent_req" based "foo_send()"/"foo_recv()" functions pairs +for all abstracted methods that need to be async. + +The tsocket_address abstraction +=============================== + +A tsocket_address represents a generic socket endpoint. +It behaves like an abstract class, therefore it has no direct constructor. +Constructors are described in later sections of this document. + +A function to get the string representation of an endpoint for debugging is +available but callers SHOULD NOT try to parse this string. To get more +details, callers should use getter methods of the specific tsocket_address +implementation. + + char *tsocket_address_string(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx); + +A function to create a copy of the tsocket_address is also available. +This is useful before doing modifications to a socket +via additional methods of the specific tsocket_address implementation. + + struct tsocket_address *tsocket_address_copy(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx); + +The tdgram_context abstraction +============================== + +The tdgram_context is like an abstract class for datagram +based sockets. The interface provides async 'tevent_req' based +functions similar to recvfrom(2)/sendto(2)/close(2) syscalls. + +The tdgram_recvfrom_send() method can be called to ask for the +next available datagram from the abstracted tdgram_context. +It returns a 'tevent_req' handle, where the caller can register +a callback with tevent_req_set_callback(). The callback is triggered +when a datagram is available or an error occurs. + +The callback is then supposed to get the result by calling +tdgram_recvfrom_recv() on the 'tevent_req'. It returns -1 +and sets '*perrno' to the actual 'errno' on failure. +Otherwise it returns the length of the datagram +(0 is never returned!). '*buf' will contain the buffer of the +datagram and '*src' the abstracted tsocket_address of the sender +of the received datagram. + +The caller can only have one outstanding tdgram_recvfrom_send() +at a time otherwise the caller will get '*perrno = EBUSY'. + + struct tevent_req *tdgram_recvfrom_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram); + + ssize_t tdgram_recvfrom_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + uint8_t **buf, + struct tsocket_address **src); + +The tdgram_sendto_send() method can be called to send a +datagram (specified by a buf/len) to a destination endpoint +(specified by dst). It is not allowed for len to be 0. +It returns a 'tevent_req' handle, where the caller can register a +callback with tevent_req_set_callback(). The callback is triggered +when the specific implementation (thinks it) +has delivered the datagram to the "wire". + +The callback is then supposed to get the result by calling +tdgram_sendto_recv() on the 'tevent_req'. It returns -1 +and sets '*perrno' to the actual 'errno' on failure. +Otherwise it returns the length of the datagram +(0 is never returned!). + +The caller can only have one outstanding tdgram_sendto_send() +at a time otherwise the caller will get '*perrno = EBUSY'. + + struct tevent_req *tdgram_sendto_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram, + const uint8_t *buf, size_t len, + const struct tsocket_address *dst); + + ssize_t tdgram_sendto_recv(struct tevent_req *req, + int *perrno); + +The tdgram_disconnect_send() method should be used to normally +shutdown/close the abstracted socket. + +The caller should make sure there are no outstanding tdgram_recvfrom_send() +and tdgram_sendto_send() calls otherwise the caller will get '*perrno = EBUSY'. + +Note: you can always use talloc_free(tdgram) to cleanup the resources +of the tdgram_context on a fatal error. + + struct tevent_req *tdgram_disconnect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram); + + int tdgram_disconnect_recv(struct tevent_req *req, + int *perrno); + +The tstream_context abstraction +=============================== + +A tstream_context is like an abstract class for stream +based sockets. The interface provides async 'tevent_req' based +functions similar to the readv(2)/writev(2)/close(2) syscalls. + +The tstream_pending_bytes() function is able to report how many bytes of +the incoming stream have been received but have not been consumed yet. +It returns -1 and sets 'errno' on failure. +Otherwise it returns the number of unconsumed bytes (it can return 0!). + + ssize_t tstream_pending_bytes(struct tstream_context *stream); + +The tstream_readv_send() method can be called to read a +specific amount of bytes from the stream into the buffers +of the given iovec vector. The caller has to preallocate the buffers +in the iovec vector. The caller might need to use +tstream_pending_bytes() if the protocol does not have a fixed pdu header +containing the pdu size. tstream_readv_send() returns a 'tevent_req' handle, +where the caller can register a callback with tevent_req_set_callback(). +The callback is triggered when all iovec buffers are completely +filled with bytes from the socket or an error occurs. + +The callback is then supposed to get the result by calling +tstream_readv_recv() on the 'tevent_req'. It returns -1 +and sets '*perrno' to the actual 'errno' on failure. +Otherwise it returns the total number of bytes received +(0 is never returned!). + +The caller can only have one outstanding tstream_readv_send() +at a time otherwise the caller will get *perrno = EBUSY. + + struct tevent_req *tstream_readv_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct iovec *vector, + size_t count); + + int tstream_readv_recv(struct tevent_req *req, + int *perrno); + +The tstream_writev_send() method can be called to write +buffers in the given iovec vector into the stream socket. +It is invalid to pass an empty vector. +tstream_writev_send() returns a 'tevent_req' handle, +where the caller can register a callback with tevent_req_set_callback(). +The callback is triggered when the specific implementation (thinks it) +has delivered the all buffers to the "wire". + +The callback is then supposed to get the result by calling +tstream_writev_recv() on the 'tevent_req'. It returns -1 +and sets '*perrno' to the actual 'errno' on failure. +Otherwise it returns the total amount of bytes sent +(0 is never returned!). + +The caller can only have one outstanding tstream_writev_send() +at a time otherwise the caller will get '*perrno = EBUSY'. + + struct tevent_req *tstream_writev_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + const struct iovec *vector, + size_t count); + + int tstream_writev_recv(struct tevent_req *req, + int *perrno); + +The tstream_disconnect_send() method should normally be used to +shutdown/close the abstracted socket. + +The caller should make sure there are no outstanding tstream_readv_send() +and tstream_writev_send() calls otherwise the caller will get '*perrno = EBUSY'. + +Note: you can always use talloc_free(tstream) to cleanup the resources +of the tstream_context on a fatal error. + + struct tevent_req *tstream_disconnect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream); + + int tstream_disconnect_recv(struct tevent_req *req, + int *perrno); + +PDU receive helper functions +============================ + +In order to simplify the job, for callers that want to implement +a function to receive a full PDU with a single async function pair, +some helper functions are provided. + +The caller can use the tstream_readv_pdu_send() function +to ask for the next available PDU on the abstracted tstream_context. +The caller needs to provide a "next_vector" function and a private +state for this function. The tstream_readv_pdu engine will ask +the next_vector function for the next iovec vector to be used. +There is a tstream_readv_send/recv pair for each vector returned +by the next_vector function. If the next_vector function detects +it received a full pdu, it returns an empty vector. The callback +of the tevent_req (returned by tstream_readv_pdu_send()) is triggered. +Note: the buffer allocation is completely up to the next_vector function +and its private state. + +See the 'dcerpc_read_ncacn_packet_send/recv' functions in Samba as an +example. + + typedef int (*tstream_readv_pdu_next_vector_t)(struct tstream_context *stream, + void *private_data, + TALLOC_CTX *mem_ctx, + struct iovec **vector, + size_t *count); + + struct tevent_req *tstream_readv_pdu_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + tstream_readv_pdu_next_vector_t next_vector_fn, + void *next_vector_private); + + int tstream_readv_pdu_recv(struct tevent_req *req, int *perrno); + +Async 'tevent_queue' based helper functions +=========================================== + +In some cases, the caller does not care about the IO ordering on the +abstracted socket. +(Remember at the low level there is always only one IO in a specific + direction allowed, only one tdgram_sendto_send() at a time). + +Some helpers that use 'tevent_queue' are available to simplify handling +multiple IO requests. The functions just get a 'queue' argument and +internally serialize all operations. + + struct tevent_req *tdgram_sendto_queue_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram, + struct tevent_queue *queue, + const uint8_t *buf, + size_t len, + struct tsocket_address *dst); + + ssize_t tdgram_sendto_queue_recv(struct tevent_req *req, int *perrno); + + struct tevent_req *tstream_readv_pdu_queue_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct tevent_queue *queue, + tstream_readv_pdu_next_vector_t next_vector_fn, + void *next_vector_private); + + int tstream_readv_pdu_queue_recv(struct tevent_req *req, int *perrno); + + struct tevent_req *tstream_writev_queue_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct tevent_queue *queue, + const struct iovec *vector, + size_t count); + + int tstream_writev_queue_recv(struct tevent_req *req, int *perrno); + +BSD sockets: ipv4, ipv6 and unix +================================ + +The main tsocket library comes with implementations +for BSD style ipv4, ipv6 and unix sockets. + +You can use the tsocket_address_inet_from_strings() +function to create a tsocket_address for ipv4 and ipv6 +endpoint addresses. "family" can be "ipv4", "ipv6" or "ip". +With "ip" it autodetects "ipv4" or "ipv6" based on the +"addr_string" string. "addr_string" must be a valid +ip address string based on the selected family +(dns names are not allowed!). But it is valid to pass NULL, +which gets mapped to "0.0.0.0" or "::". +It returns -1 and sets errno on error. Otherwise it returns 0. + + int tsocket_address_inet_from_strings(TALLOC_CTX *mem_ctx, + const char *family, + const char *addr_string, + uint16_t port, + struct tsocket_address **addr); + +To get the ip address string of an existing 'inet' tsocket_address +you can use the tsocket_address_inet_addr_string() function. +It will return NULL and set errno to EINVAL if the tsocket_address +does not represent an ipv4 or ipv6 endpoint address. + + char *tsocket_address_inet_addr_string(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx); + +To get the port number of an existing 'inet' tsocket_address +you can use the tsocket_address_inet_port() function. +It will return 0 and set errno to EINVAL if the tsocket_address +does not represent an ipv4 or ipv6 endpoint address. + + uint16_t tsocket_address_inet_port(const struct tsocket_address *addr); + +To set the port number of an existing 'inet' tsocket_address +you can use the tsocket_address_inet_set_port() function. +It will return -1 and set errno to EINVAL if the tsocket_address +does not represent an ipv4 or ipv6 endpoint address. +It returns 0 on success. + + int tsocket_address_inet_set_port(struct tsocket_address *addr, + uint16_t port); + +You can use the tsocket_address_unix_from_path() +function to create a tsocket_address for unix domain +endpoint addresses. "path" is the filesystem path +(NULL will map ""). If the path is longer than +the low level kernel supports the function will +return -1 and set errno to ENAMETOOLONG. +On success it returns 0. + + int tsocket_address_unix_from_path(TALLOC_CTX *mem_ctx, + const char *path, + struct tsocket_address **addr); + +To get the path of a 'unix' tsocket_address +you can use the tsocket_address_unix_path() function. +It will return NULL and set errno to EINVAL if the tsocket_address +does not represent a unix domain endpoint path. + + char *tsocket_address_unix_path(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx); + +You can use tdgram_inet_udp_socket() to create a tdgram_context +for ipv4 or ipv6 UDP communication. "local_address" has to be +an 'inet' tsocket_address and it has to represent the local +endpoint. "remote_address" can be NULL or an 'inet' tsocket_address +presenting a remote endpoint. It returns -1 ans sets errno on error +and it returns 0 on success. + + int tdgram_inet_udp_socket(const struct tsocket_address *local_address, + const struct tsocket_address *remote_address, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram); + +You can use tdgram_unix_socket() to create a tdgram_context +for unix domain datagram communication. "local_address" has to be +an 'unix' tsocket_address and it has to represent the local +endpoint. "remote_address" can be NULL or an 'unix' tsocket_address +presenting a remote endpoint. It returns -1 ans sets errno on error +and it returns 0 on success. + + int tdgram_unix_socket(const struct tsocket_address *local, + const struct tsocket_address *remote, + TALLOC_CTX *mem_ctx, + struct tdgram_context **dgram); + +You can use tstream_inet_tcp_connect_send to asynchronously +connect to a remote ipv4 or ipv6 TCP endpoint and create a +tstream_context for the stream based communication. "local_address" has to be +an 'inet' tsocket_address and it has to represent the local +endpoint. "remote_address" has to be an 'inet' tsocket_address +presenting a remote endpoint. It returns a 'tevent_req' handle, +where the caller can register a callback with tevent_req_set_callback(). +The callback is triggered when a socket is connected and ready for IO +or an error happened. + +The callback is then supposed to get the result by calling +tstream_inet_tcp_connect_recv() on the 'tevent_req'. It returns -1 +and sets '*perrno' to the actual 'errno' on failure. +It returns 0 on success and returns the new tstream_context +in '*stream'. + + struct tevent_req *tstream_inet_tcp_connect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + const struct tsocket_address *local_address, + const struct tsocket_address *remote_address); + + int tstream_inet_tcp_connect_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + struct tstream_context **stream); + +You can use tstream_unix_connect_send to asynchronously +connect to a unix domain endpoint and create a +tstream_context for the stream based communication. +"local_address" has to be an 'unix' tsocket_address and +it has to represent the local endpoint. "remote_address" +has to be an 'inet' tsocket_address presenting a remote endpoint. +It returns a 'tevent_req' handle, where the caller can register +a callback with tevent_req_set_callback(). The callback is +triggered when a socket is connected and ready for IO +or an error happened. + +The callback is then supposed to get the result by calling +tstream_unix_connect_recv() on the 'tevent_req'. It returns -1 +and sets '*perrno' to the actual 'errno' on failure. +It returns 0 on success and returns the new tstream_context +in '*stream'. + + struct tevent_req *tstream_unix_connect_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + const struct tsocket_address *local, + const struct tsocket_address *remote); + + int _tstream_unix_connect_recv(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + struct tstream_context **stream); + +You can use tstream_unix_socketpair to create two connected +'unix' tsocket_contexts for the stream based communication. +It returns -1 and sets errno on error and it returns 0 on +success. + + int tstream_unix_socketpair(TALLOC_CTX *mem_ctx1, + struct tstream_context **stream1, + TALLOC_CTX *mem_ctx2, + struct tstream_context **stream2); + +In some situations, it is needed to create a tsocket_address from +a given 'struct sockaddr'. You can use tsocket_address_bsd_from_sockaddr() +for that. This should only be used if really needed, because of +already existing fixed APIs. Only AF_INET, AF_INET6 and AF_UNIX +sockets are allowed. The function returns -1 and sets errno on error. +Otherwise it returns 0. + + int tsocket_address_bsd_from_sockaddr(TALLOC_CTX *mem_ctx, + struct sockaddr *sa, + socklen_t sa_socklen, + struct tsocket_address **addr); + +In some situations, it is needed to get a 'struct sockaddr' from a +given tsocket_address . You can use tsocket_address_bsd_sockaddr() +for that. This should only be used if really needed. Only AF_INET, +AF_INET6 and AF_UNIX are supported. It returns the size of '*sa' on +success, otherwise it returns -1 and sets 'errno'. + + ssize_t tsocket_address_bsd_sockaddr(const struct tsocket_address *addr, + struct sockaddr *sa, + socklen_t sa_socklen); + +In some situations, it is needed to wrap existing file descriptors +into the tstream abstraction. You can use tstream_bsd_existing_socket() +for that. But you should read the tsocket_bsd.c code and unterstand it +in order use this function. E.g. the fd has to be non blocking already. +It will return -1 and set errno on error. Otherwise it returns 0 +and sets '*stream' to point to the new tstream_context. + + int tstream_bsd_existing_socket(TALLOC_CTX *mem_ctx, + int fd, + struct tstream_context **stream); + +Virtual Sockets +=============== + +The abstracted layout of tdgram_context and tstream_context +allow implementations around virtual sockets for encrypted tunnels +(like TLS, SASL or GSSAPI) or named pipes over smb. + +Named Pipe Auth (NPA) Sockets +============================= + +Samba has an implementation to abstract named pipes over smb +(within the server side). See libcli/named_pipe_auth/npa_tstream.[ch] +for the core code. The current callers are located in source4/ntvfs/ipc/vfs_ipc.c +and source4/rpc_server/service_rpc.c for the users. + diff --git a/lib/tsocket/tsocket_helpers.c b/lib/tsocket/tsocket_helpers.c new file mode 100644 index 0000000..c7ad531 --- /dev/null +++ b/lib/tsocket/tsocket_helpers.c @@ -0,0 +1,559 @@ +/* + Unix SMB/CIFS implementation. + + Copyright (C) Stefan Metzmacher 2009 + + ** NOTE! The following LGPL license applies to the tsocket + ** library. This does NOT imply that all of Samba is released + ** under the LGPL + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see <http://www.gnu.org/licenses/>. +*/ + +#include "replace.h" +#include "system/filesys.h" +#include "tsocket.h" +#include "tsocket_internal.h" + +struct tdgram_sendto_queue_state { + /* this structs are owned by the caller */ + struct { + struct tevent_context *ev; + struct tdgram_context *dgram; + const uint8_t *buf; + size_t len; + const struct tsocket_address *dst; + } caller; + ssize_t ret; +}; + +static void tdgram_sendto_queue_trigger(struct tevent_req *req, + void *private_data); +static void tdgram_sendto_queue_done(struct tevent_req *subreq); + +struct tevent_req *tdgram_sendto_queue_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram, + struct tevent_queue *queue, + const uint8_t *buf, + size_t len, + struct tsocket_address *dst) +{ + struct tevent_req *req; + struct tdgram_sendto_queue_state *state; + struct tevent_queue_entry *e; + + req = tevent_req_create(mem_ctx, &state, + struct tdgram_sendto_queue_state); + if (!req) { + return NULL; + } + + state->caller.ev = ev; + state->caller.dgram = dgram; + state->caller.buf = buf; + state->caller.len = len; + state->caller.dst = dst; + state->ret = -1; + + /* + * we use tevent_queue_add_optimize_empty() with allow_direct + * in order to optimize for the empty queue case. + */ + e = tevent_queue_add_optimize_empty( + queue, + ev, + req, + tdgram_sendto_queue_trigger, + NULL); + if (tevent_req_nomem(e, req)) { + return tevent_req_post(req, ev); + } + if (!tevent_req_is_in_progress(req)) { + return tevent_req_post(req, ev); + } + + return req; +} + +static void tdgram_sendto_queue_trigger(struct tevent_req *req, + void *private_data) +{ + struct tdgram_sendto_queue_state *state = tevent_req_data(req, + struct tdgram_sendto_queue_state); + struct tevent_req *subreq; + + subreq = tdgram_sendto_send(state, + state->caller.ev, + state->caller.dgram, + state->caller.buf, + state->caller.len, + state->caller.dst); + if (tevent_req_nomem(subreq, req)) { + return; + } + tevent_req_set_callback(subreq, tdgram_sendto_queue_done, req); +} + +static void tdgram_sendto_queue_done(struct tevent_req *subreq) +{ + struct tevent_req *req = tevent_req_callback_data(subreq, + struct tevent_req); + struct tdgram_sendto_queue_state *state = tevent_req_data(req, + struct tdgram_sendto_queue_state); + ssize_t ret; + int sys_errno; + + ret = tdgram_sendto_recv(subreq, &sys_errno); + talloc_free(subreq); + if (ret == -1) { + tevent_req_error(req, sys_errno); + return; + } + state->ret = ret; + + tevent_req_done(req); +} + +ssize_t tdgram_sendto_queue_recv(struct tevent_req *req, int *perrno) +{ + struct tdgram_sendto_queue_state *state = tevent_req_data(req, + struct tdgram_sendto_queue_state); + ssize_t ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = state->ret; + } + + tevent_req_received(req); + return ret; +} + +struct tstream_readv_pdu_state { + /* this structs are owned by the caller */ + struct { + struct tevent_context *ev; + struct tstream_context *stream; + tstream_readv_pdu_next_vector_t next_vector_fn; + void *next_vector_private; + } caller; + + /* + * Each call to the callback resets iov and count + * the callback allocated the iov as child of our state, + * that means we are allowed to modify and free it. + * + * we should call the callback every time we filled the given + * vector and ask for a new vector. We return if the callback + * ask for 0 bytes. + */ + struct iovec *vector; + size_t count; + + /* + * the total number of bytes we read, + * the return value of the _recv function + */ + int total_read; +}; + +static void tstream_readv_pdu_ask_for_next_vector(struct tevent_req *req); +static void tstream_readv_pdu_readv_done(struct tevent_req *subreq); + +struct tevent_req *tstream_readv_pdu_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + tstream_readv_pdu_next_vector_t next_vector_fn, + void *next_vector_private) +{ + struct tevent_req *req; + struct tstream_readv_pdu_state *state; + + req = tevent_req_create(mem_ctx, &state, + struct tstream_readv_pdu_state); + if (!req) { + return NULL; + } + + state->caller.ev = ev; + state->caller.stream = stream; + state->caller.next_vector_fn = next_vector_fn; + state->caller.next_vector_private = next_vector_private; + + state->vector = NULL; + state->count = 0; + state->total_read = 0; + + tstream_readv_pdu_ask_for_next_vector(req); + if (!tevent_req_is_in_progress(req)) { + goto post; + } + + return req; + + post: + return tevent_req_post(req, ev); +} + +static void tstream_readv_pdu_ask_for_next_vector(struct tevent_req *req) +{ + struct tstream_readv_pdu_state *state = tevent_req_data(req, + struct tstream_readv_pdu_state); + int ret; + size_t to_read = 0; + size_t i; + struct tevent_req *subreq; + bool optimize = false; + bool save_optimize = false; + + if (state->count > 0) { + /* + * This is not the first time we asked for a vector, + * which means parts of the pdu already arrived. + * + * In this case it make sense to enable + * a syscall/performance optimization if the + * low level tstream implementation supports it. + */ + optimize = true; + } + + TALLOC_FREE(state->vector); + state->count = 0; + + ret = state->caller.next_vector_fn(state->caller.stream, + state->caller.next_vector_private, + state, &state->vector, &state->count); + if (ret == -1) { + tevent_req_error(req, errno); + return; + } + + if (state->count == 0) { + tevent_req_done(req); + return; + } + + for (i=0; i < state->count; i++) { + size_t tmp = to_read; + tmp += state->vector[i].iov_len; + + if (tmp < to_read) { + tevent_req_error(req, EMSGSIZE); + return; + } + + to_read = tmp; + } + + /* + * this is invalid the next vector function should have + * reported count == 0. + */ + if (to_read == 0) { + tevent_req_error(req, EINVAL); + return; + } + + if (state->total_read + to_read < state->total_read) { + tevent_req_error(req, EMSGSIZE); + return; + } + + if (optimize) { + /* + * If the low level stream is a bsd socket + * we will get syscall optimization. + * + * If it is not a bsd socket + * tstream_bsd_optimize_readv() just returns. + */ + save_optimize = tstream_bsd_optimize_readv(state->caller.stream, + true); + } + subreq = tstream_readv_send(state, + state->caller.ev, + state->caller.stream, + state->vector, + state->count); + if (optimize) { + tstream_bsd_optimize_readv(state->caller.stream, + save_optimize); + } + if (tevent_req_nomem(subreq, req)) { + return; + } + tevent_req_set_callback(subreq, tstream_readv_pdu_readv_done, req); +} + +static void tstream_readv_pdu_readv_done(struct tevent_req *subreq) +{ + struct tevent_req *req = tevent_req_callback_data(subreq, + struct tevent_req); + struct tstream_readv_pdu_state *state = tevent_req_data(req, + struct tstream_readv_pdu_state); + int ret; + int sys_errno; + + ret = tstream_readv_recv(subreq, &sys_errno); + TALLOC_FREE(subreq); + if (ret == -1) { + tevent_req_error(req, sys_errno); + return; + } + + state->total_read += ret; + + /* ask the callback for a new vector we should fill */ + tstream_readv_pdu_ask_for_next_vector(req); +} + +int tstream_readv_pdu_recv(struct tevent_req *req, int *perrno) +{ + struct tstream_readv_pdu_state *state = tevent_req_data(req, + struct tstream_readv_pdu_state); + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = state->total_read; + } + + tevent_req_received(req); + return ret; +} + +struct tstream_readv_pdu_queue_state { + /* this structs are owned by the caller */ + struct { + struct tevent_context *ev; + struct tstream_context *stream; + tstream_readv_pdu_next_vector_t next_vector_fn; + void *next_vector_private; + } caller; + int ret; +}; + +static void tstream_readv_pdu_queue_trigger(struct tevent_req *req, + void *private_data); +static void tstream_readv_pdu_queue_done(struct tevent_req *subreq); + +struct tevent_req *tstream_readv_pdu_queue_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct tevent_queue *queue, + tstream_readv_pdu_next_vector_t next_vector_fn, + void *next_vector_private) +{ + struct tevent_req *req; + struct tstream_readv_pdu_queue_state *state; + struct tevent_queue_entry *e; + + req = tevent_req_create(mem_ctx, &state, + struct tstream_readv_pdu_queue_state); + if (!req) { + return NULL; + } + + state->caller.ev = ev; + state->caller.stream = stream; + state->caller.next_vector_fn = next_vector_fn; + state->caller.next_vector_private = next_vector_private; + state->ret = -1; + + /* + * we use tevent_queue_add_optimize_empty() with allow_direct + * in order to optimize for the empty queue case. + */ + e = tevent_queue_add_optimize_empty( + queue, + ev, + req, + tstream_readv_pdu_queue_trigger, + NULL); + if (tevent_req_nomem(e, req)) { + return tevent_req_post(req, ev); + } + if (!tevent_req_is_in_progress(req)) { + return tevent_req_post(req, ev); + } + + return req; +} + +static void tstream_readv_pdu_queue_trigger(struct tevent_req *req, + void *private_data) +{ + struct tstream_readv_pdu_queue_state *state = tevent_req_data(req, + struct tstream_readv_pdu_queue_state); + struct tevent_req *subreq; + + subreq = tstream_readv_pdu_send(state, + state->caller.ev, + state->caller.stream, + state->caller.next_vector_fn, + state->caller.next_vector_private); + if (tevent_req_nomem(subreq, req)) { + return; + } + tevent_req_set_callback(subreq, tstream_readv_pdu_queue_done ,req); +} + +static void tstream_readv_pdu_queue_done(struct tevent_req *subreq) +{ + struct tevent_req *req = tevent_req_callback_data(subreq, + struct tevent_req); + struct tstream_readv_pdu_queue_state *state = tevent_req_data(req, + struct tstream_readv_pdu_queue_state); + int ret; + int sys_errno; + + ret = tstream_readv_pdu_recv(subreq, &sys_errno); + talloc_free(subreq); + if (ret == -1) { + tevent_req_error(req, sys_errno); + return; + } + state->ret = ret; + + tevent_req_done(req); +} + +int tstream_readv_pdu_queue_recv(struct tevent_req *req, int *perrno) +{ + struct tstream_readv_pdu_queue_state *state = tevent_req_data(req, + struct tstream_readv_pdu_queue_state); + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = state->ret; + } + + tevent_req_received(req); + return ret; +} + +struct tstream_writev_queue_state { + /* this structs are owned by the caller */ + struct { + struct tevent_context *ev; + struct tstream_context *stream; + const struct iovec *vector; + size_t count; + } caller; + int ret; +}; + +static void tstream_writev_queue_trigger(struct tevent_req *req, + void *private_data); +static void tstream_writev_queue_done(struct tevent_req *subreq); + +struct tevent_req *tstream_writev_queue_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct tevent_queue *queue, + const struct iovec *vector, + size_t count) +{ + struct tevent_req *req; + struct tstream_writev_queue_state *state; + struct tevent_queue_entry *e; + + req = tevent_req_create(mem_ctx, &state, + struct tstream_writev_queue_state); + if (!req) { + return NULL; + } + + state->caller.ev = ev; + state->caller.stream = stream; + state->caller.vector = vector; + state->caller.count = count; + state->ret = -1; + + /* + * we use tevent_queue_add_optimize_empty() with allow_direct + * in order to optimize for the empty queue case. + */ + e = tevent_queue_add_optimize_empty( + queue, + ev, + req, + tstream_writev_queue_trigger, + NULL); + if (tevent_req_nomem(e, req)) { + return tevent_req_post(req, ev); + } + if (!tevent_req_is_in_progress(req)) { + return tevent_req_post(req, ev); + } + + return req; +} + +static void tstream_writev_queue_trigger(struct tevent_req *req, + void *private_data) +{ + struct tstream_writev_queue_state *state = tevent_req_data(req, + struct tstream_writev_queue_state); + struct tevent_req *subreq; + + subreq = tstream_writev_send(state, + state->caller.ev, + state->caller.stream, + state->caller.vector, + state->caller.count); + if (tevent_req_nomem(subreq, req)) { + return; + } + tevent_req_set_callback(subreq, tstream_writev_queue_done ,req); +} + +static void tstream_writev_queue_done(struct tevent_req *subreq) +{ + struct tevent_req *req = tevent_req_callback_data(subreq, + struct tevent_req); + struct tstream_writev_queue_state *state = tevent_req_data(req, + struct tstream_writev_queue_state); + int ret; + int sys_errno; + + ret = tstream_writev_recv(subreq, &sys_errno); + talloc_free(subreq); + if (ret == -1) { + tevent_req_error(req, sys_errno); + return; + } + state->ret = ret; + + tevent_req_done(req); +} + +int tstream_writev_queue_recv(struct tevent_req *req, int *perrno) +{ + struct tstream_writev_queue_state *state = tevent_req_data(req, + struct tstream_writev_queue_state); + int ret; + + ret = tsocket_simple_int_recv(req, perrno); + if (ret == 0) { + ret = state->ret; + } + + tevent_req_received(req); + return ret; +} + diff --git a/lib/tsocket/tsocket_internal.h b/lib/tsocket/tsocket_internal.h new file mode 100644 index 0000000..154b2ce --- /dev/null +++ b/lib/tsocket/tsocket_internal.h @@ -0,0 +1,144 @@ +/* + Unix SMB/CIFS implementation. + + Copyright (C) Stefan Metzmacher 2009 + + ** NOTE! The following LGPL license applies to the tsocket + ** library. This does NOT imply that all of Samba is released + ** under the LGPL + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef _TSOCKET_INTERNAL_H +#define _TSOCKET_INTERNAL_H + +#include <unistd.h> +#include <sys/uio.h> + +struct tsocket_address_ops { + const char *name; + + char *(*string)(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx); + + struct tsocket_address *(*copy)(const struct tsocket_address *addr, + TALLOC_CTX *mem_ctx, + const char *location); +}; + +struct tsocket_address { + const char *location; + const struct tsocket_address_ops *ops; + + void *private_data; +}; + +struct tsocket_address *_tsocket_address_create(TALLOC_CTX *mem_ctx, + const struct tsocket_address_ops *ops, + void *pstate, + size_t psize, + const char *type, + const char *location); +#define tsocket_address_create(mem_ctx, ops, state, type, location) \ + _tsocket_address_create(mem_ctx, ops, state, sizeof(type), \ + #type, location) + +struct tdgram_context_ops { + const char *name; + + struct tevent_req *(*recvfrom_send)(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram); + ssize_t (*recvfrom_recv)(struct tevent_req *req, + int *perrno, + TALLOC_CTX *mem_ctx, + uint8_t **buf, + struct tsocket_address **src); + + struct tevent_req *(*sendto_send)(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram, + const uint8_t *buf, size_t len, + const struct tsocket_address *dst); + ssize_t (*sendto_recv)(struct tevent_req *req, + int *perrno); + + struct tevent_req *(*disconnect_send)(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tdgram_context *dgram); + int (*disconnect_recv)(struct tevent_req *req, + int *perrno); +}; + +struct tdgram_context *_tdgram_context_create(TALLOC_CTX *mem_ctx, + const struct tdgram_context_ops *ops, + void *pstate, + size_t psize, + const char *type, + const char *location); +#define tdgram_context_create(mem_ctx, ops, state, type, location) \ + _tdgram_context_create(mem_ctx, ops, state, sizeof(type), \ + #type, location) + +void *_tdgram_context_data(struct tdgram_context *dgram); +#define tdgram_context_data(_req, _type) \ + talloc_get_type_abort(_tdgram_context_data(_req), _type) + +struct tstream_context_ops { + const char *name; + + ssize_t (*pending_bytes)(struct tstream_context *stream); + + struct tevent_req *(*readv_send)(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + struct iovec *vector, + size_t count); + int (*readv_recv)(struct tevent_req *req, + int *perrno); + + struct tevent_req *(*writev_send)(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream, + const struct iovec *vector, + size_t count); + int (*writev_recv)(struct tevent_req *req, + int *perrno); + + struct tevent_req *(*disconnect_send)(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct tstream_context *stream); + int (*disconnect_recv)(struct tevent_req *req, + int *perrno); +}; + +struct tstream_context *_tstream_context_create(TALLOC_CTX *mem_ctx, + const struct tstream_context_ops *ops, + void *pstate, + size_t psize, + const char *type, + const char *location); +#define tstream_context_create(mem_ctx, ops, state, type, location) \ + _tstream_context_create(mem_ctx, ops, state, sizeof(type), \ + #type, location) + +void *_tstream_context_data(struct tstream_context *stream); +#define tstream_context_data(_req, _type) \ + talloc_get_type_abort(_tstream_context_data(_req), _type) + +int tsocket_simple_int_recv(struct tevent_req *req, int *perrno); + +#endif /* _TSOCKET_H */ + diff --git a/lib/tsocket/wscript b/lib/tsocket/wscript new file mode 100644 index 0000000..fa284a7 --- /dev/null +++ b/lib/tsocket/wscript @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +def configure(conf): + conf.CHECK_CODE(''' + #include <netinet/tcp.h> + int main(void) { return TCP_USER_TIMEOUT; } + ''', + 'HAVE_TCP_USER_TIMEOUT', + addmain=False, + msg='Checking for TCP_USER_TIMEOUT') + +def build(bld): + bld.SAMBA_SUBSYSTEM( + 'LIBTSOCKET', + source='tsocket.c tsocket_helpers.c tsocket_bsd.c', + public_deps='talloc tevent iov_buf socket-blocking', + public_headers='tsocket.h tsocket_internal.h' + ) + + bld.SAMBA_BINARY( + 'test_tsocket_bsd_addr', + source='tests/test_bsd_addr.c', + deps='cmocka replace LIBTSOCKET', + local_include=False, + for_selftest=True + ) + + bld.SAMBA_BINARY( + 'test_tstream', + source='tests/test_tstream.c tests/socketpair_tcp.c', + deps='cmocka replace LIBTSOCKET', + local_include=False, + enabled=bld.CONFIG_SET('HAVE_TCP_USER_TIMEOUT'), + for_selftest=True + ) + |